1 ###############################################################################
2 # Copyright (c) 2015 Ericsson AB and others.
3 # szilard.cserey@ericsson.com
4 # peter.barabas@ericsson.com
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9 ###############################################################################
22 class SSHClient(object):
24 def __init__(self, host, username, password):
26 self.username = username
27 self.password = password
30 def open(self, timeout=TIMEOUT):
31 self.client = paramiko.SSHClient()
32 self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
33 self.client.connect(self.host, username=self.username,
34 password=self.password, look_for_keys=False,
38 if self.client is not None:
46 def __exit__(self, type, value, traceback):
49 def exec_cmd(self, command, check=True, sudo=False, timeout=TIMEOUT):
50 if sudo and self.username != 'root':
51 command = "sudo -S -p '' %s" % command
52 stdin, stdout, stderr = self.client.exec_command(command,
55 stdin.write(self.password + '\n')
57 response = stdout.read().strip()
58 error = stderr.read().strip()
63 raise Exception(error)
66 return response, error
68 def run(self, command):
69 transport = self.client.get_transport()
70 transport.set_keepalive(1)
71 chan = transport.open_session()
72 chan.exec_command(command)
73 while not chan.exit_status_ready():
75 data = chan.recv(1024)
78 data = chan.recv(1024)
80 if chan.recv_stderr_ready():
81 error_buff = chan.recv_stderr(1024)
83 log(error_buff.strip())
84 error_buff = chan.recv_stderr(1024)
85 return chan.recv_exit_status()
87 def scp_get(self, remote, local='.', dir=False):
89 with scp.SCPClient(self.client.get_transport(),
91 socket_timeout=TIMEOUT) as _scp:
92 _scp.get(remote, local, dir)
93 except Exception as e:
96 def scp_put(self, local, remote='.', dir=False):
98 with scp.SCPClient(self.client.get_transport(),
100 socket_timeout=TIMEOUT) as _scp:
101 _scp.put(local, remote, dir)
102 except Exception as e: