Example #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
Example #2
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
Example #3
0
def adb_background_shell(device, command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, as_root=False):
    """Runs the sepcified command in a subprocess, returning the the Popen object."""
    _check_env()
    if as_root:
        command = 'echo \'{}\' | su'.format(escape_single_quotes(command))
    device_string = '-s {}'.format(device) if device else ''
    full_command = 'adb {} shell "{}"'.format(device_string, escape_double_quotes(command))
    logger.debug(full_command)
    return subprocess.Popen(full_command, stdout=stdout, stderr=stderr, shell=True)
def adb_background_shell(device, command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, as_root=False):
    """Runs the sepcified command in a subprocess, returning the the Popen object."""
    _check_env()
    if as_root:
        command = 'echo \'{}\' | su'.format(escape_single_quotes(command))
    device_string = '-s {}'.format(device) if device else ''
    full_command = 'adb {} shell "{}"'.format(device_string, escape_double_quotes(command))
    logger.debug(full_command)
    return subprocess.Popen(full_command, stdout=stdout, stderr=stderr, shell=True)
Example #5
0
def adb_shell(device, command, timeout=None, check_exit_code=False, as_root=False):  # NOQA
    _check_env()
    if as_root:
        command = 'echo \'{}\' | su'.format(escape_single_quotes(command))
    device_string = '-s {}'.format(device) if device else ''
    full_command = 'adb {} shell "{}"'.format(device_string, escape_double_quotes(command))
    logger.debug(full_command)
    if check_exit_code:
        actual_command = "adb {} shell '({}); echo; echo $?'".format(device_string, escape_single_quotes(command))
        raw_output, error = check_output(actual_command, timeout, shell=True)
        if raw_output:
            try:
                output, exit_code, _ = raw_output.rsplit('\r\n', 2)
            except ValueError:
                exit_code, _ = raw_output.rsplit('\r\n', 1)
                output = ''
        else:  # raw_output is empty
            exit_code = '969696'  # just because
            output = ''

        exit_code = exit_code.strip()
        if exit_code.isdigit():
            if int(exit_code):
                message = 'Got exit code {}\nfrom: {}\nSTDOUT: {}\nSTDERR: {}'.format(exit_code, full_command,
                                                                                      output, error)
                raise DeviceError(message)
            elif am_start_error.findall(output):
                message = 'Could not start activity; got the following:'
                message += '\n{}'.format(am_start_error.findall(output)[0])
                raise DeviceError(message)
        else:  # not all digits
            if am_start_error.findall(output):
                message = 'Could not start activity; got the following:'
                message += '\n{}'.format(am_start_error.findall(output)[0])
                raise DeviceError(message)
            else:
                raise DeviceError('adb has returned early; did not get an exit code. Was kill-server invoked?')
    else:  # do not check exit code
        output, _ = check_output(full_command, timeout, shell=True)
    return output
Example #6
0
def adb_shell(device,
              command,
              timeout=None,
              check_exit_code=False,
              as_root=False):  # NOQA
    _check_env()
    if as_root:
        command = 'echo "{}" | su'.format(escape_double_quotes(command))
    device_string = '-s {}'.format(device) if device else ''
    full_command = 'adb {} shell "{}"'.format(device_string,
                                              escape_double_quotes(command))
    logger.debug(full_command)
    if check_exit_code:
        actual_command = "adb {} shell '({}); echo $?'".format(
            device_string, escape_single_quotes(command))
        raw_output, error = check_output(actual_command, timeout, shell=True)
        if raw_output:
            try:
                output, exit_code, _ = raw_output.rsplit('\n', 2)
            except ValueError:
                exit_code, _ = raw_output.rsplit('\n', 1)
                output = ''
        else:  # raw_output is empty
            exit_code = '969696'  # just because
            output = ''

        exit_code = exit_code.strip()
        if exit_code.isdigit():
            if int(exit_code):
                message = 'Got exit code {}\nfrom: {}\nSTDOUT: {}\nSTDERR: {}'.format(
                    exit_code, full_command, output, error)
                raise DeviceError(message)
            elif am_start_error.findall(output):
                message = 'Could not start activity; got the following:'
                message += '\n{}'.format(am_start_error.findall(output)[0])
                raise DeviceError(message)
        else:  # not all digits
            if am_start_error.findall(output):
                message = 'Could not start activity; got the following:'
                message += '\n{}'.format(am_start_error.findall(output)[0])
                raise DeviceError(message)
            else:
                raise DeviceError(
                    'adb has returned early; did not get an exit code. Was kill-server invoked?'
                )
    else:  # do not check exit code
        output, _ = check_output(full_command, timeout, shell=True)
    return output
