Merge pull request #17168 from privateip/clibase
replaces NetCli in network with CliBase in shell
This commit is contained in:
commit
321d2e8cee
2 changed files with 81 additions and 98 deletions
|
@ -32,7 +32,6 @@ from ansible.module_utils.basic import AnsibleModule
|
||||||
from ansible.module_utils.basic import env_fallback, get_exception
|
from ansible.module_utils.basic import env_fallback, get_exception
|
||||||
from ansible.module_utils.netcli import Cli, Command
|
from ansible.module_utils.netcli import Cli, Command
|
||||||
from ansible.module_utils.netcfg import Config
|
from ansible.module_utils.netcfg import Config
|
||||||
from ansible.module_utils.shell import Shell, ShellError, HAS_PARAMIKO
|
|
||||||
|
|
||||||
NET_TRANSPORT_ARGS = dict(
|
NET_TRANSPORT_ARGS = dict(
|
||||||
host=dict(required=True),
|
host=dict(required=True),
|
||||||
|
@ -160,63 +159,6 @@ class NetworkModule(AnsibleModule):
|
||||||
exc = get_exception()
|
exc = get_exception()
|
||||||
self.fail_json(msg=exc.message)
|
self.fail_json(msg=exc.message)
|
||||||
|
|
||||||
class NetCli(object):
|
|
||||||
"""Basic paramiko-based ssh transport any NetworkModule can use."""
|
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
if not HAS_PARAMIKO:
|
|
||||||
raise NetworkError(
|
|
||||||
msg='paramiko is required but does not appear to be installed. '
|
|
||||||
'It can be installed using `pip install paramiko`'
|
|
||||||
)
|
|
||||||
|
|
||||||
self.shell = None
|
|
||||||
self._connected = False
|
|
||||||
self.default_output = 'text'
|
|
||||||
|
|
||||||
def connect(self, params, kickstart=True, **kwargs):
|
|
||||||
host = params['host']
|
|
||||||
port = params.get('port') or 22
|
|
||||||
|
|
||||||
username = params['username']
|
|
||||||
password = params.get('password')
|
|
||||||
key_file = params.get('ssh_keyfile')
|
|
||||||
timeout = params['timeout']
|
|
||||||
|
|
||||||
try:
|
|
||||||
self.shell = Shell(
|
|
||||||
kickstart=kickstart,
|
|
||||||
prompts_re=self.CLI_PROMPTS_RE,
|
|
||||||
errors_re=self.CLI_ERRORS_RE,
|
|
||||||
)
|
|
||||||
self.shell.open(
|
|
||||||
host, port=port, username=username, password=password,
|
|
||||||
key_filename=key_file, timeout=timeout,
|
|
||||||
)
|
|
||||||
except ShellError:
|
|
||||||
exc = get_exception()
|
|
||||||
raise NetworkError(
|
|
||||||
msg='failed to connect to %s:%s' % (host, port), exc=str(exc)
|
|
||||||
)
|
|
||||||
|
|
||||||
self._connected = True
|
|
||||||
|
|
||||||
def disconnect(self, **kwargs):
|
|
||||||
self.shell.close()
|
|
||||||
self._connected = False
|
|
||||||
|
|
||||||
def authorize(self, params, **kwargs):
|
|
||||||
passwd = params['auth_pass']
|
|
||||||
self.execute(Command('enable', prompt=self.NET_PASSWD_RE, response=passwd))
|
|
||||||
|
|
||||||
def execute(self, commands, **kwargs):
|
|
||||||
try:
|
|
||||||
return self.shell.send(commands)
|
|
||||||
except ShellError:
|
|
||||||
exc = get_exception()
|
|
||||||
raise NetworkError(exc.message, commands=commands)
|
|
||||||
|
|
||||||
|
|
||||||
def register_transport(transport, default=False):
|
def register_transport(transport, default=False):
|
||||||
def register(cls):
|
def register(cls):
|
||||||
NET_CONNECTIONS[transport] = cls
|
NET_CONNECTIONS[transport] = cls
|
||||||
|
|
|
@ -18,8 +18,7 @@
|
||||||
#
|
#
|
||||||
import re
|
import re
|
||||||
import socket
|
import socket
|
||||||
|
import time
|
||||||
from ansible.module_utils.basic import get_exception
|
|
||||||
|
|
||||||
# py2 vs py3; replace with six via ansiballz
|
# py2 vs py3; replace with six via ansiballz
|
||||||
try:
|
try:
|
||||||
|
@ -35,25 +34,11 @@ except ImportError:
|
||||||
HAS_PARAMIKO = False
|
HAS_PARAMIKO = False
|
||||||
|
|
||||||
from ansible.module_utils.basic import get_exception
|
from ansible.module_utils.basic import get_exception
|
||||||
|
from ansible.module_utils.network import NetworkError
|
||||||
|
|
||||||
ANSI_RE = re.compile(r'(\x1b\[\?1h\x1b=)')
|
ANSI_RE = [
|
||||||
|
re.compile(r'(\x1b\[\?1h\x1b=)'),
|
||||||
CLI_PROMPTS_RE = [
|
re.compile(r'\x08.')
|
||||||
re.compile(r'[\r\n]?[a-zA-Z]{1}[a-zA-Z0-9-]*[>|#|%](?:\s*)$'),
|
|
||||||
re.compile(r'[\r\n]?[a-zA-Z]{1}[a-zA-Z0-9-]*\(.+\)#(?:\s*)$')
|
|
||||||
]
|
|
||||||
|
|
||||||
CLI_ERRORS_RE = [
|
|
||||||
re.compile(r"% ?Error"),
|
|
||||||
re.compile(r"^% \w+", re.M),
|
|
||||||
re.compile(r"% ?Bad secret"),
|
|
||||||
re.compile(r"invalid input", re.I),
|
|
||||||
re.compile(r"(?:incomplete|ambiguous) command", re.I),
|
|
||||||
re.compile(r"connection timed out", re.I),
|
|
||||||
re.compile(r"[^\r\n]+ not found", re.I),
|
|
||||||
re.compile(r"'[^']' +returned error code: ?\d+"),
|
|
||||||
re.compile(r"syntax error"),
|
|
||||||
re.compile(r"unknown command")
|
|
||||||
]
|
]
|
||||||
|
|
||||||
def to_list(val):
|
def to_list(val):
|
||||||
|
@ -64,6 +49,7 @@ def to_list(val):
|
||||||
else:
|
else:
|
||||||
return list()
|
return list()
|
||||||
|
|
||||||
|
|
||||||
class ShellError(Exception):
|
class ShellError(Exception):
|
||||||
|
|
||||||
def __init__(self, msg, command=None):
|
def __init__(self, msg, command=None):
|
||||||
|
@ -71,15 +57,6 @@ class ShellError(Exception):
|
||||||
self.message = msg
|
self.message = msg
|
||||||
self.command = command
|
self.command = command
|
||||||
|
|
||||||
class Command(object):
|
|
||||||
|
|
||||||
def __init__(self, command, prompt=None, response=None):
|
|
||||||
self.command = command
|
|
||||||
self.prompt = prompt
|
|
||||||
self.response = response
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return self.command
|
|
||||||
|
|
||||||
class Shell(object):
|
class Shell(object):
|
||||||
|
|
||||||
|
@ -90,8 +67,8 @@ class Shell(object):
|
||||||
self.kickstart = kickstart
|
self.kickstart = kickstart
|
||||||
self._matched_prompt = None
|
self._matched_prompt = None
|
||||||
|
|
||||||
self.prompts = prompts_re or CLI_PROMPTS_RE
|
self.prompts = prompts_re or list()
|
||||||
self.errors = errors_re or CLI_ERRORS_RE
|
self.errors = errors_re or list()
|
||||||
|
|
||||||
def open(self, host, port=22, username=None, password=None,
|
def open(self, host, port=22, username=None, password=None,
|
||||||
timeout=10, key_filename=None, pkey=None, look_for_keys=None,
|
timeout=10, key_filename=None, pkey=None, look_for_keys=None,
|
||||||
|
@ -123,10 +100,13 @@ class Shell(object):
|
||||||
self.receive()
|
self.receive()
|
||||||
|
|
||||||
def strip(self, data):
|
def strip(self, data):
|
||||||
return ANSI_RE.sub('', data)
|
for regex in ANSI_RE:
|
||||||
|
data = regex.sub('', data)
|
||||||
|
return data
|
||||||
|
|
||||||
def receive(self, cmd=None):
|
def receive(self, cmd=None):
|
||||||
recv = StringIO()
|
recv = StringIO()
|
||||||
|
handled = False
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
data = self.shell.recv(200)
|
data = self.shell.recv(200)
|
||||||
|
@ -136,12 +116,15 @@ class Shell(object):
|
||||||
|
|
||||||
window = self.strip(recv.read())
|
window = self.strip(recv.read())
|
||||||
|
|
||||||
if isinstance(cmd, Command):
|
if hasattr(cmd, 'prompt') and not handled:
|
||||||
self.handle_input(window, prompt=cmd.prompt,
|
if self.handle_prompt(window, prompt=cmd.prompt, response=cmd.response):
|
||||||
response=cmd.response)
|
handled = True
|
||||||
|
time.sleep(cmd.delay)
|
||||||
|
if cmd.is_reboot:
|
||||||
|
return
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if self.read(window):
|
if self.find_prompt(window):
|
||||||
resp = self.strip(recv.getvalue())
|
resp = self.strip(recv.getvalue())
|
||||||
return self.sanitize(cmd, resp)
|
return self.sanitize(cmd, resp)
|
||||||
except ShellError:
|
except ShellError:
|
||||||
|
@ -157,7 +140,7 @@ class Shell(object):
|
||||||
self.shell.sendall(cmd)
|
self.shell.sendall(cmd)
|
||||||
responses.append(self.receive(command))
|
responses.append(self.receive(command))
|
||||||
except socket.timeout:
|
except socket.timeout:
|
||||||
raise ShellError("timeout trying to send command", cmd)
|
raise ShellError("timeout trying to send command: %s" % cmd)
|
||||||
except socket.error:
|
except socket.error:
|
||||||
exc = get_exception()
|
exc = get_exception()
|
||||||
raise ShellError("problem sending command to host: %s" % exc.message)
|
raise ShellError("problem sending command to host: %s" % exc.message)
|
||||||
|
@ -166,7 +149,7 @@ class Shell(object):
|
||||||
def close(self):
|
def close(self):
|
||||||
self.shell.close()
|
self.shell.close()
|
||||||
|
|
||||||
def handle_input(self, resp, prompt, response):
|
def handle_prompt(self, resp, prompt, response):
|
||||||
if not prompt or not response:
|
if not prompt or not response:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
@ -178,16 +161,17 @@ class Shell(object):
|
||||||
if match:
|
if match:
|
||||||
cmd = '%s\r' % ans
|
cmd = '%s\r' % ans
|
||||||
self.shell.sendall(cmd)
|
self.shell.sendall(cmd)
|
||||||
|
return True
|
||||||
|
|
||||||
def sanitize(self, cmd, resp):
|
def sanitize(self, cmd, resp):
|
||||||
cleaned = []
|
cleaned = []
|
||||||
for line in resp.splitlines():
|
for line in resp.splitlines():
|
||||||
if line.startswith(str(cmd)) or self.read(line):
|
if line.startswith(str(cmd)) or self.find_prompt(line):
|
||||||
continue
|
continue
|
||||||
cleaned.append(line)
|
cleaned.append(line)
|
||||||
return "\n".join(cleaned)
|
return "\n".join(cleaned)
|
||||||
|
|
||||||
def read(self, response):
|
def find_prompt(self, response):
|
||||||
for regex in self.errors:
|
for regex in self.errors:
|
||||||
if regex.search(response):
|
if regex.search(response):
|
||||||
raise ShellError('matched error in response: %s' % response)
|
raise ShellError('matched error in response: %s' % response)
|
||||||
|
@ -197,3 +181,60 @@ class Shell(object):
|
||||||
if match:
|
if match:
|
||||||
self._matched_prompt = match.group()
|
self._matched_prompt = match.group()
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
class CliBase(object):
|
||||||
|
"""Basic paramiko-based ssh transport any NetworkModule can use."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
if not HAS_PARAMIKO:
|
||||||
|
raise NetworkError(
|
||||||
|
msg='paramiko is required but does not appear to be installed. '
|
||||||
|
'It can be installed using `pip install paramiko`'
|
||||||
|
)
|
||||||
|
|
||||||
|
self.shell = None
|
||||||
|
self._connected = False
|
||||||
|
self.default_output = 'text'
|
||||||
|
|
||||||
|
def connect(self, params, kickstart=True, **kwargs):
|
||||||
|
host = params['host']
|
||||||
|
port = params.get('port') or 22
|
||||||
|
|
||||||
|
username = params['username']
|
||||||
|
password = params.get('password')
|
||||||
|
key_file = params.get('ssh_keyfile')
|
||||||
|
timeout = params['timeout']
|
||||||
|
|
||||||
|
try:
|
||||||
|
self.shell = Shell(
|
||||||
|
kickstart=kickstart,
|
||||||
|
prompts_re=self.CLI_PROMPTS_RE,
|
||||||
|
errors_re=self.CLI_ERRORS_RE,
|
||||||
|
)
|
||||||
|
self.shell.open(
|
||||||
|
host, port=port, username=username, password=password,
|
||||||
|
key_filename=key_file, timeout=timeout,
|
||||||
|
)
|
||||||
|
except ShellError:
|
||||||
|
exc = get_exception()
|
||||||
|
raise NetworkError(
|
||||||
|
msg='failed to connect to %s:%s' % (host, port), exc=str(exc)
|
||||||
|
)
|
||||||
|
|
||||||
|
self._connected = True
|
||||||
|
|
||||||
|
def disconnect(self, **kwargs):
|
||||||
|
self.shell.close()
|
||||||
|
self._connected = False
|
||||||
|
|
||||||
|
def authorize(self, params, **kwargs):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def execute(self, commands, **kwargs):
|
||||||
|
try:
|
||||||
|
return self.shell.send(commands)
|
||||||
|
except ShellError:
|
||||||
|
exc = get_exception()
|
||||||
|
raise NetworkError(exc.message, commands=commands)
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue