9 class SSHClient(object):
11 def __init__(self, host, username, password):
13 self.username = username
14 self.password = password
17 def open(self, timeout=TIMEOUT):
18 self.client = paramiko.SSHClient()
19 self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
20 self.client.connect(self.host, username=self.username,
21 password=self.password, timeout=timeout)
24 if self.client is not None:
32 def __exit__(self, type, value, traceback):
35 def exec_cmd(self, command, sudo=False, timeout=TIMEOUT, check=True):
36 if sudo and self.username != 'root':
37 command = "sudo -S -p '' %s" % command
38 stdin, stdout, stderr = self.client.exec_command(command,
41 stdin.write(self.password + '\n')
43 response = stdout.read().strip()
44 error = stderr.read().strip()
52 return response, error
54 def run(self, command):
55 transport = self.client.get_transport()
56 transport.set_keepalive(1)
57 chan = transport.open_session()
58 chan.exec_command(command)
59 while not chan.exit_status_ready():
61 data = chan.recv(1024)
64 data = chan.recv(1024)
66 if chan.recv_stderr_ready():
67 error_buff = chan.recv_stderr(1024)
70 error_buff = chan.recv_stderr(1024)
71 exit_status = chan.recv_exit_status()
72 log('Exit status %s' % exit_status)
74 def scp_get(self, remote, local='.', dir=False):
76 with scp.SCPClient(self.client.get_transport()) as _scp:
77 _scp.get(remote, local, dir)
78 except Exception as e:
81 def scp_put(self, local, remote='.', dir=False):
83 with scp.SCPClient(self.client.get_transport()) as _scp:
84 _scp.put(local, remote, dir)
85 except Exception as e: