Add SSH disconnect
[csit.git] / resources / libraries / python / ssh.py
index 2de6f4a..a94eec4 100644 (file)
@@ -18,7 +18,6 @@ from time import time
 from robot.api import logger
 from interruptingcow import timeout
 from robot.utils.asserts import assert_equal, assert_not_equal
-from socket import timeout as socket_timeout
 
 __all__ = ["exec_cmd", "exec_cmd_no_error"]
 
@@ -56,7 +55,8 @@ class SSH(object):
             self._ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
 
             self._ssh.connect(node['host'], username=node['username'],
-                              password=node.get('password'), pkey=pkey)
+                              password=node.get('password'), pkey=pkey,
+                              port=node['port'])
 
             SSH.__existing_connections[node_hash] = self._ssh
 
@@ -67,6 +67,17 @@ class SSH(object):
                 format(self._ssh.get_transport().getpeername()))
         logger.debug('Connections: {0}'.format(str(SSH.__existing_connections)))
 
+    def disconnect(self, node):
+        """Close SSH connection to the node.
+
+        :param node: The node to disconnect from.
+        :type node: dict
+        """
+        node_hash = self._node_hash(node)
+        if node_hash in SSH.__existing_connections:
+            ssh = SSH.__existing_connections.pop(node_hash)
+            ssh.close()
+
     def exec_command(self, cmd, timeout=10):
         """Execute SSH command on a new channel on the connected Node.
 
@@ -85,24 +96,16 @@ class SSH(object):
 
         stdout = ""
         while True:
-            try:
-                buf = chan.recv(self.__MAX_RECV_BUF)
-                stdout += buf
-                if not buf:
-                    break
-            except socket_timeout:
-                logger.trace('Channels stdout timeout occurred')
+            buf = chan.recv(self.__MAX_RECV_BUF)
+            stdout += buf
+            if not buf:
                 break
 
         stderr = ""
         while True:
-            try:
-                buf = chan.recv_stderr(self.__MAX_RECV_BUF)
-                stderr += buf
-                if not buf:
-                    break
-            except socket_timeout:
-                logger.trace('Channels stderr timeout occurred')
+            buf = chan.recv_stderr(self.__MAX_RECV_BUF)
+            stderr += buf
+            if not buf:
                 break
 
         return_code = chan.recv_exit_status()