Exemplo n.º 1
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(quote(str(
         self.port))) if (self.port and self.port != 22) else ''
     keyfile_string = '-i {}'.format(quote(
         self.keyfile)) if self.keyfile else ''
     options = " ".join(
         ["-o{}={}".format(key, val) for key, val in self.options.items()])
     command = '{} {} -r {} {} {} {}'.format(scp, options, keyfile_string,
                                             port_string, quote(source),
                                             quote(dest))
     command_redacted = command
     logger.debug(command)
     if self.password:
         command, command_redacted = _give_password(self.password, command)
     try:
         check_output(command, timeout=timeout, shell=True)
     except subprocess.CalledProcessError as e:
         raise_from(
             HostError("Failed to copy file with '{}'. Output:\n{}".format(
                 command_redacted, e.output)), None)
     except TimeoutError as e:
         raise TimeoutError(command_redacted, e.output)
Exemplo n.º 2
0
def adb_shell(device,
              command,
              timeout=None,
              check_exit_code=False,
              as_root=False,
              newline_separator='\r\n'):  # NOQA
    _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]
        raw_output, error = check_output(actual_command, timeout, shell=False)
        if raw_output:
            try:
                output, exit_code, _ = raw_output.rsplit(newline_separator, 2)
            except ValueError:
                exit_code, _ = raw_output.rsplit(newline_separator, 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: {}'
                raise TargetError(
                    message.format(exit_code, full_command, output, error))
            elif AM_START_ERROR.findall(output):
                message = 'Could not start activity; got the following:'
                message += '\n{}'.format(AM_START_ERROR.findall(output)[0])
                raise TargetError(message)
        else:  # not all digits
            if AM_START_ERROR.findall(output):
                message = 'Could not start activity; got the following:\n{}'
                raise TargetError(
                    message.format(AM_START_ERROR.findall(output)[0]))
            else:
                message = 'adb has returned early; did not get an exit code. '\
                          'Was kill-server invoked?'
                raise TargetError(message)
    else:  # do not check exit code
        output, _ = check_output(full_command, timeout, shell=True)
    return output
Exemplo n.º 3
0
    def execute(self, command, timeout=None, check_exit_code=True,
                as_root=False, strip_colors=True, will_succeed=False):
        self.logger.debug(command)
        use_sudo = as_root and not self.connected_as_root
        if use_sudo:
            if self.unrooted:
                raise TargetStableError('unrooted')
            password = self._get_password()
            command = "echo {} | sudo -p ' ' -S -- sh -c {}".format(quote(password), quote(command))
        ignore = None if check_exit_code else 'all'
        try:
            stdout, stderr = check_output(command, shell=True, timeout=timeout, ignore=ignore)
        except subprocess.CalledProcessError as e:
            message = 'Got exit code {}\nfrom: {}\nOUTPUT: {}'.format(
                e.returncode, command, e.output)
            if will_succeed:
                raise TargetTransientError(message)
            else:
                raise TargetStableError(message)

        # Remove the one-character prompt of sudo -S -p
        if use_sudo and stderr:
            stderr = stderr[1:]

        return stdout + stderr
Exemplo n.º 4
0
def fastboot_command(command, timeout=None, device=None):
    _check_env()
    target = '-s {}'.format(device) if device else ''
    full_command = 'fastboot {} {}'.format(target, command)
    logger.debug(full_command)
    output, _ = check_output(full_command, timeout, shell=True)
    return output
Exemplo n.º 5
0
def adb_command(device, command, timeout=None):
    _check_env()
    device_string = ' -s {}'.format(device) if device else ''
    full_command = "adb{} {}".format(device_string, command)
    logger.debug(full_command)
    output, _ = check_output(full_command, timeout, shell=True)
    return output
Exemplo n.º 6
0
 def execute(self,
             command,
             timeout=None,
             check_exit_code=True,
             as_root=False,
             strip_colors=True,
             will_succeed=False):
     self.logger.debug(command)
     if as_root and not self.connected_as_root:
         if self.unrooted:
             raise TargetStableError('unrooted')
         password = self._get_password()
         command = 'echo {} | sudo -S -- sh -c '.format(
             quote(password)) + quote(command)
     ignore = None if check_exit_code else 'all'
     try:
         return check_output(command,
                             shell=True,
                             timeout=timeout,
                             ignore=ignore)[0]
     except subprocess.CalledProcessError as e:
         message = 'Got exit code {}\nfrom: {}\nOUTPUT: {}'.format(
             e.returncode, command, e.output)
         if will_succeed:
             raise TargetTransientError(message)
         else:
             raise TargetStableError(message)
Exemplo n.º 7
0
def fastboot_command(command, timeout=None, device=None):
    _check_env()
    target = '-s {}'.format(quote(device)) if device else ''
    full_command = 'fastboot {} {}'.format(target, command)
    logger.debug(full_command)
    output, _ = check_output(full_command, timeout, shell=True)
    return output
Exemplo n.º 8
0
def adb_connect(device, timeout=None, attempts=MAX_ATTEMPTS, adb_server=None):
    _check_env()
    tries = 0
    output = None
    while tries <= attempts:
        tries += 1
        if device:
            if "." in device:  # Connect is required only for ADB-over-IP
                # ADB does not automatically remove a network device from it's
                # devices list when the connection is broken by the remote, so the
                # adb connection may have gone "stale", resulting in adb blocking
                # indefinitely when making calls to the device. To avoid this,
                # always disconnect first.
                adb_disconnect(device, adb_server)
                adb_cmd = get_adb_command(None, 'connect', adb_server)
                command = '{} {}'.format(adb_cmd, quote(device))
                logger.debug(command)
                output, _ = check_output(command, shell=True, timeout=timeout)
        if _ping(device, adb_server):
            break
        time.sleep(10)
    else:  # did not connect to the device
        message = 'Could not connect to {}'.format(device or 'a device')
        if output:
            message += '; got: "{}"'.format(output)
        raise HostError(message)
def adb_command(device, command, timeout=None):
    _check_env()
    device_string = ' -s {}'.format(device) if device else ''
    full_command = "adb{} {}".format(device_string, command)
    logger.debug(full_command)
    output, _ = check_output(full_command, timeout, shell=True)
    return output
Exemplo n.º 10
0
def adb_shell(device,
              command,
              timeout=None,
              check_exit_code=False,
              as_root=False,
              adb_server=None):  # NOQA
    _check_env()
    if as_root:
        command = 'echo \'{}\' | su'.format(escape_single_quotes(command))
    device_part = []
    if adb_server:
        device_part = ['-H', adb_server]
    device_part += ['-s', device] if device else []

    # On older combinations of ADB/Android versions, the adb host command always
    # exits with 0 if it was able to run the command on the target, even if the
    # command failed (https://code.google.com/p/android/issues/detail?id=3254).
    # Homogenise this behaviour by running the command then echoing the exit
    # code.
    adb_shell_command = '({}); echo \"\n$?\"'.format(command)
    actual_command = ['adb'] + device_part + ['shell', adb_shell_command]
    logger.debug('adb {} shell {}'.format(' '.join(device_part), command))
    raw_output, error = check_output(actual_command, timeout, shell=False)
    if raw_output:
        try:
            output, exit_code, _ = raw_output.replace('\r\n', '\n').replace(
                '\r', '\n').rsplit('\n', 2)
        except ValueError:
            exit_code, _ = raw_output.replace('\r\n', '\n').replace(
                '\r', '\n').rsplit('\n', 1)
            output = ''
    else:  # raw_output is empty
        exit_code = '969696'  # just because
        output = ''

    if check_exit_code:
        exit_code = exit_code.strip()
        re_search = AM_START_ERROR.findall('{}\n{}'.format(output, error))
        if exit_code.isdigit():
            if int(exit_code):
                message = ('Got exit code {}\nfrom target command: {}\n'
                           'STDOUT: {}\nSTDERR: {}')
                raise TargetError(
                    message.format(exit_code, command, output, error))
            elif re_search:
                message = 'Could not start activity; got the following:\n{}'
                raise TargetError(message.format(re_search[0]))
        else:  # not all digits
            if re_search:
                message = 'Could not start activity; got the following:\n{}'
                raise TargetError(message.format(re_search[0]))
            else:
                message = 'adb has returned early; did not get an exit code. '\
                          'Was kill-server invoked?\nOUTPUT:\n-----\n{}\n'\
                          '-----\nERROR:\n-----\n{}\n-----'
                raise TargetError(message.format(raw_output, error))

    return output
Exemplo n.º 11
0
def adb_shell(device, command, timeout=None, check_exit_code=False,
              as_root=False, adb_server=None, su_cmd='su -c {}'):  # NOQA
    _check_env()

    # On older combinations of ADB/Android versions, the adb host command always
    # exits with 0 if it was able to run the command on the target, even if the
    # command failed (https://code.google.com/p/android/issues/detail?id=3254).
    # Homogenise this behaviour by running the command then echoing the exit
    # code of the executed command itself.
    command = r'({}); echo "\n$?"'.format(command)

    parts = ['adb']
    if adb_server is not None:
        parts += ['-H', adb_server]
    if device is not None:
        parts += ['-s', device]
    parts += ['shell',
              command if not as_root else su_cmd.format(quote(command))]

    logger.debug(' '.join(quote(part) for part in parts))
    try:
        raw_output, _ = check_output(parts, timeout, shell=False, combined_output=True)
    except subprocess.CalledProcessError as e:
        raise TargetStableError(str(e))

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

    if check_exit_code:
        exit_code = exit_code.strip()
        re_search = AM_START_ERROR.findall(output)
        if exit_code.isdigit():
            if int(exit_code):
                message = ('Got exit code {}\nfrom target command: {}\n'
                           'OUTPUT: {}')
                raise TargetStableError(message.format(exit_code, command, output))
            elif re_search:
                message = 'Could not start activity; got the following:\n{}'
                raise TargetStableError(message.format(re_search[0]))
        else:  # not all digits
            if re_search:
                message = 'Could not start activity; got the following:\n{}'
                raise TargetStableError(message.format(re_search[0]))
            else:
                message = 'adb has returned early; did not get an exit code. '\
                          'Was kill-server invoked?\nOUTPUT:\n-----\n{}\n'\
                          '-----'
                raise TargetTransientError(message.format(raw_output))

    return output
Exemplo n.º 12
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 subprocess.CalledProcessError(e.returncode, e.cmd.replace(pass_string, ""), e.output)
     except TimeoutError as e:
         raise TimeoutError(e.command.replace(pass_string, ""), e.output)
Exemplo n.º 13
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 subprocess.CalledProcessError(e.returncode, e.cmd.replace(pass_string, ''), e.output)
     except TimeoutError as e:
         raise TimeoutError(e.command.replace(pass_string, ''), e.output)
Exemplo n.º 14
0
def adb_shell(device, command, timeout=None, check_exit_code=False,
              as_root=False, newline_separator='\r\n'):  # NOQA
    _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]
        raw_output, error = check_output(actual_command, timeout, shell=False)
        if raw_output:
            try:
                output, exit_code, _ = raw_output.rsplit(newline_separator, 2)
            except ValueError:
                exit_code, _ = raw_output.rsplit(newline_separator, 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: {}'
                raise TargetError(message.format(exit_code, full_command, output, error))
            elif AM_START_ERROR.findall(output):
                message = 'Could not start activity; got the following:'
                message += '\n{}'.format(AM_START_ERROR.findall(output)[0])
                raise TargetError(message)
        else:  # not all digits
            if AM_START_ERROR.findall(output):
                message = 'Could not start activity; got the following:\n{}'
                raise TargetError(message.format(AM_START_ERROR.findall(output)[0]))
            else:
                message = 'adb has returned early; did not get an exit code. '\
                          'Was kill-server invoked?'
                raise TargetError(message)
    else:  # do not check exit code
        output, _ = check_output(full_command, timeout, shell=True)
    return output
Exemplo n.º 15
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)
     command_redacted = command
     logger.debug(command)
     if self.password:
         command = _give_password(self.password, command)
         command_redacted = command.replace(self.password, '<redacted>')
     try:
         check_output(command, timeout=timeout, shell=True)
     except subprocess.CalledProcessError as e:
         raise HostError("Failed to copy file with '{}'. Output:\n{}".format(
             command_redacted, e.output))
     except TimeoutError as e:
         raise TimeoutError(command_redacted, e.output)
