Autodeploy inspired on Prototype #2
[genesis.git] / fuel / deploy / ssh_client.py
similarity index 61%
rename from fuel/deploy/cloud_deploy/ssh_client.py
rename to fuel/deploy/ssh_client.py
index b9aad6c..9ea227a 100644 (file)
@@ -1,8 +1,10 @@
 import paramiko
-from cloud import common
+import common
+import scp
 
 TIMEOUT = 600
-LOG = common.LOG
+log = common.log
+err = common.err
 
 class SSHClient(object):
 
@@ -23,7 +25,14 @@ 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,
@@ -31,15 +40,22 @@ class SSHClient(object):
         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)
@@ -53,4 +69,18 @@ class SSHClient(object):
                     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)