2016-11-28 17:49:40 +00:00
|
|
|
#
|
|
|
|
# (c) 2016 Red Hat Inc.
|
|
|
|
#
|
|
|
|
# This file is part of Ansible
|
|
|
|
#
|
|
|
|
# Ansible is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# Ansible is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
from __future__ import (absolute_import, division, print_function)
|
|
|
|
__metaclass__ = type
|
|
|
|
|
|
|
|
import json
|
2017-05-12 16:13:51 +00:00
|
|
|
import logging
|
|
|
|
import re
|
2016-11-28 17:49:40 +00:00
|
|
|
import signal
|
2017-05-12 16:13:51 +00:00
|
|
|
import socket
|
2017-02-20 20:37:14 +00:00
|
|
|
import traceback
|
2017-06-06 08:26:25 +00:00
|
|
|
|
2017-05-12 16:13:51 +00:00
|
|
|
from collections import Sequence
|
2016-11-28 17:49:40 +00:00
|
|
|
|
2017-03-29 19:12:18 +00:00
|
|
|
from ansible import constants as C
|
2016-11-28 17:49:40 +00:00
|
|
|
from ansible.errors import AnsibleConnectionFailure
|
2017-05-24 14:10:38 +00:00
|
|
|
from ansible.module_utils.six import BytesIO, binary_type
|
2017-05-12 16:13:51 +00:00
|
|
|
from ansible.module_utils._text import to_bytes, to_text
|
2017-08-15 20:38:59 +00:00
|
|
|
from ansible.plugins.loader import cliconf_loader, terminal_loader
|
2016-11-28 17:49:40 +00:00
|
|
|
from ansible.plugins.connection.paramiko_ssh import Connection as _Connection
|
2017-06-06 08:26:25 +00:00
|
|
|
from ansible.utils.jsonrpc import Rpc
|
2016-11-28 17:49:40 +00:00
|
|
|
|
2017-03-21 03:08:02 +00:00
|
|
|
try:
|
|
|
|
from __main__ import display
|
|
|
|
except ImportError:
|
|
|
|
from ansible.utils.display import Display
|
|
|
|
display = Display()
|
|
|
|
|
2016-11-28 17:49:40 +00:00
|
|
|
|
2017-06-06 08:26:25 +00:00
|
|
|
class Connection(Rpc, _Connection):
|
2016-12-06 02:42:09 +00:00
|
|
|
''' CLI (shell) SSH connections on Paramiko '''
|
2016-11-28 17:49:40 +00:00
|
|
|
|
|
|
|
transport = 'network_cli'
|
2017-02-17 15:00:23 +00:00
|
|
|
has_pipelining = True
|
2016-11-28 17:49:40 +00:00
|
|
|
|
|
|
|
def __init__(self, play_context, new_stdin, *args, **kwargs):
|
|
|
|
super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs)
|
|
|
|
|
2016-11-30 21:28:47 +00:00
|
|
|
self._terminal = None
|
2017-06-06 08:26:25 +00:00
|
|
|
self._cliconf = None
|
2016-11-28 17:49:40 +00:00
|
|
|
self._shell = None
|
|
|
|
self._matched_prompt = None
|
|
|
|
self._matched_pattern = None
|
|
|
|
self._last_response = None
|
|
|
|
self._history = list()
|
2017-06-06 08:26:25 +00:00
|
|
|
self._play_context = play_context
|
2016-11-28 17:49:40 +00:00
|
|
|
|
2017-03-21 02:26:18 +00:00
|
|
|
if play_context.verbosity > 3:
|
|
|
|
logging.getLogger('paramiko').setLevel(logging.DEBUG)
|
|
|
|
|
2016-11-28 17:49:40 +00:00
|
|
|
def update_play_context(self, play_context):
|
2016-12-06 02:42:09 +00:00
|
|
|
"""Updates the play context information for the connection"""
|
2017-03-21 02:26:18 +00:00
|
|
|
|
2017-03-21 03:08:02 +00:00
|
|
|
display.display('updating play_context for connection', log_only=True)
|
2017-02-21 14:21:41 +00:00
|
|
|
|
2016-11-28 17:49:40 +00:00
|
|
|
if self._play_context.become is False and play_context.become is True:
|
|
|
|
auth_pass = play_context.become_pass
|
|
|
|
self._terminal.on_authorize(passwd=auth_pass)
|
|
|
|
|
|
|
|
elif self._play_context.become is True and not play_context.become:
|
|
|
|
self._terminal.on_deauthorize()
|
|
|
|
|
|
|
|
self._play_context = play_context
|
|
|
|
|
|
|
|
def _connect(self):
|
2016-12-06 02:42:09 +00:00
|
|
|
"""Connections to the device and sets the terminal type"""
|
2017-03-29 19:12:18 +00:00
|
|
|
|
|
|
|
if self._play_context.password and not self._play_context.private_key_file:
|
|
|
|
C.PARAMIKO_LOOK_FOR_KEYS = False
|
|
|
|
|
2016-11-28 17:49:40 +00:00
|
|
|
super(Connection, self)._connect()
|
2016-11-30 21:28:47 +00:00
|
|
|
|
2017-03-21 03:08:02 +00:00
|
|
|
display.display('ssh connection done, setting terminal', log_only=True)
|
2017-01-26 19:00:08 +00:00
|
|
|
|
2017-06-06 08:26:25 +00:00
|
|
|
self._shell = self.ssh.invoke_shell()
|
|
|
|
self._shell.settimeout(self._play_context.timeout)
|
|
|
|
|
2016-11-30 21:28:47 +00:00
|
|
|
network_os = self._play_context.network_os
|
|
|
|
if not network_os:
|
|
|
|
raise AnsibleConnectionFailure(
|
2017-01-13 00:31:35 +00:00
|
|
|
'Unable to automatically determine host network os. Please '
|
|
|
|
'manually configure ansible_network_os value for this host'
|
2016-11-30 21:28:47 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
self._terminal = terminal_loader.get(network_os, self)
|
|
|
|
if not self._terminal:
|
|
|
|
raise AnsibleConnectionFailure('network os %s is not supported' % network_os)
|
|
|
|
|
2017-06-06 08:26:25 +00:00
|
|
|
display.display('loaded terminal plugin for network_os %s' % network_os, log_only=True)
|
2016-11-28 17:49:40 +00:00
|
|
|
|
2017-06-06 08:26:25 +00:00
|
|
|
self._cliconf = cliconf_loader.get(network_os, self)
|
|
|
|
if self._cliconf:
|
|
|
|
self._rpc.add(self._cliconf)
|
|
|
|
display.display('loaded cliconf plugin for network_os %s' % network_os, log_only=True)
|
|
|
|
else:
|
|
|
|
display.display('unable to load cliconf for network_os %s' % network_os)
|
2016-11-28 17:49:40 +00:00
|
|
|
|
|
|
|
self.receive()
|
|
|
|
|
2017-06-06 08:26:25 +00:00
|
|
|
display.display('firing event: on_open_shell()', log_only=True)
|
|
|
|
self._terminal.on_open_shell()
|
2016-11-28 17:49:40 +00:00
|
|
|
|
2016-12-06 02:42:09 +00:00
|
|
|
if getattr(self._play_context, 'become', None):
|
2017-06-06 08:26:25 +00:00
|
|
|
display.display('firing event: on_authorize', log_only=True)
|
2016-12-06 02:42:09 +00:00
|
|
|
auth_pass = self._play_context.become_pass
|
|
|
|
self._terminal.on_authorize(passwd=auth_pass)
|
2016-11-28 17:49:40 +00:00
|
|
|
|
2017-06-06 08:26:25 +00:00
|
|
|
self._connected = True
|
|
|
|
display.display('ssh connection has completed successfully', log_only=True)
|
2017-02-17 01:26:48 +00:00
|
|
|
|
2016-11-28 17:49:40 +00:00
|
|
|
def close(self):
|
2017-06-06 08:26:25 +00:00
|
|
|
"""Close the active connection to the device
|
|
|
|
"""
|
|
|
|
display.display("closing ssh connection to device", log_only=True)
|
2016-11-28 17:49:40 +00:00
|
|
|
if self._shell:
|
2017-06-06 08:26:25 +00:00
|
|
|
display.display("firing event: on_close_shell()", log_only=True)
|
2016-11-28 17:49:40 +00:00
|
|
|
self._terminal.on_close_shell()
|
|
|
|
self._shell.close()
|
|
|
|
self._shell = None
|
2017-06-06 08:26:25 +00:00
|
|
|
display.display("cli session is now closed", log_only=True)
|
2016-11-28 17:49:40 +00:00
|
|
|
|
2017-06-06 08:26:25 +00:00
|
|
|
super(Connection, self).close()
|
2016-11-28 17:49:40 +00:00
|
|
|
|
2017-06-06 08:26:25 +00:00
|
|
|
self._connected = False
|
|
|
|
display.display("ssh connection has been closed successfully", log_only=True)
|
|
|
|
|
|
|
|
def receive(self, command=None, prompts=None, answer=None):
|
2016-12-06 02:42:09 +00:00
|
|
|
"""Handles receiving of output from command"""
|
2017-05-12 16:13:51 +00:00
|
|
|
recv = BytesIO()
|
2016-11-28 17:49:40 +00:00
|
|
|
handled = False
|
|
|
|
|
|
|
|
self._matched_prompt = None
|
|
|
|
|
|
|
|
while True:
|
|
|
|
data = self._shell.recv(256)
|
|
|
|
|
|
|
|
recv.write(data)
|
2016-12-04 01:05:33 +00:00
|
|
|
offset = recv.tell() - 256 if recv.tell() > 256 else 0
|
|
|
|
recv.seek(offset)
|
2016-11-28 17:49:40 +00:00
|
|
|
|
|
|
|
window = self._strip(recv.read())
|
|
|
|
|
2017-06-06 08:26:25 +00:00
|
|
|
if prompts and not handled:
|
|
|
|
handled = self._handle_prompt(window, prompts, answer)
|
2016-11-28 17:49:40 +00:00
|
|
|
|
|
|
|
if self._find_prompt(window):
|
|
|
|
self._last_response = recv.getvalue()
|
|
|
|
resp = self._strip(self._last_response)
|
2017-06-06 08:26:25 +00:00
|
|
|
return self._sanitize(resp, command)
|
2016-11-28 17:49:40 +00:00
|
|
|
|
2017-06-06 08:26:25 +00:00
|
|
|
def send(self, command, prompts=None, answer=None, send_only=False):
|
2016-12-06 02:42:09 +00:00
|
|
|
"""Sends the command to the device in the opened shell"""
|
2016-11-28 17:49:40 +00:00
|
|
|
try:
|
|
|
|
self._history.append(command)
|
2017-05-12 16:13:51 +00:00
|
|
|
self._shell.sendall(b'%s\r' % command)
|
2017-06-06 08:26:25 +00:00
|
|
|
if send_only:
|
2017-01-04 03:33:02 +00:00
|
|
|
return
|
2017-06-06 08:26:25 +00:00
|
|
|
return self.receive(command, prompts, answer)
|
2017-05-12 16:13:51 +00:00
|
|
|
except (socket.timeout, AttributeError):
|
2017-03-21 03:08:02 +00:00
|
|
|
display.display(traceback.format_exc(), log_only=True)
|
2016-11-28 17:49:40 +00:00
|
|
|
raise AnsibleConnectionFailure("timeout trying to send command: %s" % command.strip())
|
|
|
|
|
|
|
|
def _strip(self, data):
|
2016-12-06 02:42:09 +00:00
|
|
|
"""Removes ANSI codes from device response"""
|
2016-11-28 17:49:40 +00:00
|
|
|
for regex in self._terminal.ansi_re:
|
2017-05-12 16:13:51 +00:00
|
|
|
data = regex.sub(b'', data)
|
2016-11-28 17:49:40 +00:00
|
|
|
return data
|
|
|
|
|
2017-05-24 14:10:38 +00:00
|
|
|
def _handle_prompt(self, resp, prompts, answer):
|
|
|
|
"""
|
|
|
|
Matches the command prompt and responds
|
|
|
|
|
|
|
|
:arg resp: Byte string containing the raw response from the remote
|
|
|
|
:arg prompts: Sequence of byte strings that we consider prompts for input
|
|
|
|
:arg answer: Byte string to send back to the remote if we find a prompt.
|
|
|
|
A carriage return is automatically appended to this string.
|
|
|
|
:returns: True if a prompt was found in ``resp``. False otherwise
|
|
|
|
"""
|
|
|
|
prompts = [re.compile(r, re.I) for r in prompts]
|
2017-02-21 13:27:33 +00:00
|
|
|
for regex in prompts:
|
|
|
|
match = regex.search(resp)
|
|
|
|
if match:
|
2017-05-12 16:13:51 +00:00
|
|
|
self._shell.sendall(b'%s\r' % answer)
|
2017-02-21 13:27:33 +00:00
|
|
|
return True
|
2017-05-24 14:10:38 +00:00
|
|
|
return False
|
2016-11-28 17:49:40 +00:00
|
|
|
|
2017-06-06 08:26:25 +00:00
|
|
|
def _sanitize(self, resp, command=None):
|
2016-12-06 02:42:09 +00:00
|
|
|
"""Removes elements from the response before returning to the caller"""
|
2016-11-28 17:49:40 +00:00
|
|
|
cleaned = []
|
|
|
|
for line in resp.splitlines():
|
2017-08-09 13:43:04 +00:00
|
|
|
if (command and line.strip() == command.strip()) or self._matched_prompt.strip() in line:
|
2016-11-28 17:49:40 +00:00
|
|
|
continue
|
|
|
|
cleaned.append(line)
|
2017-05-24 14:10:38 +00:00
|
|
|
return b'\n'.join(cleaned).strip()
|
2016-11-28 17:49:40 +00:00
|
|
|
|
|
|
|
def _find_prompt(self, response):
|
2016-12-06 02:42:09 +00:00
|
|
|
"""Searches the buffered response for a matching command prompt"""
|
2017-02-17 14:13:26 +00:00
|
|
|
errored_response = None
|
2017-05-24 14:10:38 +00:00
|
|
|
is_error_message = False
|
2017-02-17 15:00:23 +00:00
|
|
|
for regex in self._terminal.terminal_stderr_re:
|
2016-11-28 17:49:40 +00:00
|
|
|
if regex.search(response):
|
2017-05-24 14:10:38 +00:00
|
|
|
is_error_message = True
|
|
|
|
|
|
|
|
# Check if error response ends with command prompt if not
|
|
|
|
# receive it buffered prompt
|
|
|
|
for regex in self._terminal.terminal_stdout_re:
|
|
|
|
match = regex.search(response)
|
|
|
|
if match:
|
|
|
|
errored_response = response
|
|
|
|
break
|
|
|
|
|
|
|
|
if not is_error_message:
|
|
|
|
for regex in self._terminal.terminal_stdout_re:
|
|
|
|
match = regex.search(response)
|
|
|
|
if match:
|
|
|
|
self._matched_pattern = regex.pattern
|
|
|
|
self._matched_prompt = match.group()
|
|
|
|
if not errored_response:
|
|
|
|
return True
|
2017-02-17 14:13:26 +00:00
|
|
|
|
|
|
|
if errored_response:
|
|
|
|
raise AnsibleConnectionFailure(errored_response)
|
2016-11-28 17:49:40 +00:00
|
|
|
|
2017-05-24 14:10:38 +00:00
|
|
|
return False
|
|
|
|
|
2016-11-28 17:49:40 +00:00
|
|
|
def alarm_handler(self, signum, frame):
|
2016-12-06 02:42:09 +00:00
|
|
|
"""Alarm handler raised in case of command timeout """
|
2017-03-21 03:08:02 +00:00
|
|
|
display.display('closing shell due to sigalarm', log_only=True)
|
2017-06-17 19:48:30 +00:00
|
|
|
self.close()
|
2016-11-28 17:49:40 +00:00
|
|
|
|
|
|
|
def exec_command(self, cmd):
|
2016-12-06 02:42:09 +00:00
|
|
|
"""Executes the cmd on in the shell and returns the output
|
|
|
|
|
2017-06-06 08:26:25 +00:00
|
|
|
The method accepts three forms of cmd. The first form is as a byte
|
2016-12-06 02:42:09 +00:00
|
|
|
string that represents the command to be executed in the shell. The
|
2017-05-12 16:13:51 +00:00
|
|
|
second form is as a utf8 JSON byte string with additional keywords.
|
2017-06-06 08:26:25 +00:00
|
|
|
The third form is a json-rpc (2.0)
|
2016-12-06 02:42:09 +00:00
|
|
|
Keywords supported for cmd:
|
2017-05-24 14:10:38 +00:00
|
|
|
:command: the command string to execute
|
|
|
|
:prompt: the expected prompt generated by executing command.
|
|
|
|
This can be a string or a list of strings
|
|
|
|
:answer: the string to respond to the prompt with
|
|
|
|
:sendonly: bool to disable waiting for response
|
2017-05-12 16:13:51 +00:00
|
|
|
:arg cmd: the byte string that represents the command to be executed
|
|
|
|
which can be a single command or a json encoded string.
|
2016-12-06 02:42:09 +00:00
|
|
|
:returns: a tuple of (return code, stdout, stderr). The return
|
2017-05-12 16:13:51 +00:00
|
|
|
code is an integer and stdout and stderr are byte strings
|
2016-12-06 02:42:09 +00:00
|
|
|
"""
|
2016-11-28 17:49:40 +00:00
|
|
|
try:
|
2017-05-12 16:13:51 +00:00
|
|
|
obj = json.loads(to_text(cmd, errors='surrogate_or_strict'))
|
2017-01-27 01:39:47 +00:00
|
|
|
except (ValueError, TypeError):
|
2017-05-12 16:13:51 +00:00
|
|
|
obj = {'command': to_bytes(cmd.strip(), errors='surrogate_or_strict')}
|
2016-11-28 17:49:40 +00:00
|
|
|
|
2017-05-24 14:10:38 +00:00
|
|
|
obj = dict((k, to_bytes(v, errors='surrogate_or_strict', nonstring='passthru')) for k, v in obj.items())
|
|
|
|
if 'prompt' in obj:
|
|
|
|
if isinstance(obj['prompt'], binary_type):
|
|
|
|
# Prompt was a string
|
|
|
|
obj['prompt'] = [obj['prompt']]
|
|
|
|
elif not isinstance(obj['prompt'], Sequence):
|
|
|
|
# Convert nonstrings into byte strings (to_bytes(5) => b'5')
|
|
|
|
if obj['prompt'] is not None:
|
|
|
|
obj['prompt'] = [to_bytes(obj['prompt'], errors='surrogate_or_strict')]
|
|
|
|
else:
|
|
|
|
# Prompt was a Sequence of strings. Make sure they're byte strings
|
|
|
|
obj['prompt'] = [to_bytes(p, errors='surrogate_or_strict') for p in obj['prompt'] if p is not None]
|
2016-11-28 17:49:40 +00:00
|
|
|
|
2017-06-06 08:26:25 +00:00
|
|
|
if 'jsonrpc' in obj:
|
|
|
|
if self._cliconf:
|
|
|
|
out = self._exec_rpc(obj)
|
|
|
|
else:
|
|
|
|
out = self.internal_error("cliconf is not supported for network_os %s" % self._play_context.network_os)
|
|
|
|
return 0, to_bytes(out, errors='surrogate_or_strict'), b''
|
|
|
|
|
|
|
|
if obj['command'] == b'prompt()':
|
|
|
|
return 0, self._matched_prompt, b''
|
2016-11-28 17:49:40 +00:00
|
|
|
|
|
|
|
try:
|
2017-01-16 13:32:45 +00:00
|
|
|
if not signal.getsignal(signal.SIGALRM):
|
|
|
|
signal.signal(signal.SIGALRM, self.alarm_handler)
|
2017-01-16 14:15:46 +00:00
|
|
|
signal.alarm(self._play_context.timeout)
|
2017-06-06 08:26:25 +00:00
|
|
|
out = self.send(obj['command'], obj.get('prompt'), obj.get('answer'), obj.get('sendonly'))
|
2017-01-16 13:32:45 +00:00
|
|
|
signal.alarm(0)
|
2017-06-06 08:26:25 +00:00
|
|
|
return 0, out, b''
|
2016-11-28 17:49:40 +00:00
|
|
|
except (AnsibleConnectionFailure, ValueError) as exc:
|
2017-06-06 08:26:25 +00:00
|
|
|
return 1, b'', to_bytes(exc)
|