import paramiko
-from cloud import common
+import common
+import scp
TIMEOUT = 600
-LOG = common.LOG
+log = common.log
+err = common.err
class SSHClient(object):
self.client.close()
self.client = None
- def execute(self, command, sudo=False, timeout=TIMEOUT):
+ def __enter__(self):
+ self.open()
+ return self
+
+ def __exit__(self, type, value, traceback):
+ self.close()
+
+ def exec_cmd(self, command, sudo=False, timeout=TIMEOUT, check=True):
if sudo and self.username != 'root':
command = "sudo -S -p '' %s" % command
stdin, stdout, stderr = self.client.exec_command(command,
if sudo:
stdin.write(self.password + '\n')
stdin.flush()
- return ''.join(''.join(stderr.readlines()) +
- ''.join(stdout.readlines()))
+ response = stdout.read().strip()
+ error = stderr.read().strip()
+
+ if check:
+ if error:
+ self.close()
+ err(error)
+ else:
+ return response
+ return response, error
def run(self, command):
transport = self.client.get_transport()
transport.set_keepalive(1)
chan = transport.open_session()
chan.exec_command(command)
-
while not chan.exit_status_ready():
if chan.recv_ready():
data = chan.recv(1024)
print error_buff
error_buff = chan.recv_stderr(1024)
exit_status = chan.recv_exit_status()
- LOG.debug('Exit status %s' % exit_status)
\ No newline at end of file
+ log('Exit status %s' % exit_status)
+
+ def scp_get(self, remote, local='.', dir=False):
+ try:
+ with scp.SCPClient(self.client.get_transport()) as _scp:
+ _scp.get(remote, local, dir)
+ except Exception as e:
+ err(e)
+
+ def scp_put(self, local, remote='.', dir=False):
+ try:
+ with scp.SCPClient(self.client.get_transport()) as _scp:
+ _scp.put(local, remote, dir)
+ except Exception as e:
+ err(e)