Exemplo n.º 16
0
 def execute(self, command, timeout=None, check_exit_code=True, as_root=False):
     self.logger.debug(command)
     if as_root:
         if self.unrooted:
             raise TargetError("unrooted")
         password = self._get_password()
         command = "echo '{}' | sudo -S ".format(password) + command
     ignore = None if check_exit_code else "all"
     try:
         return check_output(command, shell=True, timeout=timeout, ignore=ignore)[0]
     except subprocess.CalledProcessError as e:
         raise TargetError(e)
Exemplo n.º 17
0
def adb_shell(device, command, timeout=None, check_exit_code=False,
              as_root=False, adb_server=None):  # NOQA
    _check_env()
    if as_root:
        command = 'echo \'{}\' | su'.format(escape_single_quotes(command))
    device_part = []
    if adb_server:
        device_part = ['-H', adb_server]
    device_part += ['-s', device] if device else []

    # On older combinations of ADB/Android versions, the adb host command always
    # exits with 0 if it was able to run the command on the target, even if the
    # command failed (https://code.google.com/p/android/issues/detail?id=3254).
    # Homogenise this behaviour by running the command then echoing the exit
    # code.
    adb_shell_command = '({}); echo \"\n$?\"'.format(command)
    actual_command = ['adb'] + device_part + ['shell', adb_shell_command]
    logger.debug('adb {} shell {}'.format(' '.join(device_part), command))
    raw_output, error = check_output(actual_command, timeout, shell=False)
    if raw_output:
        try:
            output, exit_code, _ = raw_output.replace('\r\n', '\n').replace('\r', '\n').rsplit('\n', 2)
        except ValueError:
            exit_code, _ = raw_output.replace('\r\n', '\n').replace('\r', '\n').rsplit('\n', 1)
            output = ''
    else:  # raw_output is empty
        exit_code = '969696'  # just because
        output = ''

    if check_exit_code:
        exit_code = exit_code.strip()
        re_search = AM_START_ERROR.findall('{}\n{}'.format(output, error))
        if exit_code.isdigit():
            if int(exit_code):
                message = ('Got exit code {}\nfrom target command: {}\n'
                           'STDOUT: {}\nSTDERR: {}')
                raise TargetError(message.format(exit_code, command, output, error))
            elif re_search:
                message = 'Could not start activity; got the following:\n{}'
                raise TargetError(message.format(re_search[0]))
        else:  # not all digits
            if re_search:
                message = 'Could not start activity; got the following:\n{}'
                raise TargetError(message.format(re_search[0]))
            else:
                message = 'adb has returned early; did not get an exit code. '\
                          'Was kill-server invoked?\nOUTPUT:\n-----\n{}\n'\
                          '-----\nERROR:\n-----\n{}\n-----'
                raise TargetError(message.format(raw_output, error))

    return output