Example #7
0
def adb_shell(device, command, timeout=None, check_exit_code=False, as_root=False):  # NOQA
    # pylint: disable=too-many-branches, too-many-locals, too-many-statements
    _check_env()
    if as_root:
        command = 'echo \'{}\' | su'.format(escape_single_quotes(command))
    device_string = '-s {}'.format(device) if device else ''
    full_command = 'adb {} shell "{}"'.format(device_string, escape_double_quotes(command))
    logger.debug(full_command)
    if check_exit_code:
        actual_command = "adb {} shell '({}); echo; echo $?'".format(device_string, escape_single_quotes(command))
        try:
            raw_output, error = check_output(actual_command, timeout, shell=True)
        except CalledProcessErrorWithStderr as e:
            raw_output = e.output
            error = e.error
            exit_code = e.returncode
            if exit_code == 1:
                logger.debug("Exit code 1 could be either the return code of the command or mean ADB failed")

        if raw_output:
            if raw_output.endswith('\r\n'):
                newline = '\r\n'
            elif raw_output.endswith('\n'):
                newline = '\n'
            else:
                raise WAError("Unknown new line separator in: {}".format(raw_output))

            try:
                output, exit_code, _ = raw_output.rsplit(newline, 2)
            except ValueError:
                exit_code, _ = raw_output.rsplit(newline, 1)
                output = ''
        else:  # raw_output is empty
            exit_code = '969696'  # just because
            output = ''

        exit_code = exit_code.strip()
        if exit_code.isdigit():
            if int(exit_code):
                message = 'Got exit code {}\nfrom: {}\nSTDOUT: {}\nSTDERR: {}'.format(exit_code, full_command,
                                                                                      output, error)
                raise DeviceError(message)
            elif am_start_error.findall(output):
                message = 'Could not start activity; got the following:'
                message += '\n{}'.format(am_start_error.findall(output)[0])
                raise DeviceError(message)
        else:  # not all digits
            if am_start_error.findall(output):
                message = 'Could not start activity; got the following:'
                message += '\n{}'.format(am_start_error.findall(output)[0])
                raise DeviceError(message)
            else:
                raise DeviceError('adb has returned early; did not get an exit code. Was kill-server invoked?')
    else:  # do not check exit code
        try:
            output, _ = check_output(full_command, timeout, shell=True)
        except CalledProcessErrorWithStderr as e:
            output = e.output
            error = e.error
            exit_code = e.returncode
            if e.returncode == 1:
                logger.debug("Got Exit code 1, could be either the return code of the command or mean ADB failed")
    return output
Example #8
0
def adb_shell(device,
              command,
              timeout=None,
              check_exit_code=False,
              as_root=False):  # NOQA
    # pylint: disable=too-many-branches, too-many-locals, too-many-statements
    _check_env()
    if as_root:
        command = 'echo \'{}\' | su'.format(escape_single_quotes(command))
    device_part = ['-s', device] if device else []
    device_string = ' {} {}'.format(*device_part) if device_part else ''
    full_command = 'adb{} shell "{}"'.format(device_string,
                                             escape_double_quotes(command))
    logger.debug(full_command)
    if check_exit_code:
        adb_shell_command = '({}); echo \"\n$?\"'.format(command)
        actual_command = ['adb'] + device_part + ['shell', adb_shell_command]
        try:
            raw_output, error = check_output(actual_command,
                                             timeout,
                                             shell=False)
        except CalledProcessErrorWithStderr as e:
            raw_output = e.output
            error = e.error
            exit_code = e.returncode
            if exit_code == 1:
                logger.debug(
                    "Exit code 1 could be either the return code of the command or mean ADB failed"
                )

        if raw_output:
            if raw_output.endswith('\r\n'):
                newline = '\r\n'
            elif raw_output.endswith('\n'):
                newline = '\n'
            else:
                raise WAError(
                    "Unknown new line separator in: {}".format(raw_output))

            try:
                output, exit_code, _ = raw_output.rsplit(newline, 2)
            except ValueError:
                exit_code, _ = raw_output.rsplit(newline, 1)
                output = ''
        else:  # raw_output is empty
            exit_code = '969696'  # just because
            output = ''

        exit_code = exit_code.strip()
        if exit_code.isdigit():
            if int(exit_code):
                message = 'Got exit code {}\nfrom: {}\nSTDOUT: {}\nSTDERR: {}'.format(
                    exit_code, full_command, output, error)
                raise DeviceError(message)
            elif am_start_error.findall(output):
                message = 'Could not start activity; got the following:'
                message += '\n{}'.format(am_start_error.findall(output)[0])
                raise DeviceError(message)
        else:  # not all digits
            if am_start_error.findall(output):
                message = 'Could not start activity; got the following:'
                message += '\n{}'.format(am_start_error.findall(output)[0])
                raise DeviceError(message)
            else:
                message = 'adb has returned early; did not get an exit code. '\
                          'Was kill-server invoked?\nOUTPUT:\n-----\n{}\n'\
                          '-----ERROR:\n-----\n{}\n-----'
                raise DeviceError(message.format(raw_output, error))
    else:  # do not check exit code
        try:
            output, error = check_output(full_command, timeout, shell=True)
            if output is None:
                output = error
            elif error is not None:
                output = '\n'.join([output, error])
        except CalledProcessErrorWithStderr as e:
            output = e.error or e.output
            exit_code = e.returncode
            if e.returncode == 1:
                logger.debug(
                    "Got Exit code 1, could be either the return code of the command or mean ADB failed"
                )
    return output