From 8a0a67d2e2d8a0018e2ac33d80f34848519f1ebb Mon Sep 17 00:00:00 2001 From: Christopher Hunt Date: Wed, 27 Apr 2016 11:08:59 -0500 Subject: [PATCH] Added execute_cmds_via_open_connection * There are use cases where rather than SSH to a remote server to execute cmds, the connection to the remote server is already open, so use that connection to execute the commands. USE CASE (example): Execute cmds on/from proxy server: conn = connect_to_proxy(), and then use that connection to execute commands.) * Updated to better check if connection provided could be a connection Raise execption if it is not a pexpect.spawn object. Change-Id: Ie01aa891ecbfe76a1231cd0714ce5511bc4d05cc --- .../networks/common/proxy_mgr/ssh_util.py | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/cloudcafe/networking/networks/common/proxy_mgr/ssh_util.py b/cloudcafe/networking/networks/common/proxy_mgr/ssh_util.py index aadec13c..f8a91586 100644 --- a/cloudcafe/networking/networks/common/proxy_mgr/ssh_util.py +++ b/cloudcafe/networking/networks/common/proxy_mgr/ssh_util.py @@ -18,6 +18,12 @@ class MissingCredentials(SshUnableToConnect): MSG = 'Missing credentials to connect to: {ip} (Type: {t_type})' +class ConnectionNotFound(Exception): + def __str__(self): + return ('No open pexpect connection was provided. Was not type ' + 'pexpect.spawn') + + class SshResponse(object): str_concat = '{0!s}\n{1!s}' @@ -372,6 +378,32 @@ class SshMixin(object): self.last_response = response_obj return response_obj + def execute_cmds_via_open_connection( + self, connection, cmds, response_obj=None, close_conn=False): + """ + Execute the list of commands on the open connection + + @param connection: Open pexpect connection + @param cmds: list of commands to execute + @param response_obj: The SSH Response object; instantiated if !provided + @param close_conn: (Boolean), Close the connection when done? + @return: Populated response object + """ + + if not isinstance(connection, pexpect.spawn): + raise ConnectionNotFound() + + if response_obj is None: + response_obj = SshResponse() + response_obj.connection = connection + + args = {'response_obj': response_obj, 'cmds': cmds} + + response_obj = self._cmds_via_open_connection(**args) + if close_conn: + self.close_connections(response_obj) + return response_obj + def _cmds_via_open_connection(self, response_obj, cmds): """ SSH from the local host using pexpect.