Exemplo n.º 18
0
 def execute(self, command, timeout=None, check_exit_code=True,
             as_root=False, strip_colors=True):
     self.logger.debug(command)
     if as_root:
         if self.unrooted:
             raise TargetError('unrooted')
         password = self._get_password()
         command = 'echo \'{}\' | sudo -S '.format(password) + command
     ignore = None if check_exit_code else 'all'
     try:
         return check_output(command, shell=True, timeout=timeout, ignore=ignore)[0]
     except subprocess.CalledProcessError as e:
         message = 'Got exit code {}\nfrom: {}\nOUTPUT: {}'.format(
             e.returncode, command, e.output)
         raise TargetError(message)
Exemplo n.º 19
0
def adb_connect(device, timeout=None, attempts=MAX_ATTEMPTS):
    _check_env()
    tries = 0
    output = None
    while tries <= attempts:
        tries += 1
        if device:
            command = 'adb connect {}'.format(device)
            logger.debug(command)
            output, _ = check_output(command, shell=True, timeout=timeout)
        if _ping(device):
            break
        time.sleep(10)
    else:  # did not connect to the device
        message = 'Could not connect to {}'.format(device or 'a device')
        if output:
            message += '; got: "{}"'.format(output)
        raise HostError(message)
Exemplo n.º 20
0
def adb_connect(device, timeout=None, attempts=MAX_ATTEMPTS):
    _check_env()
    tries = 0
    output = None
    while tries <= attempts:
        tries += 1
        if device:
            command = 'adb connect {}'.format(device)
            logger.debug(command)
            output, _ = check_output(command, shell=True, timeout=timeout)
        if _ping(device):
            break
        time.sleep(10)
    else:  # did not connect to the device
        message = 'Could not connect to {}'.format(device or 'a device')
        if output:
            message += '; got: "{}"'.format(output)
        raise HostError(message)
