X-Git-Url: https://gerrit.fd.io/r/gitweb?a=blobdiff_plain;f=resources%2Flibraries%2Fpython%2Fssh.py;h=6914d528d6f8e48ff7f8a6af05d765c566fecd13;hb=43277be7e77afe0363f62c97c687bcfa506ee4b8;hp=a2bb9b1dc4862c6c9e7fe12ace77bdf0f1d99f10;hpb=8f285166faf13156a4f7c70adac9a7e20549268f;p=csit.git diff --git a/resources/libraries/python/ssh.py b/resources/libraries/python/ssh.py index a2bb9b1dc4..6914d528d6 100644 --- a/resources/libraries/python/ssh.py +++ b/resources/libraries/python/ssh.py @@ -10,6 +10,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +import socket import paramiko from paramiko import RSAKey import StringIO @@ -55,7 +56,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 @@ -66,13 +68,24 @@ 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. Returns (return_code, stdout, stderr). """ logger.trace('exec_command on {0}: {1}' - .format(self._ssh.get_transport().getpeername(), cmd)) + .format(self._ssh.get_transport().getpeername(), cmd)) start = time() chan = self._ssh.get_transport().open_session() if timeout is not None: @@ -83,11 +96,17 @@ class SSH(object): self._ssh.get_transport().getpeername(), end-start)) stdout = "" - while True: - buf = chan.recv(self.__MAX_RECV_BUF) - stdout += buf - if not buf: - break + try: + while True: + buf = chan.recv(self.__MAX_RECV_BUF) + stdout += buf + if not buf: + break + except socket.timeout: + logger.error('Caught timeout exception, current contents ' + 'of buffer: {0}'.format(stdout)) + raise + stderr = "" while True: @@ -99,7 +118,10 @@ class SSH(object): return_code = chan.recv_exit_status() logger.trace('chan_recv/_stderr took {} seconds'.format(time()-end)) - return (return_code, stdout, stderr) + logger.trace('return RC {}'.format(return_code)) + logger.trace('return STDOUT {}'.format(stdout)) + logger.trace('return STDERR {}'.format(stderr)) + return return_code, stdout, stderr def exec_command_sudo(self, cmd, cmd_input=None, timeout=10): """Execute SSH command with sudo on a new channel on the connected Node.