From 0a20cec2d9c913a0fa8efd402bf9f7b308b2956e Mon Sep 17 00:00:00 2001 From: Brendan Jackman Date: Wed, 3 May 2017 10:53:43 +0100 Subject: [PATCH] ssh: Combine exit code and main command This avoids a network round trip and speeds up SSH targets. --- devlib/utils/ssh.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/devlib/utils/ssh.py b/devlib/utils/ssh.py index ff30346..3ba8ae6 100644 --- a/devlib/utils/ssh.py +++ b/devlib/utils/ssh.py @@ -183,18 +183,26 @@ class SshConnection(object): def execute(self, command, timeout=None, check_exit_code=True, as_root=False, strip_colors=True): #pylint: disable=unused-argument + if command == '': + # Empty command is valid but the __devlib_ec stuff below will + # produce a syntax error with bash. Treat as a special case. + return '' try: with self.lock: - output = self._execute_and_wait_for_prompt(command, timeout, as_root, strip_colors) + _command = '({}); __devlib_ec=$?; echo; echo $__devlib_ec'.format(command) + raw_output = self._execute_and_wait_for_prompt( + _command, timeout, as_root, strip_colors) + output, exit_code_text, _ = raw_output.rsplit('\r\n', 2) if check_exit_code: - exit_code_text = self._execute_and_wait_for_prompt('echo $?', strip_colors=strip_colors, log=False) try: - exit_code = int(exit_code_text.split()[0]) + exit_code = int(exit_code_text) if exit_code: message = 'Got exit code {}\nfrom: {}\nOUTPUT: {}' raise TargetError(message.format(exit_code, command, output)) except (ValueError, IndexError): - logger.warning('Could not get exit code for "{}",\ngot: "{}"'.format(command, exit_code_text)) + logger.warning( + 'Could not get exit code for "{}",\ngot: "{}"'\ + .format(command, exit_code_text)) return output except EOF: raise TargetError('Connection lost.')