| 1 |
import sys |
| 2 |
import re |
| 3 |
from io import BytesIO as StringIO |
| 4 |
from subprocess import Popen, check_output, PIPE, STDOUT |
| 5 |
|
| 6 |
from ncclient.transport.errors import SessionCloseError, TransportError, PermissionError |
| 7 |
from ncclient.transport.ssh import SSHSession |
| 8 |
|
| 9 |
MSG_DELIM = b"]]>]]>" |
| 10 |
NETCONF_SHELL = 'netconf' |
| 11 |
|
| 12 |
|
| 13 |
class IOProc(SSHSession): |
| 14 |
|
| 15 |
def __init__(self, device_handler): |
| 16 |
SSHSession.__init__(self, device_handler) |
| 17 |
self._host_keys = None |
| 18 |
self._transport = None |
| 19 |
self._connected = False |
| 20 |
self._channel = None |
| 21 |
self._channel_id = None |
| 22 |
self._channel_name = None |
| 23 |
self._buffer = StringIO() # for incoming data |
| 24 |
# parsing-related, see _parse() |
| 25 |
self._parsing_state = 0 |
| 26 |
self._parsing_pos = 0 |
| 27 |
self._device_handler = device_handler |
| 28 |
|
| 29 |
def close(self): |
| 30 |
stdout, stderr = self._channel.communicate() |
| 31 |
self._channel = None |
| 32 |
self._connected = False |
| 33 |
|
| 34 |
def connect(self): |
| 35 |
stdoutdata = check_output(NETCONF_SHELL, shell=True, stdin=PIPE, |
| 36 |
stderr=STDOUT).decode(encoding="utf8") |
| 37 |
if 'error: Restricted user session' in stdoutdata: |
| 38 |
obj = re.search(r'<error-message>\n?(.*)\n?</error-message>', stdoutdata, re.M) |
| 39 |
if obj: |
| 40 |
raise PermissionError(obj.group(1)) |
| 41 |
else: |
| 42 |
raise PermissionError('Restricted user session') |
| 43 |
elif 'xml-mode: command not found' in stdoutdata: |
| 44 |
raise PermissionError('xml-mode: command not found') |
| 45 |
self._channel = Popen([NETCONF_SHELL], |
| 46 |
stdin=PIPE, stdout=PIPE, stderr=STDOUT) |
| 47 |
self._connected = True |
| 48 |
self._channel_id = self._channel.pid |
| 49 |
self._channel_name = "netconf-shell" |
| 50 |
self._post_connect() |
| 51 |
return |
| 52 |
|
| 53 |
def run(self): |
| 54 |
chan = self._channel |
| 55 |
q = self._q |
| 56 |
try: |
| 57 |
while True: |
| 58 |
# write |
| 59 |
data = q.get().encode() + MSG_DELIM |
| 60 |
chan.stdin.write(data) |
| 61 |
chan.stdin.flush() |
| 62 |
# read |
| 63 |
data = [] |
| 64 |
while True: |
| 65 |
line = chan.stdout.readline() |
| 66 |
data.append(line) |
| 67 |
if MSG_DELIM in line: |
| 68 |
break |
| 69 |
self._buffer.write(b''.join(data)) |
| 70 |
self._parse() |
| 71 |
except Exception as e: |
| 72 |
self._dispatch_error(e) |
| 73 |
self.close() |
| 74 |
|
| 75 |
@property |
| 76 |
def transport(self): |
| 77 |
"Underlying `paramiko.Transport <http://www.lag.net/paramiko/docs/paramiko.Transport-class.html>`_ object. This makes it possible to call methods like :meth:`~paramiko.Transport.set_keepalive` on it." |
| 78 |
return self._transport |