1 # Copyright (c) 2018 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
6 # http://www.apache.org/licenses/LICENSE-2.0
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
14 """Library for SSH connection management."""
17 from time import time, sleep
21 from paramiko import RSAKey
22 from paramiko.ssh_exception import SSHException
23 from scp import SCPClient
24 from robot.api import logger
26 __all__ = ["exec_cmd", "exec_cmd_no_error"]
31 class SSHTimeout(Exception):
32 """This exception is raised when a timeout occurs."""
37 """Contains methods for managing and using SSH connections."""
39 __MAX_RECV_BUF = 10*1024*1024
40 __existing_connections = {}
48 """Get IP address and port hash from node dictionary.
50 :param node: Node in topology.
52 :returns: IP address and port for the specified node.
56 return hash(frozenset([node['host'], node['port']]))
58 def connect(self, node, attempts=5):
59 """Connect to node prior to running exec_command or scp.
61 If there already is a connection to the node, this method reuses it.
63 :param node: Node in topology.
64 :param attempts: Number of reconnect attempts.
67 :raises IOError: If cannot connect to host.
70 node_hash = self._node_hash(node)
71 if node_hash in SSH.__existing_connections:
72 self._ssh = SSH.__existing_connections[node_hash]
73 if self._ssh.get_transport().is_active():
74 logger.debug('Reusing SSH: {ssh}'.format(ssh=self._ssh))
77 self._reconnect(attempts-1)
79 raise IOError('Cannot connect to {host}'.
80 format(host=node['host']))
85 if 'priv_key' in node:
86 pkey = RSAKey.from_private_key(
87 StringIO.StringIO(node['priv_key']))
89 self._ssh = paramiko.SSHClient()
90 self._ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
92 self._ssh.connect(node['host'], username=node['username'],
93 password=node.get('password'), pkey=pkey,
96 self._ssh.get_transport().set_keepalive(10)
98 SSH.__existing_connections[node_hash] = self._ssh
99 logger.debug('New SSH to {peer} took {total} seconds: {ssh}'.
101 peer=self._ssh.get_transport().getpeername(),
102 total=(time() - start),
105 raise IOError('Cannot connect to {host}'.
106 format(host=node['host']))
108 def disconnect(self, node):
109 """Close SSH connection to the node.
111 :param node: The node to disconnect from.
114 node_hash = self._node_hash(node)
115 if node_hash in SSH.__existing_connections:
116 logger.debug('Disconnecting peer: {host}, {port}'.
117 format(host=node['host'], port=node['port']))
118 ssh = SSH.__existing_connections.pop(node_hash)
121 def _reconnect(self, attempts=0):
122 """Close the SSH connection and open it again.
124 :param attempts: Number of reconnect attempts.
128 self.disconnect(node)
129 self.connect(node, attempts)
130 logger.debug('Reconnecting peer done: {host}, {port}'.
131 format(host=node['host'], port=node['port']))
133 def exec_command(self, cmd, timeout=10):
134 """Execute SSH command on a new channel on the connected Node.
136 :param cmd: Command to run on the Node.
137 :param timeout: Maximal time in seconds to wait until the command is
138 done. If set to None then wait forever.
141 :return return_code, stdout, stderr
142 :rtype: tuple(int, str, str)
143 :raise SSHTimeout: If command is not finished in timeout time.
145 stdout = StringIO.StringIO()
146 stderr = StringIO.StringIO()
148 chan = self._ssh.get_transport().open_session(timeout=5)
149 peer = self._ssh.get_transport().getpeername()
150 except AttributeError:
152 chan = self._ssh.get_transport().open_session(timeout=5)
153 peer = self._ssh.get_transport().getpeername()
156 chan = self._ssh.get_transport().open_session(timeout=5)
157 peer = self._ssh.get_transport().getpeername()
158 chan.settimeout(timeout)
160 logger.trace('exec_command on {peer} with timeout {timeout}: {cmd}'
161 .format(peer=peer, timeout=timeout, cmd=cmd))
164 chan.exec_command(cmd)
165 while not chan.exit_status_ready() and timeout is not None:
166 if chan.recv_ready():
167 stdout.write(chan.recv(self.__MAX_RECV_BUF))
169 if chan.recv_stderr_ready():
170 stderr.write(chan.recv_stderr(self.__MAX_RECV_BUF))
172 if time() - start > timeout:
174 'Timeout exception during execution of command: {cmd}\n'
175 'Current contents of stdout buffer: {stdout}\n'
176 'Current contents of stderr buffer: {stderr}\n'
177 .format(cmd=cmd, stdout=stdout.getvalue(),
178 stderr=stderr.getvalue())
182 return_code = chan.recv_exit_status()
184 while chan.recv_ready():
185 stdout.write(chan.recv(self.__MAX_RECV_BUF))
187 while chan.recv_stderr_ready():
188 stderr.write(chan.recv_stderr(self.__MAX_RECV_BUF))
191 logger.trace('exec_command on {peer} took {total} seconds'.
192 format(peer=peer, total=end-start))
194 logger.trace('return RC {rc}'.format(rc=return_code))
195 logger.trace('return STDOUT {stdout}'.format(stdout=stdout.getvalue()))
196 logger.trace('return STDERR {stderr}'.format(stderr=stderr.getvalue()))
197 return return_code, stdout.getvalue(), stderr.getvalue()
199 def exec_command_sudo(self, cmd, cmd_input=None, timeout=30):
200 """Execute SSH command with sudo on a new channel on the connected Node.
202 :param cmd: Command to be executed.
203 :param cmd_input: Input redirected to the command.
204 :param timeout: Timeout.
205 :returns: return_code, stdout, stderr
209 >>> from ssh import SSH
211 >>> ssh.connect(node)
212 >>> # Execute command without input (sudo -S cmd)
213 >>> ssh.exec_command_sudo("ifconfig eth0 down")
214 >>> # Execute command with input (sudo -S cmd <<< "input")
215 >>> ssh.exec_command_sudo("vpp_api_test", "dump_interface_table")
217 if cmd_input is None:
218 command = 'sudo -S {c}'.format(c=cmd)
220 command = 'sudo -S {c} <<< "{i}"'.format(c=cmd, i=cmd_input)
221 return self.exec_command(command, timeout)
223 def exec_command_lxc(self, lxc_cmd, lxc_name, lxc_params='', sudo=True,
225 """Execute command in LXC on a new SSH channel on the connected Node.
227 :param lxc_cmd: Command to be executed.
228 :param lxc_name: LXC name.
229 :param lxc_params: Additional parameters for LXC attach.
230 :param sudo: Run in privileged LXC mode. Default: privileged
231 :param timeout: Timeout.
234 :type lxc_params: str
237 :returns: return_code, stdout, stderr
239 command = "lxc-attach {p} --name {n} -- /bin/sh -c '{c}'"\
240 .format(p=lxc_params, n=lxc_name, c=lxc_cmd)
243 command = 'sudo -S {c}'.format(c=command)
244 return self.exec_command(command, timeout)
246 def interactive_terminal_open(self, time_out=45):
247 """Open interactive terminal on a new channel on the connected Node.
249 :param time_out: Timeout in seconds.
250 :returns: SSH channel with opened terminal.
252 .. warning:: Interruptingcow is used here, and it uses
253 signal(SIGALRM) to let the operating system interrupt program
254 execution. This has the following limitations: Python signal
255 handlers only apply to the main thread, so you cannot use this
256 from other threads. You must not use this in a program that
257 uses SIGALRM itself (this includes certain profilers)
259 chan = self._ssh.get_transport().open_session()
262 chan.settimeout(int(time_out))
263 chan.set_combine_stderr(True)
266 while not buf.endswith((":~# ", ":~$ ", "~]$ ", "~]# ")):
268 chunk = chan.recv(self.__MAX_RECV_BUF)
272 if chan.exit_status_ready():
273 logger.error('Channel exit status ready')
275 except socket.timeout:
276 logger.error('Socket timeout: {0}'.format(buf))
277 raise Exception('Socket timeout: {0}'.format(buf))
280 def interactive_terminal_exec_command(self, chan, cmd, prompt):
281 """Execute command on interactive terminal.
283 interactive_terminal_open() method has to be called first!
285 :param chan: SSH channel with opened terminal.
286 :param cmd: Command to be executed.
287 :param prompt: Command prompt, sequence of characters used to
288 indicate readiness to accept commands.
289 :returns: Command output.
291 .. warning:: Interruptingcow is used here, and it uses
292 signal(SIGALRM) to let the operating system interrupt program
293 execution. This has the following limitations: Python signal
294 handlers only apply to the main thread, so you cannot use this
295 from other threads. You must not use this in a program that
296 uses SIGALRM itself (this includes certain profilers)
298 chan.sendall('{c}\n'.format(c=cmd))
300 while not buf.endswith(prompt):
302 chunk = chan.recv(self.__MAX_RECV_BUF)
306 if chan.exit_status_ready():
307 logger.error('Channel exit status ready')
309 except socket.timeout:
310 logger.error('Socket timeout during execution of command: '
311 '{0}\nBuffer content:\n{1}'.format(cmd, buf))
312 raise Exception('Socket timeout during execution of command: '
313 '{0}\nBuffer content:\n{1}'.format(cmd, buf))
314 tmp = buf.replace(cmd.replace('\n', ''), '')
316 tmp.replace(item, '')
320 def interactive_terminal_close(chan):
321 """Close interactive terminal SSH channel.
323 :param: chan: SSH channel to be closed.
327 def scp(self, local_path, remote_path, get=False, timeout=30):
328 """Copy files from local_path to remote_path or vice versa.
330 connect() method has to be called first!
332 :param local_path: Path to local file that should be uploaded; or
333 path where to save remote file.
334 :param remote_path: Remote path where to place uploaded file; or
335 path to remote file which should be downloaded.
336 :param get: scp operation to perform. Default is put.
337 :param timeout: Timeout value in seconds.
338 :type local_path: str
339 :type remote_path: str
344 logger.trace('SCP {0} to {1}:{2}'.format(
345 local_path, self._ssh.get_transport().getpeername(),
348 logger.trace('SCP {0}:{1} to {2}'.format(
349 self._ssh.get_transport().getpeername(), remote_path,
351 # SCPCLient takes a paramiko transport as its only argument
352 scp = SCPClient(self._ssh.get_transport(), socket_timeout=timeout)
355 scp.put(local_path, remote_path)
357 scp.get(remote_path, local_path)
360 logger.trace('SCP took {0} seconds'.format(end-start))
363 def exec_cmd(node, cmd, timeout=600, sudo=False):
364 """Convenience function to ssh/exec/return rc, out & err.
366 Returns (rc, stdout, stderr).
369 raise TypeError('Node parameter is None')
371 raise TypeError('Command parameter is None')
373 raise ValueError('Empty command parameter')
378 except SSHException as err:
379 logger.error("Failed to connect to node" + str(err))
380 return None, None, None
384 (ret_code, stdout, stderr) = ssh.exec_command(cmd, timeout=timeout)
386 (ret_code, stdout, stderr) = ssh.exec_command_sudo(cmd,
388 except SSHException as err:
390 return None, None, None
392 return ret_code, stdout, stderr
395 def exec_cmd_no_error(node, cmd, timeout=600, sudo=False, message=None):
396 """Convenience function to ssh/exec/return out & err.
398 Verifies that return code is zero.
400 :param node: DUT node.
401 :param cmd: Command to be executed.
402 :param timeout: Timeout value in seconds. Default: 600.
403 :param sudo: Sudo privilege execution flag. Default: False.
404 :param message: Error message in case of failure. Default: None.
410 :returns: Stdout, Stderr.
411 :rtype: tuple(str, str)
412 :raise RuntimeError: If bash return code is not 0.
414 ret_code, stdout, stderr = exec_cmd(node, cmd, timeout=timeout, sudo=sudo)
415 msg = ('Command execution failed: "{cmd}"\n{stderr}'.
416 format(cmd=cmd, stderr=stderr) if message is None else message)
418 raise RuntimeError(msg)
420 return stdout, stderr