def start_server(self): """ Start ADB server """ try: _adb_kill_server() _adb_start_server() client = AdbClient(host=self._host, port=self._port) if (self._serial or "") == "": devices = client.devices() if len(devices) == 1: self.device = devices[0] elif len(devices) > 1: raise DeviceNotProvidedException() else: raise DeviceNotFoundException() else: self.device = client.device(self._serial) self.state = ADBServerState.OPENED logger.debug("ADB server started successfully.") except Exception as ex: _adb_kill_server() logger.debug("ADB server has failed to start.") self.state = ADBServerState.CLOSED raise ex
def connect(): adb = Client(host="127.0.0.1", port=5037) devices = adb.devices() if len(devices) == 0: print("No device found!") quit(1) return devices[0]
def tryConnect(self) -> bool: if self.connected and self.getDeviceSerialNo() is not None: return True self._changeConnectedState(False) self.checkingConnectionChange(True) adb = AdbClient(host="127.0.0.1", port=5037) devices = adb.devices() if len(devices) == 0: logger.debug( "No device attached. Restarting adb-server and retrying...") check_call(["adb", "kill-server"], stdout=DEVNULL, stderr=STDOUT) check_call(["adb", "start-server"], stdout=DEVNULL, stderr=STDOUT) else: self._client = adb try: self.my_device = devices[0] self._changeConnectedState(True) logger.info(f"Connected to device {self._host}:{self._port}") except RuntimeError: self._changeConnectedState(True) logger.info("Unable to connect to device") self.checkingConnectionChange(False) return self.connected
def connect_device(): adb = Client(host='127.0.0.1',port=5037) devices = adb.devices() if len(devices) == 0: print("No Devices Attached") quit() return devices[0]
def connect(deviceid): try: cnx = initmysql() cursor = mysqlCursor(cnx) query = execQuery( cursor, "SELECT port,name FROM lords.devices where id=" + str(deviceid)) field_name = [field[0] for field in query.description] result_set = query.fetchone() if result_set != None: row = dict(zip(field_name, result_set)) portNo = int(row['port']) emulatorname = row['name'] else: portNo = 5037 print("name ", emulatorname) adb = Client(host='127.0.0.1', port=portNo) devices = adb.devices() if len(devices) == 0: print('no device attached') quit() device = adb.device(emulatorname) return device except (): quit()
def check_device_exist(udid): client = AdbClient(host="127.0.0.1", port=5037) devices = client.devices() for device in devices: if device.get_serial_no() == udid: return udid return None
class Adb: def __init__(self, host='127.0.0.1', port=5037): self.client = PPADBClient(host, port) def connect_to_device(self, host='127.0.0.1', port=5555): adb_path = resource_path(FilePaths.ADB_EXE_PATH.value) cmd = build_command(adb_path, 'connect', "{}:{}".format(host, port)) ret = subprocess.check_output(cmd, shell=True, stderr=subprocess.PIPE, encoding="utf-8", timeout=2) return self.get_device(host, port) def get_client_devices(self): return self.client.devices() def get_device(self, host='127.0.0.1', port=5555): device = self.client.device('{}:{}'.format(host, port)) try: if device is None: self.connect_to_device(host, port) device = self.client.device('{}:{}'.format(host, port)) except Exception as e: traceback.print_exc() return None return device
def connect(self): # connect to android device self.adb = Client(host=self.host, port=self.port) try: self.device = self.adb.devices()[0] except: print("Cannot connect to phone!")
class adb(): def __init__(self, path: str) -> None: self.path = path ## self.adb_exe = '{}\\platform-tools\\adb.exe'.format(self.path) def connect_to_BS(self, ip: str, port: int) -> None: ''' 待測試 => 重開機直接執行 ''' self.client = AdbClient(host="127.0.0.1", port=5037) try: self.client.remote_connect(ip, port) except: subprocess.Popen('{} start-server'.format(self.adb_exe), stdout=subprocess.PIPE).stdout.read() print('Connect success!') def list_devices(self) -> None: devices = self.client.devices() print('List of devices attached:') for device in devices: print(' {}'.format(device.serial)) def tap(self, device, x: str, y: str) -> None: device.shell('input tap {} {}'.format(x, y)) def get_device(self, serial: str): return self.client.device(serial) def screencap(self, device): image_bytes = device.screencap() img = cv2.imdecode(np.frombuffer(image_bytes, dtype='uint8'), cv2.IMREAD_COLOR) return img
def __init__(self): self.log = MyLogger('ADB', LOG_LEVEL=logging.INFO) client = Client(host='127.0.0.1', port=5037) self.log.debug(client.version()) devices = client.devices() if len(devices) == 0: self.log.debug("no devices") quit() self.device = devices[0] self.log.debug(f'updating info for {self.device}') number = 5 touch_id = 0 lines = self.device.shell('getevent -p').split("\n") for line in lines: if "/dev/input" in line: number = line[-1] if "Touch" in line: touch_id = number self.touch = f"sendevent /dev/input/event{number}" if "max" in line and "ABS" in line and number == touch_id: values = line.split(', ') for value in values: if "max" in value: self.max = int(value[4:]) self.log.debug(f"found max: {self.max}")
async def main(argv): tasks = [] config = Object() config.width = 1 config.height = 1 client = AdbClient(host="127.0.0.1", port=5037) devices = client.devices() if len(devices) == 0: print("no device detected!") exit(1) return elif len(devices) == 1: device = devices[0] else: # print("multiple device detected, chose one") index = 0 for device in devices: print(f"{index}: {device.serial}") index = int( input("multiple device detected, chose one (index number): ")) device = devices[index] config.device = device if argv[1].endswith(".yaml") or argv[1].endswith(".yml"): config_text = open(argv[1]).read() argv = argv[1:] else: config_text = open("android_clicker.yaml").read() config_data = yaml.safe_load(config_text) print(config_data) if "screen" in config_data: screen = config_data["screen"] screen_cap = device.screencap() if len(screen_cap) != 0: img = cv2.imdecode(np.frombuffer(screen_cap, np.uint8), cv2.IMREAD_COLOR) sp = img.shape height = sp[0] width = sp[1] print(f'screen width: {width:d}, height: {height:d}') if "width" in screen: config.width = width / int(screen["width"]) if "height" in screen: config.height = height / int(screen["height"]) available_motions = argv[1:] if "motions" in config_data: motions = config_data["motions"] if len(available_motions) != 0: motions = filter( lambda m: "name" in m and m["name"] in available_motions, motions) for motion in motions: task = asyncio.create_task(loop(motion, device, config)) tasks.append(task) for task in tasks: await task
def __init__(self): client = AdbClient(host="127.0.0.1", port=5037) devices = client.devices() if len(devices) == 0: raise Exception('There is no ADB devices') self.device = devices[0] self.app_name = 'com.firsttouchgames.smp'
def stager_clean(devicename): """ This function cleans the file system by removing the stager binaries created in adb_stager_process """ logging.info("[+] Clean the stager process") client = AdbClient(host="127.0.0.1", port=5037) device = client.device(devicename) device.shell("rm /data/local/tmp/load.sh /data/local/tmp/STAGER")
def initDevice(): os.system('taskkill /f /im %s' % 'cmd.exe') os.system('taskkill /f /im %s' % 'adb.exe') os.system("adb kill-server") os.system("adb start-server") global client client = AdbClient(host="127.0.0.1", port=5037) global device device = client.devices()[0]
def connectServer(self): """ Method to establish a connection between smartphone and computer. """ client = AdbClient(host=self.host, port=self.port) if client : print("Client version :", client.version()) return client else: print("Problem to connect adb Server, please verify your port or host")
def main(): with open('/opt/tachiyomimangaexporter/secrets.json') as json_file2: secrets = json.load(json_file2) client = AdbClient(host="127.0.0.1", port=5037) # print(client.version()) ip = conectar(secrets) client.remote_connect(ip, 5555) device = client.device(ip + ":5555") device.pull("/storage/emulated/0/Tachiyomi", "/media/cristian/Datos/Comics/Tachiyomi")
def download(self, id): client = AdbClient(host="127.0.0.1", port=5037) device = client.device(id) url = self.te_link.toPlainText() device.shell("input tap 65.2 411.1") sleep(3) device.shell("input tap 310.2 73") device.input_text(str(url)) device.shell("input keyevent 66") sleep(8) device.shell('input tap 603.7 153.2')
def connect(self, UserPort): client = AdbClient(host="127.0.0.1", port=5037) device = client.device("127.0.0.1:" + UserPort) if device is None: # print("找不到模擬器") self.isConnect = False sys.exit("找不到模擬器") else: # print("找到模擬器") self.device = device self.isConnect = True
def _connect(self, tries: int = 1) -> AdbClient: try: client = AdbClient(host=self.host, port=self.port) client.version() return client except RuntimeError as e: if isinstance(e.__context__, ConnectionRefusedError) and tries > 0: os.system('adb start-server') return self._connect(tries - 1) else: raise e
def get_device_udid(number: int): client = AdbClient(host="127.0.0.1", port=5037) devices = client.devices() if len(devices) > number: return devices[number].get_serial_no() else: new_number = number - (number // len(devices)) * len(devices) logger.log_warn( f'You choose device number {number + 1} but there are only {len(devices)} connected. ' f'Will use device number {new_number + 1} instead', jump_line=True) return devices[new_number].get_serial_no()
def init(): os.system('adb devices -l') adb = Client(host='127.0.0.1', port=5037) devices = adb.devices() if len(devices) == 0: print('no devices found') quit() device = devices[0] return device
def _connect(self, try_adb: bool = True) -> AdbClient: try: client = AdbClient() client.create_connection() return client except (RuntimeError, ConnectionRefusedError): if try_adb: self._run_adb() return self._connect(try_adb=False) else: print("Failed. ADB is not running.") return None
def check_device(): global current_device adb = Client(host='127.0.0.1', port=5037) devices = adb.devices() if len(devices) == 0: print('no device attached') print('exit') quit() else: current_device = devices[0] print(f"device found {current_device.serial} ") create_folder(folder) start()
def adb_connect(self): try: client = AdbClient(host="127.0.0.1", port=5037) self.adb_device = client.device(self.serial) #print(self.adb_device, self.adb_device == None) if self.adb_device == None: self.adb_device = "no serial" self.err = str("Check Your Device!") else: return self.adb_device except Exception as e: self.adb_device = "" self.err = str(e) return self.adb_device
def get_devices(): for attempt in range(2): try: client = AdbClient(host="127.0.0.1", port=5037) client.version() # a random call to check if adb server is up except Exception as err: eprint(str(err)) eprint("⚡ Starting ADB server...") subprocess.run(["adb", "start-server"]) devices = client.devices() if len(devices) == 0: eprint("⚠️ no devices connected!") return devices
def __init__(self): # Default is "127.0.0.1" and 5037 self.client = AdbClient(host="127.0.0.1", port=5037) self.device = self.client.device("emulator-5554") # if not connect to adb server # type `./adb start-server` after `./emulator -avd Pixel_XL_API_23` self.package_name = None
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: # pure-python-adb try: self._adb_client = AdbClient() self._adb_client.remote_connect(self.host, self.port) print(self._adb_client.devices()) self._adb_device = self._adb_client.device( f"{self.host}:{self.port}") self._available = bool(self._adb_device) except: traceback.print_exc() self._available = False finally: return self._available finally: self._adb_lock.release()
class SSMAndroidDevices: """ AndroidDevices class this is collection of devices found by adb executable """ def __init__(self, host: object, port: int) -> object: self.client = AdbClient(host, port) self.devices = self.client.devices() if self.devices.__len__() <= 0: logging.critical("There are no devices connected") self.num_of_device = 0 exit() else: logging.info("There are " + self.devices.__len__().__str__() + " devices connected") self.num_of_device = self.devices.__len__() return def print_devices(self): for device in self.devices: print("Serial: " + device.serial) # print("State: " + device.serial.get_state) print(device.get_serial_no()) print(device.get_device_path()) print(device.get_state()) # below require package name # print(device.get_meminfo()) print(device.get_top_activities()) print(" ") for activity in device.get_top_activities(): print(activity.activity) print(activity.package) print(activity.pid) print(" ") return
def tryConnect(self) -> bool: # Default is "127.0.0.1" and 5037, but nox is 62001 if self.connected and self.getDeviceSerialNo() is not None: return True self._changeConnectedState(False) self.checkingConnectionChange(True) ports = [5037, 62001] ok = False os.system("adb disconnect") dev = 'device' for p in ports: os.system("adb connect {}:{}".format(self._host, p)) dev = self.getDeviceSerialNo() if dev is not None: if 'offline' not in dev: self._port = 5037 ok = True break os.system("adb disconnect") if ok: self._client = AdbClient(host=self._host, port=self._port) self.my_device = self._client.device(dev) self._changeConnectedState(True) else: self._changeConnectedState(False) self.checkingConnectionChange(False) return self.connected
def conecta_android(): client = AdbClient(host="127.0.0.1", port=5037) print(client.version()) os.system('adb kill-server') sleep(1) os.system('adb usb') sleep(1) os.system('adb devices') sleep(1) os.system('adb tcpip 5556') sleep(1) os.system('adb connect "192.168.0.11:5556"') sleep(1) device = client.device("192.168.0.11:5556") device.shell("echo hello world !") return device