2016-09-19 19:04:56 +00:00
|
|
|
# Copyright 2016 Google Inc.
|
|
|
|
#
|
|
|
|
# Use of this source code is governed by a BSD-style license that can be
|
|
|
|
# found in the LICENSE file.
|
|
|
|
|
2016-11-09 16:41:23 +00:00
|
|
|
from __future__ import print_function
|
2016-09-22 12:10:02 +00:00
|
|
|
import re
|
2017-10-20 15:58:32 +00:00
|
|
|
import time
|
2016-09-19 19:04:56 +00:00
|
|
|
import subprocess
|
2016-10-18 16:19:50 +00:00
|
|
|
import sys
|
2016-09-19 19:04:56 +00:00
|
|
|
|
2016-09-22 12:10:02 +00:00
|
|
|
class Adb:
|
2017-10-13 12:15:09 +00:00
|
|
|
def __init__(self, device_serial=None, adb_binary=None, echo=False):
|
|
|
|
self.__invocation = [adb_binary]
|
2016-09-22 12:10:02 +00:00
|
|
|
if device_serial:
|
|
|
|
self.__invocation.extend(['-s', device_serial])
|
2016-11-09 20:37:48 +00:00
|
|
|
self.__echo = echo
|
2016-11-09 16:41:23 +00:00
|
|
|
self.__is_root = None
|
2016-09-22 12:10:02 +00:00
|
|
|
|
|
|
|
def shell(self, cmd):
|
2016-11-09 20:37:48 +00:00
|
|
|
if self.__echo:
|
|
|
|
self.__echo_shell_cmd(cmd)
|
|
|
|
self.__invoke('shell', cmd)
|
2016-09-22 12:10:02 +00:00
|
|
|
|
|
|
|
def check(self, cmd):
|
2016-11-09 20:37:48 +00:00
|
|
|
if self.__echo:
|
|
|
|
self.__echo_shell_cmd(cmd)
|
2016-09-22 12:10:02 +00:00
|
|
|
result = subprocess.check_output(self.__invocation + ['shell', cmd])
|
2016-11-09 20:37:48 +00:00
|
|
|
if self.__echo:
|
|
|
|
print(result, file=sys.stderr)
|
2016-11-09 16:41:23 +00:00
|
|
|
return result
|
|
|
|
|
|
|
|
def root(self):
|
|
|
|
if not self.is_root():
|
2016-11-09 20:37:48 +00:00
|
|
|
self.__invoke('root')
|
|
|
|
self.__invoke('wait-for-device')
|
2016-11-09 16:41:23 +00:00
|
|
|
self.__is_root = None
|
|
|
|
return self.is_root()
|
2016-09-22 12:10:02 +00:00
|
|
|
|
|
|
|
def is_root(self):
|
2016-11-09 16:41:23 +00:00
|
|
|
if self.__is_root is None:
|
|
|
|
self.__is_root = ('root' == self.check('whoami').strip())
|
|
|
|
return self.__is_root
|
2016-09-22 12:10:02 +00:00
|
|
|
|
|
|
|
def remount(self):
|
2016-11-09 20:37:48 +00:00
|
|
|
self.__invoke('remount')
|
2016-11-09 16:41:23 +00:00
|
|
|
|
2017-10-20 15:58:32 +00:00
|
|
|
def reboot(self):
|
|
|
|
self.__is_root = None
|
|
|
|
self.shell('reboot')
|
|
|
|
self.__invoke('wait-for-device')
|
|
|
|
while '1' != self.check('getprop sys.boot_completed').strip():
|
|
|
|
time.sleep(1)
|
|
|
|
|
2016-11-09 20:37:48 +00:00
|
|
|
def __echo_shell_cmd(self, cmd):
|
2016-11-09 16:41:23 +00:00
|
|
|
escaped = [re.sub(r'([^a-zA-Z0-9])', r'\\\1', x)
|
|
|
|
for x in cmd.strip().splitlines()]
|
2016-11-09 20:37:48 +00:00
|
|
|
self.__invoke('shell', 'echo', '$(whoami)@$(getprop ro.serialno)$',
|
|
|
|
" '\n>' ".join(escaped))
|
|
|
|
|
|
|
|
def __invoke(self, *args):
|
|
|
|
subprocess.call(self.__invocation + list(args), stdout=sys.stderr)
|