Exemplo n.º 21
0
 def execute(self,
             command,
             timeout=None,
             check_exit_code=True,
             as_root=False):
     self.logger.debug(command)
     if as_root:
         if self.unrooted:
             raise TargetError('unrooted')
         password = self._get_password()
         command = 'echo \'{}\' | sudo -S '.format(password) + command
     ignore = None if check_exit_code else 'all'
     try:
         return check_output(command,
                             shell=True,
                             timeout=timeout,
                             ignore=ignore)[0]
     except subprocess.CalledProcessError as e:
         raise TargetError(e)
Exemplo n.º 22
0
def adb_connect(device, timeout=None, attempts=MAX_ATTEMPTS):
    _check_env()
    # Connect is required only for ADB-over-IP
    if "." not in device:
        logger.debug('Device connected via USB, connect not required')
        return
    tries = 0
    output = None
    while tries <= attempts:
        tries += 1
        if device:
            command = 'adb connect {}'.format(device)
            logger.debug(command)
            output, _ = check_output(command, shell=True, timeout=timeout)
        if _ping(device):
            break
        time.sleep(10)
    else:  # did not connect to the device
        message = 'Could not connect to {}'.format(device or 'a device')
        if output:
            message += '; got: "{}"'.format(output)
        raise HostError(message)
