Debian Codegraph @

lib/jnpr/junos/transport/tty_ssh.py

raw
1 import logging
2 import re
3 import select
4 import socket
5 import sys
6 from time import sleep, time
7
8 import paramiko
9 import six
10
11 from jnpr.junos.transport.tty import Terminal
12
13 logger = logging.getLogger("jnpr.junos.tty_ssh")
14
15 # -------------------------------------------------------------------------
16 # Terminal connection over SSH CONSOLE
17 # -------------------------------------------------------------------------
18 _PROMPT = re.compile(six.b("|").join([six.b(i) for i in Terminal._RE_PAT]))
19
20
21 class PY6:
22 NEW_LINE = six.b("\n")
23 EMPTY_STR = six.b("")
24 NETCONF_EOM = six.b("]]>]]>")
25 IN_USE = six.b("in use")
26
27
28 class SSH(Terminal):
29 RETRY_OPEN = 3 # number of attempts to open TTY
30 RETRY_BACKOFF = 2 # seconds to wait between retries
31 MAX_BUFFER = 65535
32 READ_PROMPT_DELAY = 10.0
33 RECVSZ = 1024
34
35 def __init__(self, host, port, **kvargs):
36 """
37 :host:
38 The hostname or ip-addr of the terminal server
39
40 :port:
41 The TCP port that maps to the TTY device on the
42 console server
43
44 :kvargs['timeout']:
45 this is the tty read polling timeout.
46 generally you should not have to tweak this.
47 """
48 # initialize the underlying TTY device
49
50 self._ssh_pre = self._ssh_client_pre()
51 self.host = host
52 self.port = port
53 self.ssh_private_key_file = kvargs.get("ssh_private_key_file")
54 self.timeout = kvargs.get("timeout", self.TIMEOUT)
55 self.baud = kvargs.get("baud", 9600)
56 self._tty_name = "{}:{}".format(host, port)
57
58 Terminal.__init__(self, **kvargs)
59
60 @staticmethod
61 def _ssh_client_pre():
62 ssh_client_pre = paramiko.SSHClient()
63 ssh_client_pre.load_system_host_keys()
64 ssh_client_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
65
66 return ssh_client_pre
67
68 # -------------------------------------------------------------------------
69 # I/O open close called from Terminal class
70 # -------------------------------------------------------------------------
71
72 def _tty_open(self):
73 retry = self.RETRY_OPEN
74
75 # we want to enable the ssh-agent if-and-only-if we are
76 # not given a password or an ssh key file.
77 # in this condition it means we want to query the agent
78 # for available ssh keys
79 allow_agent = bool(
80 (self.cs_passwd is None) and (self.ssh_private_key_file is None)
81 )
82
83 while retry > 0:
84 try:
85 self._ssh_pre.connect(
86 hostname=self.host,
87 port=int(self.port),
88 username=self.cs_user,
89 password=self.cs_passwd,
90 timeout=self.timeout,
91 allow_agent=allow_agent,
92 look_for_keys=False,
93 key_filename=self.ssh_private_key_file,
94 )
95 break
96 except socket.error as err:
97 retry -= 1
98 logger.error(
99 "SSH Socket Error: {}. Checking back in: {}".format(
100 str(err), self.RETRY_BACKOFF
101 )
102 )
103 sleep(self.RETRY_BACKOFF)
104 except paramiko.BadHostKeyException as err:
105 retry -= 1
106 logger.error(
107 "SSH Bad Host Key Error: {}.Checking back in: {}".format(
108 str(err), self.RETRY_BACKOFF
109 )
110 )
111 sleep(self.RETRY_BACKOFF)
112 except paramiko.AuthenticationException as err:
113 retry -= 1
114 logger.error(
115 "SSH Auth Error: {}. Checking back in: {}".format(
116 str(err), self.RETRY_BACKOFF
117 )
118 )
119 sleep(self.RETRY_BACKOFF)
120 else:
121 raise RuntimeError("open_fail: port not ready")
122
123 self._ssh = self._ssh_pre.invoke_shell()
124 self._ssh.read_until = self._read_until
125 self._rx = self._ssh
126 self.write("\n")
127
128 def _tty_close(self):
129 self._ssh_pre.close()
130 del self._ssh_pre
131
132 # -------------------------------------------------------------------------
133 # I/O read and write called from Terminal class
134 # -------------------------------------------------------------------------
135
136 def write(self, content):
137 """write content + <ENTER>"""
138 logger.debug("Write: %s" % content)
139 self._ssh.sendall(six.b((content + "\n")))
140
141 def rawwrite(self, content):
142 """write content as-is"""
143 logger.debug("rawwrite: %s" % content)
144 # If baud set to 0 write full speed
145 if int(self.baud) == 0:
146 self._ssh.sendall(content)
147 return None
148
149 # Write data according to defined baud
150 # per 1 byte of data there are 2 additional bits on the line
151 # (parity and stop bits)
152 if sys.version >= "3":
153 content = content.decode("utf-8")
154 for char in content:
155 self._ssh.sendall(six.b(char))
156 wtime = 10 / float(self.baud)
157 sleep(wtime) # do not remove
158
159 def read(self):
160 """read a single line"""
161 rxb = six.b("")
162 while True:
163 data = self._ssh.recv(self.RECVSZ)
164 if data is None or len(data) <= 0:
165 raise ValueError("Unable to detect device prompt")
166 elif PY6.NEW_LINE in data:
167 rxb += data.split(PY6.NEW_LINE)[0]
168 break
169 else:
170 rxb += data
171
172 return rxb
173
174 def read_prompt(self):
175 """
176 reads text from the serial console (using paramiko recv) until
177 a match is found against the :expect: regular-expression object.
178 When a match is found, return a tuple(<text>,<found>) where
179 <text> is the complete text and <found> is the name of the
180 regular-expression group. If a timeout occurs, then return
181 the tuple(None,None).
182 """
183 rxb = six.b("")
184 timeout = time() + self.READ_PROMPT_DELAY
185
186 while time() < timeout:
187 sleep(0.1)
188 rd, _, _ = select.select([self._ssh], [], [], 0.1)
189 sleep(0.05)
190 if rd:
191 rxb += self._ssh.recv(self.RECVSZ)
192 found = _PROMPT.search(rxb)
193 if found is not None:
194 break
195 timeout = time() + self.READ_PROMPT_DELAY
196 else:
197 return None, None
198 logger.debug("Got: %s" % rxb)
199 return rxb, found.lastgroup
200
201 def _read_until(self, match, timeout=None):
202 rxb = six.b("")
203 timeout = time() + self.READ_PROMPT_DELAY
204
205 while time() < timeout:
206 sleep(0.1)
207 rd, _, _ = select.select([self._ssh], [], [], 0.1)
208 sleep(0.05)
209 if rd:
210 rxb += self._ssh.recv(self.MAX_BUFFER)
211 if re.search(match, rxb):
212 return rxb
213
214 timeout = time() + self.READ_PROMPT_DELAY