def connect(self, always_log_errors=True): """Connect to an Amazon Fire TV device. Will attempt to establish ADB connection to the given host. Failure sets state to UNKNOWN and disables sending actions. :returns: True if successful, False otherwise """ self._adb_lock.acquire(**LOCK_KWARGS) try: if not self.adb_server_ip: # python-adb try: if self.adbkey: signer = Signer(self.adbkey) # Connect to the device self._adb = adb_commands.AdbCommands().ConnectDevice( serial=self.host, rsa_keys=[signer], default_timeout_ms=9000) else: self._adb = adb_commands.AdbCommands().ConnectDevice( serial=self.host, default_timeout_ms=9000) # ADB connection successfully established self._available = True except socket_error as serr: if self._available or always_log_errors: if serr.strerror is None: serr.strerror = "Timed out trying to connect to ADB device." logging.warning( "Couldn't connect to host: %s, error: %s", self.host, serr.strerror) # ADB connection attempt failed self._adb = None self._available = False finally: return self._available else: # pure-python-adb try: self._adb_client = AdbClient(host=self.adb_server_ip, port=self.adb_server_port) self._adb_device = self._adb_client.device(self.host) self._available = bool(self._adb_device) except: self._available = False finally: return self._available finally: self._adb_lock.release()
def connect(self): # Maybe one day they will merge: # https://github.com/google/python-adb/pull/142 priv_key_path = os.path.expanduser("~/.android/adbkey") with open(priv_key_path, "rb") as handle: priv_key = handle.read() pub_key_path = priv_key_path + ".pub" with open(pub_key_path, "rb") as handle: pub_key = handle.read() signer = sign_pythonrsa.PythonRSASigner(pub_key, priv_key) self.device = adb_commands.AdbCommands() while True: try: self.device.ConnectDevice(rsa_keys=[signer]) except (USBErrorBusy, USBErrorAccess): print( error( "Device is busy, maybe run `adb kill-server` and try again." )) sys.exit(-1) except DeviceAuthError: print( error( "You need to authorize this computer on the Android device. Retrying in 5 seconds..." )) time.sleep(5) except Exception as e: print(error(repr(e))) sys.exit(-1) else: break
def __init__(self): signer = sign_m2crypto.M2CryptoSigner( op.expanduser("~/.android/adbkey")) self.device = adb_commands.AdbCommands() self.device.ConnectDevice(rsa_keys=[signer]) # ADBInterface.current_interface = self self.kill_media()
def testSmallResponseShell(self): command = b'keepin it real' response = 'word.' usb = self._ExpectCommand(b'shell', command, response) dev = adb_commands.AdbCommands() dev.ConnectDevice(handle=usb, banner=BANNER) self.assertEqual(response, dev.Shell(command))
def cli(ctx, duration, adbkey, port_path, serial): """ 微信读书自动读书 """ import random import re import time from datetime import datetime from adb import adb_commands, sign_m2crypto logger = ctx.obj.logger # KitKat+ devices require authentication signer = sign_m2crypto.M2CryptoSigner(adbkey) device = adb_commands.AdbCommands() device.ConnectDevice( port_path=port_path.encode() if port_path else None, serial=serial.encode() if serial else None, rsa_keys=[signer], default_timeout_ms=3000, ) logger.info( "设备信息: %s-%s", device.Shell("getprop ro.product.brand").strip(), device.Shell("getprop ro.product.model").strip(), ) pattern = re.compile(r"(\d+)x(\d+)") width, height = pattern.search(device.Shell("wm size")).groups() width = int(width) height = int(height) logger.info("屏幕尺寸: %dx%d", width, height) # 点亮屏幕 device.Shell("input keyevent 224") # 关闭自动亮度 device.Shell("settings put system screen_brightness_mode 0") # 将亮度调到最低 device.Shell("settings put system screen_brightness 0") now = time.time() end_time = now + duration end_datetime = datetime.fromtimestamp(end_time) logger.info("截止时间: %s", end_datetime.isoformat()) pages = 0 while now < end_time: point = { "X": width * random.uniform(0.93, 0.96), "Y": width * random.uniform(0.93, 0.96), } device.Shell("input tap {X} {Y}".format(**point)) pages += 1 logger.info("进行翻页, 第 %d 页,坐标 %s", pages, point) time.sleep(random.randint(30, 40)) now = time.time() logger.info("到达截止时间:%s, 停止运行", end_datetime.isoformat())
def _get_adb_commands_object(self): # KitKat+ devices require authentication signer = sign_m2crypto.M2CryptoSigner(op.expanduser('~/.android/adbkey')) # Connect to the device device = adb_commands.AdbCommands() device.ConnectDevice(rsa_keys=[signer]) return device
def testUninstall(self): package_name = "com.test.package" response = 'Success' usb = self._ExpectCommand(b'shell', ('pm uninstall "%s"' % package_name).encode('utf8'), response) dev = adb_commands.AdbCommands() dev.ConnectDevice(handle=usb, banner=BANNER) self.assertEqual(response, dev.Uninstall(package_name))
def testConnectSerialString(self): dev = adb_commands.AdbCommands() with mock.patch.object(common.UsbHandle, 'FindAndOpen', return_value=None): with mock.patch.object(adb_commands.AdbCommands, '_Connect', return_value=None): dev.ConnectDevice(serial='/dev/invalidHandle')
def adb_test(): print("Connecting to ADB.") # KitKat+ devices require authentication signer = sign_m2crypto.M2CryptoSigner(op.expanduser('~/.android/adbkey')) # Connect to the device device = adb_commands.AdbCommands() device.ConnectDevice(rsa_keys=[signer]) # Now we can use Shell, Pull, Push, etc! for i in range(10): print(device.Shell('echo %d' % i))
def connect(self): """ Connect to an Amazon Fire TV device. Will attempt to establish ADB connection to the given host. Failure sets state to DISCONNECTED and disables sending actions. """ try: if self.adbkey: signer = Signer(self.adbkey) # Connect to the device self._adb = adb_commands.AdbCommands().ConnectDevice( serial=self.host, rsa_keys=[signer]) else: self._adb = adb_commands.AdbCommands().ConnectDevice( serial=self.host) except socket_error as serr: logging.warning("Couldn't connect to host: %s, error: %s", self.host, serr.strerror)
def ListDevices(self): out = [] try: device_list = adb_commands.AdbCommands().Devices() for one in device_list: out.append(one.serial_number) else: return (True, out) except Exception as e: return (False, e)
def startADB(): from adb import adb_commands from adb import sign_cryptography signer = sign_cryptography.CryptographySigner( op.expanduser('~/.android/adbkey')) device = adb_commands.AdbCommands() device.ConnectDevice(rsa_keys=[signer]) return device
def __init__(self): self.dev = finddev(idVendor=0x18d1, idProduct=0x4ee2) self.dev.reset() self.BANNER = "mobile" # KitKat+ devices require authentication #signer = sign_m2crypto.M2CryptoSigner( # op.expanduser('~/.android/adbkey')) # Connect to the device self.device = adb_commands.AdbCommands() self.device.ConnectDevice(banner=self.BANNER)
def Init(self): try: self.device = adb_commands.AdbCommands() self.signer = None if os.path.exists(self.adbkey): self.signer = sign_m2crypto.M2CryptoSigner( op.expanduser(self.adbkey)) # op.expanduser(r'C:\Users\liuqingping\.android\adbkey')) except Exception as e: self.device = None pass
def testStreamingResponseShellWithMultiBytesSequences(self): command = b'keepin it real big' # expect multiple bulks responses = [b'\xe2', b'\x81\x82'] # utf-8 encoded split Hiragana A (U+3042) usb = self._ExpectCommand(b'shell', command, *responses) dev = adb_commands.AdbCommands() dev.ConnectDevice(handle=usb, banner=BANNER) dev.StreamingShell(command)
def testBigResponseShell(self): command = b'keepin it real big' # The data doesn't have to be big, the point is that it just concatenates # the data from different WRTEs together. responses = [b'other stuff, ', b'and some words.'] usb = self._ExpectCommand(b'shell', command, *responses) dev = adb_commands.AdbCommands() dev.ConnectDevice(handle=usb, banner=BANNER) self.assertEqual(b''.join(responses).decode('utf8'), dev.Shell(command))
def testPull(self): filedata = b"g'ddayta, govnah" recv = self._MakeWriteSyncPacket(b'RECV', b'/data') data = [ self._MakeWriteSyncPacket(b'DATA', filedata), self._MakeWriteSyncPacket(b'DONE'), ] usb = self._ExpectSyncCommand([recv], [b''.join(data)]) dev = adb_commands.AdbCommands() dev.ConnectDevice(handle=usb, banner=BANNER) self.assertEqual(filedata, dev.Pull('/data'))
def connect_to_device(verbose = True): if verbose == True: print("CONNECTING TO ADB....") print("If unable to connect, execute adb kill-server") try: signer = sign_m2crypto.M2CryptoSigner(op.expanduser('~/.android/adbkey')) device = adb_commands.AdbCommands() device.ConnectDevice(rsa_keys=[signer]) return device except: print("execute adb kill-server first") return None
def testNonStreamingLogcatWithMultiBytesSequences(self): command = b'logcat test\xe3\x81\x82' # expect multiple bulks responses = [b'\xe3', b'\x81\x82'] # utf-8 encoded split Hiragana A (U+3042) usb = self._ExpectCommand(b'shell', command, *responses) dev = adb_commands.AdbCommands() dev.ConnectDevice(handle=usb, banner=BANNER) res = dev.NonStreamingLogcat(u'test\u3042') self.assertEqual(u'\u3042', res)
def connect(self): """ Connect to an Amazon Fire TV device. Will attempt to establish ADB connection to the given host. Failure sets state to UNKNOWN and disables sending actions. """ kwargs = {'serial': self.host} if self.adbkey: kwargs['rsa_keys'] = [Signer(self.adbkey)] try: self._adb = adb_commands.AdbCommands().ConnectDevice(**kwargs) except socket_error as serr: logging.warning("Couldn't connect to host: %s, error: %s", self.host, serr.strerror)
def testPush(self): filedata = b'alo there, govnah' mtime = 100 send = [ self._MakeWriteSyncPacket(b'SEND', b'/data,33272'), self._MakeWriteSyncPacket(b'DATA', filedata), self._MakeWriteSyncPacket(b'DONE', size=mtime), ] data = b'OKAY\0\0\0\0' usb = self._ExpectSyncCommand([b''.join(send)], [data]) dev = adb_commands.AdbCommands() dev.ConnectDevice(handle=usb, banner=BANNER) dev.Push(BytesIO(filedata), '/data', mtime=mtime)
def testStreamingResponseShell(self): command = b'keepin it real big' # expect multiple bulks responses = ['other stuff, ', 'and some words.'] usb = self._ExpectCommand(b'shell', command, *responses) dev = adb_commands.AdbCommands() dev.ConnectDevice(handle=usb, banner=BANNER) response_count = 0 for (expected, actual) in zip(responses, dev.StreamingShell(command)): self.assertEqual(expected, actual) response_count = response_count + 1 self.assertEqual(len(responses), response_count)
def push_tflite(name): print("CONNECTING TO ADB....") signer = sign_m2crypto.M2CryptoSigner(op.expanduser('~/.android/adbkey')) device = adb_commands.AdbCommands() device.ConnectDevice(rsa_keys=[signer]) # Check if tflite file is present on disk, then push it into the device file_name = 'model_' + name + '.tflite' destination_dir = '/data/local/tmp/' + file_name if op.exists(file_name): print(device.Push(file_name, destination_dir)) print("FILE PUSHED") return True else: print("FILE NOT PRESENT") return False
def execute_tflite(name): print('EXECUTING') # Should connect again, unnecceary overhead signer = sign_m2crypto.M2CryptoSigner(op.expanduser('~/.android/adbkey')) device = adb_commands.AdbCommands() device.ConnectDevice(rsa_keys=[signer]) # More checks are required, but for now, its okay! benchmark_file = "/data/local/tmp/label_image" image_file = "/data/local/tmp/grace_hopper.bmp" label_file = "/data/local/tmp/labels.txt" model_file = '/data/local/tmp/model_' + name + '.tflite' exec_command = "." + benchmark_file + " -c 100 -v 1 -i " + \ image_file + " -l " + label_file + " -m " + \ model_file + " -t 1" print(exec_command) print(device.Shell(exec_command, timeout_ms=100000)) return
def connect(self): """ Connect to an Amazon Fire TV device. Will attempt to establish ADB connection to the given host. Failure sets state to DISCONNECTED and disables sending actions. """ try: # KitKat+ devices require authentication signer = sign_m2crypto.M2CryptoSigner( op.expanduser('~/.android/adbkey')) # Connect to the device device = adb_commands.AdbCommands() self._adb = device.ConnectDevice(serial=self.host, rsa_keys=[signer]) except socket_error as serr: print 'Exception raised' if serr.errno != errno.ECONNREFUSED: raise serr
def get_device_info(args, signer, addr): dirname = get_dirname_for_addr(addr) try: device = adb_commands.AdbCommands() device.ConnectDevice(port_path=None, serial=addr, default_timeout_ms=args.timeout, rsa_keys=[signer]) version = device.Shell('cat /proc/version', timeout_ms=args.timeout) if args.screenshot or args.getprop: outpath = '{}/{}'.format(args.output, dirname) os.mkdir(outpath) if args.screenshot: try: device.Shell('screencap -p /data/local/tmp/screenshot.png', timeout_ms=args.timeout) device.Pull('/data/local/tmp/screenshot.png', dest_file='{}/screenshot.png'.format(outpath), timeout_ms=120000) device.Shell('rm -rf /data/local/tmp/screenshot.png', timeout_ms=args.timeout) except (KeyboardInterrupt, SystemExit): raise except Exception as e: print(e) if args.getprop: getprop = device.Shell('getprop', timeout_ms=args.timeout) except (KeyboardInterrupt, SystemExit): raise except Exception: return None if args.getprop: with open('{}/getprop.txt'.format(outpath), 'w+') as f: f.write(getprop) return {'addr': addr, 'dirname': dirname, 'version': version}
def testConnect(self): usb = common_stub.StubUsb(device=None, setting=None) self._ExpectConnection(usb) dev = adb_commands.AdbCommands() dev.ConnectDevice(handle=usb, banner=BANNER)
def connect(self, always_log_errors=True): """Connect to an Android TV / Fire TV device. Parameters ---------- always_log_errors : bool If True, errors will always be logged; otherwise, errors will only be logged on the first failed reconnect attempt Returns ------- bool Whether or not the connection was successfully established and the device is available """ self._adb_lock.acquire(**LOCK_KWARGS) # pylint: disable=unexpected-keyword-arg try: if not self.adb_server_ip: # python-adb try: if self.adbkey: # private key with open(self.adbkey) as f: priv = f.read() # public key try: with open(self.adbkey + '.pub') as f: pub = f.read() except FileNotFoundError: pub = '' signer = PythonRSASigner(pub, priv) # Connect to the device self._adb = adb_commands.AdbCommands().ConnectDevice( serial=self.host, rsa_keys=[signer], default_timeout_ms=9000) else: self._adb = adb_commands.AdbCommands().ConnectDevice( serial=self.host, default_timeout_ms=9000) # ADB connection successfully established self._available = True except socket_error as serr: if self._available or always_log_errors: if serr.strerror is None: serr.strerror = "Timed out trying to connect to ADB device." logging.warning( "Couldn't connect to host: %s, error: %s", self.host, serr.strerror) # ADB connection attempt failed self._adb = None self._available = False finally: return self._available else: # pure-python-adb try: self._adb_client = AdbClient(host=self.adb_server_ip, port=self.adb_server_port) self._adb_device = self._adb_client.device(self.host) self._available = bool(self._adb_device) except: # noqa pylint: disable=bare-except self._available = False finally: return self._available finally: self._adb_lock.release()
def testConnect(self): tcp = common_stub.StubTcp('10.0.0.123') self._ExpectConnection(tcp) dev = adb_commands.AdbCommands() dev.ConnectDevice(handle=tcp, banner=BANNER)
from adb import adb_commands, sign_m2crypto signer = sign_m2crypto.M2CryptoSigner('/home/sriteja/.android/adbkey') device = adb_commands.AdbCommands() device.ConnectDevice(rsa_keys=[signer]) # for i in range(10): # print(device.Shell('echo %d' % i))