Exemplo n.º 23
0
def adb_connect(device, timeout=None, attempts=MAX_ATTEMPTS):
    _check_env()
    # Connect is required only for ADB-over-IP
    if "." not in device:
        logger.debug('Device connected via USB, connect not required')
        return
    tries = 0
    output = None
    while tries <= attempts:
        tries += 1
        if device:
            command = 'adb connect {}'.format(device)
            logger.debug(command)
            output, _ = check_output(command, shell=True, timeout=timeout)
        if _ping(device):
            break
        time.sleep(10)
    else:  # did not connect to the device
        message = 'Could not connect to {}'.format(device or 'a device')
        if output:
            message += '; got: "{}"'.format(output)
        raise HostError(message)
Exemplo n.º 24
0
def adb_command(device, command, timeout=None, adb_server=None):
    full_command = get_adb_command(device, command, adb_server)
    logger.debug(full_command)
    output, _ = check_output(full_command, timeout, shell=True)
    return output
Exemplo n.º 25
0
def adb_command(device, command, timeout=None,adb_server=None):
    full_command = get_adb_command(device, command, timeout, adb_server)
    logger.debug(full_command)
    output, _ = check_output(full_command, timeout, shell=True)
    return output
 def view(self, binfile):
     check_output('{} {}'.format(self.kernelshark, binfile), shell=True)
Exemplo n.º 27
0
 def view(self, binfile):
     check_output('{} {}'.format(self.kernelshark, binfile), shell=True)
Exemplo n.º 28
0
def fastboot_command(command, timeout=None):
    _check_env()
    full_command = "fastboot {}".format(command)
    logger.debug(full_command)
    output, _ = check_output(full_command, timeout, shell=True)
    return output
Exemplo n.º 29
0
def fastboot_command(command, timeout=None):
    _check_env()
    full_command = "fastboot {}".format(command)
    logger.debug(full_command)
    output, _ = check_output(full_command, timeout, shell=True)
    return output