OLD | NEW |
1 # Copyright 2016 Google Inc. | 1 # Copyright 2016 Google Inc. |
2 # | 2 # |
3 # Use of this source code is governed by a BSD-style license that can be | 3 # Use of this source code is governed by a BSD-style license that can be |
4 # found in the LICENSE file. | 4 # found in the LICENSE file. |
5 | 5 |
| 6 from __future__ import print_function |
6 import re | 7 import re |
7 import subprocess | 8 import subprocess |
8 import sys | 9 import sys |
9 | 10 |
10 class Adb: | 11 class Adb: |
11 def __init__(self, device_serial=None): | 12 def __init__(self, device_serial=None, echofile=None): |
12 self.__invocation = ['adb'] | 13 self.__invocation = ['adb'] |
13 if device_serial: | 14 if device_serial: |
14 self.__invocation.extend(['-s', device_serial]) | 15 self.__invocation.extend(['-s', device_serial]) |
| 16 self.__echofile = echofile |
| 17 self.__is_root = None |
15 | 18 |
16 def shell(self, cmd): | 19 def shell(self, cmd): |
| 20 if self.__echofile: |
| 21 self.__echo_cmd(cmd) |
17 subprocess.call(self.__invocation + ['shell', cmd], stdout=sys.stderr) | 22 subprocess.call(self.__invocation + ['shell', cmd], stdout=sys.stderr) |
18 | 23 |
19 def check(self, cmd): | 24 def check(self, cmd): |
| 25 if self.__echofile: |
| 26 self.__echo_cmd(cmd) |
20 result = subprocess.check_output(self.__invocation + ['shell', cmd]) | 27 result = subprocess.check_output(self.__invocation + ['shell', cmd]) |
21 return result.rstrip() | 28 if self.__echofile: |
| 29 print(result, file=self.__echofile) |
| 30 return result |
22 | 31 |
23 def check_lines(self, cmd): | 32 def root(self): |
24 result = self.check(cmd) | 33 if not self.is_root(): |
25 return re.split('[\r\n]+', result) | 34 subprocess.call(self.__invocation + ['root'], stdout=sys.stderr) |
26 | 35 self.__is_root = None |
27 def get_device_model(self): | 36 return self.is_root() |
28 result = self.check('getprop | grep ro.product.model') | |
29 result = re.match(r'\[ro.product.model\]:\s*\[(.*)\]', result) | |
30 return result.group(1) if result else 'unknown_product' | |
31 | 37 |
32 def is_root(self): | 38 def is_root(self): |
33 return self.check('whoami') == 'root' | 39 if self.__is_root is None: |
34 | 40 self.__is_root = ('root' == self.check('whoami').strip()) |
35 def attempt_root(self): | 41 return self.__is_root |
36 if self.is_root(): | |
37 return True | |
38 subprocess.call(self.__invocation + ['root'], stdout=sys.stderr) | |
39 return self.is_root() | |
40 | 42 |
41 def remount(self): | 43 def remount(self): |
42 subprocess.call(self.__invocation + ['remount'], stdout=sys.stderr) | 44 subprocess.call(self.__invocation + ['remount'], stdout=sys.stderr) |
| 45 |
| 46 def __echo_cmd(self, cmd): |
| 47 escaped = [re.sub(r'([^a-zA-Z0-9])', r'\\\1', x) |
| 48 for x in cmd.strip().splitlines()] |
| 49 subprocess.call(self.__invocation + \ |
| 50 ['shell', 'echo', '$(whoami)@$(getprop ro.serialno)$', |
| 51 " '\n>' ".join(escaped)], |
| 52 stdout=self.__echofile) |
OLD | NEW |