1 ###############################################################################
2 # Copyright (c) 2015 Ericsson AB and others.
3 # szilard.cserey@ericsson.com
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ###############################################################################
20 class SSHClient(object):
22 def __init__(self, host, username, password):
24 self.username = username
25 self.password = password
28 def open(self, timeout=TIMEOUT):
29 self.client = paramiko.SSHClient()
30 self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
31 self.client.connect(self.host, username=self.username,
32 password=self.password, look_for_keys=False,
36 if self.client is not None:
44 def __exit__(self, type, value, traceback):
47 def exec_cmd(self, command, check=True, sudo=False, timeout=TIMEOUT):
48 if sudo and self.username != 'root':
49 command = "sudo -S -p '' %s" % command
50 stdin, stdout, stderr = self.client.exec_command(command,
53 stdin.write(self.password + '\n')
55 response = stdout.read().strip()
56 error = stderr.read().strip()
64 return response, error
66 def run(self, command):
67 transport = self.client.get_transport()
68 transport.set_keepalive(1)
69 chan = transport.open_session()
70 chan.exec_command(command)
71 while not chan.exit_status_ready():
73 data = chan.recv(1024)
76 data = chan.recv(1024)
78 if chan.recv_stderr_ready():
79 error_buff = chan.recv_stderr(1024)
81 log(error_buff.strip())
82 error_buff = chan.recv_stderr(1024)
83 return chan.recv_exit_status()
85 def scp_get(self, remote, local='.', dir=False):
87 with scp.SCPClient(self.client.get_transport()) as _scp:
88 _scp.get(remote, local, dir)
89 except Exception as e:
92 def scp_put(self, local, remote='.', dir=False):
94 with scp.SCPClient(self.client.get_transport()) as _scp:
95 _scp.put(local, remote, dir)
96 except Exception as e: