| 1 |
from select import select |
| 2 |
import re |
| 3 |
import datetime |
| 4 |
from jnpr.junos.utils.ssh_client import open_ssh_client |
| 5 |
import subprocess |
| 6 |
import six |
| 7 |
from threading import Thread |
| 8 |
import time |
| 9 |
|
| 10 |
_JUNOS_PROMPT = "> " |
| 11 |
_SHELL_PROMPT = r"(%|#|\$)\s" |
| 12 |
_SELECT_WAIT = 0.1 |
| 13 |
_RECVSZ = 1024 |
| 14 |
|
| 15 |
|
| 16 |
class StartShell(object): |
| 17 |
""" |
| 18 |
Junos shell execution utility. This utility is written to |
| 19 |
support the "context manager" design pattern. For example:: |
| 20 |
|
| 21 |
def _ssh_exec(self, command): |
| 22 |
with StartShell(self._dev) as sh: |
| 23 |
got = sh.run(command) |
| 24 |
return got |
| 25 |
|
| 26 |
""" |
| 27 |
|
| 28 |
def __init__(self, nc, timeout=30, shell_type="csh"): |
| 29 |
""" |
| 30 |
Utility Constructor |
| 31 |
|
| 32 |
:param Device nc: The Device object |
| 33 |
|
| 34 |
:param int timeout: |
| 35 |
Timeout value in seconds to wait for expected string/pattern. |
| 36 |
""" |
| 37 |
self._nc = nc |
| 38 |
self.timeout = timeout |
| 39 |
self._client = None |
| 40 |
self._chan = None |
| 41 |
self.ON_JUNOS = self._nc.__class__.ON_JUNOS |
| 42 |
self.shell_type = shell_type |
| 43 |
|
| 44 |
def write_stdin(self, stdin, data): |
| 45 |
stdin.write(data.encode("utf-8")) |
| 46 |
stdin.flush() |
| 47 |
|
| 48 |
def wait_for(self, this=_SHELL_PROMPT, timeout=0, sleep=0): |
| 49 |
""" |
| 50 |
Wait for the result of the command, expecting **this** prompt. |
| 51 |
|
| 52 |
:param str this: expected string/pattern. |
| 53 |
|
| 54 |
:param int timeout: |
| 55 |
Timeout value in seconds to wait for expected string/pattern. |
| 56 |
If not specified defaults to self.timeout. |
| 57 |
:param seconds sleep: |
| 58 |
Time to wait after initial call to receive data from buffer. This |
| 59 |
value can help stabilize the output when multiple calls to run() |
| 60 |
are looped but will increase the time spent receiving output. This |
| 61 |
value can be a floating point number for subsecond precision. |
| 62 |
|
| 63 |
:returns: resulting string of data in a list |
| 64 |
:rtype: list |
| 65 |
|
| 66 |
.. warning:: need to add a timeout safeguard |
| 67 |
""" |
| 68 |
chan = self._chan |
| 69 |
got = [] |
| 70 |
timeout = timeout or self.timeout |
| 71 |
timeout = datetime.datetime.now() + datetime.timedelta(seconds=timeout) |
| 72 |
while timeout > datetime.datetime.now(): |
| 73 |
if self.ON_JUNOS is True: |
| 74 |
data = chan.stdout.readline() |
| 75 |
else: |
| 76 |
rd, wr, err = select([chan], [], [], _SELECT_WAIT) |
| 77 |
if rd: |
| 78 |
data = chan.recv(_RECVSZ) |
| 79 |
else: |
| 80 |
continue |
| 81 |
if sleep: |
| 82 |
time.sleep(sleep) |
| 83 |
if isinstance(data, bytes): |
| 84 |
data = data.decode("utf-8", "replace") |
| 85 |
got.append(data) |
| 86 |
|
| 87 |
if this is not None and re.search(r"{}\s?$".format(this), str(data)): |
| 88 |
break |
| 89 |
return got |
| 90 |
|
| 91 |
def send(self, data): |
| 92 |
""" |
| 93 |
Send the command **data** followed by a newline character. |
| 94 |
|
| 95 |
:param str data: the data to write out onto the shell. |
| 96 |
:returns: result of SSH channel send |
| 97 |
""" |
| 98 |
if self.ON_JUNOS is True: |
| 99 |
data += " && echo ']]>]]>' \n" |
| 100 |
self._chan.stdin.write(data.encode("utf-8")) |
| 101 |
self.t = Thread(target=self.write_stdin, args=(self._chan.stdin, data)) |
| 102 |
self.t.daemon = True # thread dies with the program |
| 103 |
self.t.start() |
| 104 |
return |
| 105 |
else: |
| 106 |
self._chan.send(data) |
| 107 |
self._chan.send("\n") |
| 108 |
|
| 109 |
def open(self): |
| 110 |
""" |
| 111 |
Open an ssh-client connection and issue the 'start shell' command to |
| 112 |
drop into the Junos shell (csh). This process opens a |
| 113 |
:class:`paramiko.SSHClient` instance. |
| 114 |
""" |
| 115 |
if self.ON_JUNOS is True: |
| 116 |
self._chan = subprocess.Popen( |
| 117 |
["cli", "start", "shell", self.shell_type], |
| 118 |
shell=False, |
| 119 |
stdin=subprocess.PIPE, |
| 120 |
stdout=subprocess.PIPE, |
| 121 |
close_fds=1, |
| 122 |
bufsize=0, |
| 123 |
) |
| 124 |
else: |
| 125 |
self._client = open_ssh_client(dev=self._nc) |
| 126 |
self._chan = self._client.invoke_shell() |
| 127 |
|
| 128 |
got = self.wait_for(r"(%|>|#|\$)") |
| 129 |
if got[-1].endswith(_JUNOS_PROMPT): |
| 130 |
self.send("start shell " + self.shell_type) |
| 131 |
self.wait_for(_SHELL_PROMPT) |
| 132 |
|
| 133 |
def close(self): |
| 134 |
"""Close the SSH client channel""" |
| 135 |
|
| 136 |
if self.ON_JUNOS is True: |
| 137 |
self._chan.terminate() |
| 138 |
else: |
| 139 |
self._chan.close() |
| 140 |
self._client.close() |
| 141 |
|
| 142 |
def run(self, command, this=_SHELL_PROMPT, timeout=0, sleep=0): |
| 143 |
""" |
| 144 |
Run a shell command and wait for the response. The return is a |
| 145 |
tuple. The first item is True/False if exit-code is 0. The second |
| 146 |
item is the output of the command. |
| 147 |
|
| 148 |
:param str command: the shell command to execute |
| 149 |
:param str this: the expected shell-prompt to wait for. If ``this`` is |
| 150 |
set to None, function will wait for all the output on the shell till |
| 151 |
timeout value. |
| 152 |
:param int timeout: |
| 153 |
Timeout value in seconds to wait for expected string/pattern (this). |
| 154 |
If not specified defaults to self.timeout. This timeout is specific |
| 155 |
to individual run call. If ``this`` is provided with None value, |
| 156 |
function will wait till timeout value to grab all the content from |
| 157 |
command output. |
| 158 |
:param seconds sleep: |
| 159 |
Time to wait after initial call to receive data from buffer. This |
| 160 |
value can help stabilize the output when multiple calls to run() |
| 161 |
are looped but will increase the time spent receiving output. This |
| 162 |
value can be a floating point number for subsecond precision. |
| 163 |
|
| 164 |
:returns: (last_ok, result of the executed shell command (str) ) |
| 165 |
|
| 166 |
.. code-block:: python |
| 167 |
|
| 168 |
with StartShell(dev) as ss: |
| 169 |
print ss.run('cprod -A fpc0 -c "show version"', timeout=10) |
| 170 |
|
| 171 |
.. note:: as a *side-effect* this method will set the ``self.last_ok`` |
| 172 |
property. This property is set to ``True`` if ``$?`` is |
| 173 |
"0"; indicating the last shell command was successful else |
| 174 |
False. If ``this`` is set to None, last_ok will be set to |
| 175 |
True if there is any content in result of the executed shell |
| 176 |
command. |
| 177 |
""" |
| 178 |
timeout = timeout or self.timeout |
| 179 |
# run the command and capture the output |
| 180 |
self.send(command) |
| 181 |
if self.ON_JUNOS is True: |
| 182 |
got = "".join(self.wait_for(this="]]>]]>", timeout=timeout)) |
| 183 |
self.send("echo $?") |
| 184 |
rc = "".join(self.wait_for(this="]]>]]>")) |
| 185 |
self.last_ok = rc.find("0") > 0 |
| 186 |
else: |
| 187 |
got = "".join(self.wait_for(this, timeout, sleep=sleep)) |
| 188 |
self.last_ok = False |
| 189 |
if this is None: |
| 190 |
self.last_ok = got != "" |
| 191 |
elif this != _SHELL_PROMPT: |
| 192 |
self.last_ok = re.search(r"{}\s?$".format(this), got) is not None |
| 193 |
elif re.search(r"{}\s?$".format(_SHELL_PROMPT), got) is not None: |
| 194 |
# use $? to get the exit code of the command |
| 195 |
self.send("echo $?") |
| 196 |
rc = "".join(self.wait_for(_SHELL_PROMPT)) |
| 197 |
self.last_ok = rc.find("\r\n0\r\n") > 0 |
| 198 |
return (self.last_ok, got) |
| 199 |
|
| 200 |
# ------------------------------------------------------------------------- |
| 201 |
# CONTEXT MANAGER |
| 202 |
# ------------------------------------------------------------------------- |
| 203 |
|
| 204 |
def __enter__(self): |
| 205 |
self.open() |
| 206 |
return self |
| 207 |
|
| 208 |
def __exit__(self, exc_ty, exc_val, exc_tb): |
| 209 |
self.close() |