Beispiel #1
0
 def _execute_and_wait_for_prompt(self, command, timeout=None, as_root=False, strip_colors=True, log=True):
     self.conn.prompt(0.1)  # clear an existing prompt if there is one.
     if as_root:
         command = "sudo -- sh -c '{}'".format(escape_single_quotes(command))
         if log:
             logger.debug(command)
         self.conn.sendline(command)
         index = self.conn.expect_exact([self.password_prompt, TIMEOUT], timeout=0.5)
         if index == 0:
             self.conn.sendline(self.password)
         timed_out = self._wait_for_prompt(timeout)
         output = re.sub(r' \r([^\n])', r'\1', self.conn.before)
         output = process_backspaces(output)
         output = re.sub(r'.*?{}'.format(re.escape(command)), '', output, 1).strip()
     else:
         if log:
             logger.debug(command)
         self.conn.sendline(command)
         timed_out = self._wait_for_prompt(timeout)
         # the regex removes line breaks potential introduced when writing
         # command to shell.
         output = re.sub(r' \r([^\n])', r'\1', self.conn.before)
         output = process_backspaces(output)
         command_index = output.find(command)
         output = output[command_index + len(command):].strip()
     if timed_out:
         self.cancel_running_command()
         raise TimeoutError(command, output)
     if strip_colors:
         output = strip_bash_colors(output)
     return output
Beispiel #2
0
 def _scp(self, source, dest, timeout=30):
     # NOTE: the version of scp in Ubuntu 12.04 occasionally (and bizarrely)
     # fails to connect to a device if port is explicitly specified using -P
     # option, even if it is the default port, 22. To minimize this problem,
     # only specify -P for scp if the port is *not* the default.
     port_string = '-P {}'.format(self.port) if (self.port and self.port != 22) else ''
     keyfile_string = '-i {}'.format(self.keyfile) if self.keyfile else ''
     command = '{} -r {} {} {} {}'.format(scp, keyfile_string, port_string, source, dest)
     pass_string = ''
     logger.debug(command)
     if self.password:
         command = _give_password(self.password, command)
     try:
         check_output(command, timeout=timeout, shell=True)
     except subprocess.CalledProcessError as e:
         raise CalledProcessErrorWithStderr(e.returncode,
                                            e.cmd.replace(pass_string, ''),
                                            output=e.output,
                                            error=getattr(e, 'error', ''))
     except TimeoutError as e:
         raise TimeoutError(e.command.replace(pass_string, ''), e.output)