def kernel_version(): client = AdbClient(host="127.0.0.1", port=5037) device = client.device(options.device) result = device.shell("uname -r") #result = result.encode('ascii','ignore') logging.info(" kernel_version() : result is %s", result) result = result.split(".") ver = result[0] + '.' + result[1] ver = float(ver) offset_selinux = [] # case kernel version is <= 3.10 if ver <= 3.10: offset_to_comm = 0x288 offset_to_parent = 0xe0 offset_selinux.append(0xC0A77548) offset_selinux.append(0xC0A7754C) offset_selinux.append(0xC0A77550) ps_cmd = "ps" # case kernel version is > 3.10 et <=3.18 elif ver > 3.10 and ver <= 3.18: offset_to_comm = 0x444 offset_to_parent = 0xe0 offset_selinux.append(0xC0C4F288) offset_selinux.append(0xC0C4F28C) offset_selinux.append(0XC0C4F280) ps_cmd = "ps -A" else: logging.info("Sorry. Android kernel version %s not supported yet", ver) raise NotImplementedError( "Sorry. Android kernel version %s not supported yet", ver) return ver, offset_to_comm, offset_to_parent, offset_selinux, ps_cmd
def main(): try: from adb.client import Client as AdbClient import sys if len(sys.argv) < 3: print( "Error: Syntax: Python logger.py filename [cache clear (Y/N)]") apps = [ "com.android.chrome", "com.yandex.browser", "com.microsoft.emmx", "org.mozilla.firefox" ] client = AdbClient(host="127.0.0.1", port=5037) devices = client.devices() isCacheClear = sys.argv[2] for device in devices: if isCacheClear == 'Y': for app in apps: clearAppFromCache(app, device) clearLog(device) saving_log = save_log(sys.argv[1]) time = 30 for i in apps: open_app(i, time) saving_log.wait() except Exception as e: print("Error in main!")
def __init__(self): client = AdbClient(host="127.0.0.1", port=5037) devices = client.devices() if len(devices) <= 0: raise ValueError("No device connected") self.device = client.device(str(devices[0].get_serial_no())) self.settings = Settings("config.cfg") self.adbscreen = ADBScreen(self.device)
def adb_connect(self): try: client = AdbClient(host="127.0.0.1", port=5037) self.adb_device = client.devices()[0] except Exception as e: self.adb_device = "" self.err = str(e) return self.adb_device
def __init__(self): # Default is "127.0.0.1" and 5037 client = AdbClient(host="127.0.0.1", port=5037) self.device = client.device("ZY2239Q9MP") self.GREEN = '\033[92m' self.BLUE = '\033[94m' self.YELLOW = '\033[93m' self.RED = '\033[91m' self.ENDC = '\033[0m'
def check_process_is_running(process): client = AdbClient(host="127.0.0.1", port=5037) device = client.device("emulator-5554") ps = device.shell("ps") if process in ps: logging.debug("[+] OK. %s is running" %(process)) else: logging.debug("[+] NOK. It seems like %s is not running..." %(process)) logging.debug("[+] Android_Emuroot stopped") exit(1)
def list_devices(host="127.0.0.1", port=5037): client = AdbClient(host=host, port=port) try: client.version() except RuntimeError: # Can't connect to the adb server, try to start the adb server by command line. Adb._start_adb_server() return client.devices()
def setConfig(cfg): global config_dict, movementCount, client, device config_dict = cfg print(config_dict) movementCount = random.choice( range(config_dict["movement"]["stepsMin"], config_dict["movement"]["stepsMax"], 1)) client = AdbClient(host=config_dict["device"]["host"], port=config_dict["device"]["port"]) device = client.device(config_dict["device"]["name"])
def check_process_is_running(process, pscmd, device): client = AdbClient(host="127.0.0.1", port=5037) device = client.device(device) ps = device.shell(pscmd) if process in ps: logging.info("[+] OK. %s is running" % (process)) else: logging.info("[+] NOK. It seems like %s is not running..." % (process)) logging.info("[+] Android_Emuroot stopped") exit(1)
def __init__(self): print("program was starting") # Default is "127.0.0.1" and 5037 try: client = AdbClient(host="127.0.0.1", port=5037) devices = client.devices() devices_packages = devices[0].shell("pm list packages") get_all_files_from_device(devices[0], devices_packages) except Exception as e: print(e)
def get_devices(): adb = subprocess.Popen( ['adb', '-P', str(config['adb_port']), 'start-server'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) client = AdbClient(host="127.0.0.1", port=config['adb_port']) print(client) devs = [] for d in client.devices(): devs.append(AndroidDevice(d)) return devs
def screenshot(deviceAddress='ce031713383080fa0c', destFolder='screenshot', imageName="ADBScreenshot.png"): client = AdbClient(host="127.0.0.1", port=5037) device = client.device(deviceAddress) result = device.screencap() try: with open(destFolder + "/" + imageName, "wb") as fp: fp.write(result) except FileNotFoundError: print("could not file file or folder")
def __init__(self, init=False): client = AdbClient(host="127.0.0.1", port=5037) devices = client.devices() if len(devices) <= 0: raise ValueError("No device connected") self.device = client.device(str(devices[0].get_serial_no())) self.settings = Settings("config.cfg", init=init) self.adbscreen = ADBScreen(self.device) self.ENDC = '\033[0m' self.WARNING = '\033[93m' self.BLUE = '\033[94m' self.RED = '\033[91m' pytesseract.pytesseract.tesseract_cmd = self.settings.tesseract_dir
def connect(self,args): ''' connect to remote tcp daemon''' print(args) ip,prt = args client = AdbClient(host=ip, port=prt) try: client.create_connection() except RuntimeError as e: print(e) return False return client
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: print(str(err)) print("⚡ Starting ADB server...") subprocess.run(["adb", "start-server"]) devices = client.devices() if len(devices) == 0: print("⚠️ no devices connected!") return devices
class AdbUtils: def __init__(self, ip="127.0.0.1", port=5037): subprocess.run(["adb", "devices"]) self.client = AdbClient(host=ip, port=port) self.devices = [] def get_client_version(self): return self.client.version() def list_all_devices(self): for device in self.client.devices(): self.devices.append(device.serial) return self.devices # Exemple "example.package" def is_installed_apk(self, device, apk_package): return device.is_installed(apk_package) def install_apk(self, device, apk_path): device.install(apk_path) # Exemple "example.package" def uninstall_apk(self, device, apk_package): device.install(apk_package) return self.is_installed_apk(device, apk_package) def get_device_name(self, device): model = device.shell("getprop ro.product.model") manufacturer = device.shell("getprop ro.product.manufacturer") full_name = manufacturer + " " + model return full_name.replace("\n", "").replace("\r", "") def _dump_logcat(connection): while True: data = connection.read(1024) if not data: break print(data.decode('utf-8')) connection.close() def get_device_logcat(self, device): return device.shell("logcat", handler=self._dump_logcat) def get_screen_shot(self, device): result = device.screencap() with open( datetime.datetime.now().replace(" ", "").replace( "-", "").replace(":", "").replace(".", "") + ".png", "wb") as fp: fp.write(result)
def __init__(self, ini_name,init = False): #Loading config.cfg cparser = configparser.ConfigParser() dirname = os.path.dirname(__file__) ini_file = Path(os.path.join(dirname, "..\conf\\"+ini_name)) if ini_file.is_file(): cparser.read(ini_file) else: raise ValueError("Config file name not valid") self.language = "DE" #loads the config information try: self.language = cparser.get("custom", "language") self.speed_multi = cparser.getfloat("custom", "speed_multi") self.selected_raid = cparser.get("custom", "selected_raid") self.round_robin_raids = eval(cparser.get("custom", "round_robin_raids"), {}, {}) self.round_robin = cparser.getboolean("custom", "round_robin") self.tesseract_dir = cparser.get("custom", "tesseract_directory") self.rounds = cparser.getint("custom", "rounds") self.rounds_per_raid = cparser.getint("custom", "rounds_per_raid") self.debug = cparser.getboolean("custom", "debug") self.autodetect_buttons = cparser.get("screen", "autodeteckt_buttons") self.taps_resultscreen = cparser.getint("custom", "taps_resultscreen") self.auto_remove_pkmn = cparser.getboolean("custom", "auto_remove_pkmn") except Exception as e: raise ValueError("Couldn´t read config file") try: with open(os.path.join(dirname, '../conf/languages.json')) as json_file: data = json.load(json_file) self.language_pack = data[self.language] except Exception: raise ValueError("Language not found. Check your config file and update the languages.json") client = AdbClient(host="127.0.0.1", port=5037) devices = client.devices() if len(devices) <= 0: raise ValueError("No device connected") adbscreen = ADBScreen(client.device(str(devices[0].get_serial_no()))) if not init: try: with open(os.path.join(dirname, '../conf/screens/'+str(adbscreen.get_model_name()+".json"))) as json_file: data = json.load(json_file) self.screen = data except Exception: raise ValueError("Screenconfig not found. Start the python script with the --init argument to create a config.") self.check_screen_values()
def adb_stager_process(load, devicename): ''' Adb connexion TODO specify the device id ''' logging.info("[+] Launch the stager process") client = AdbClient(host="127.0.0.1", port=5037) device = client.device(devicename) device.shell("echo " + load + " > /data/local/tmp/load.sh") device.shell("chmod +x /data/local/tmp/load.sh") device.shell("ln -s /system/bin/sh /data/local/tmp/STAGER") # Launch STAGER shell device.shell("/data/local/tmp/STAGER /data/local/tmp/load.sh")
def __init__(self, interval=0): super(Clicking, self).__init__() self.interval = interval self.client = AdbClient(host="127.0.0.1", port=5037) self.device = self.client.devices()[0] self.x, self.y = None, None
def get_device(client: AdbClient): """ Gets the Android Device section from the user :param client: adb client :return: adb device object """ devices = client.devices() done = False device = None # get device selection from the user while not done: if len(devices) == 0: print("No Android Devices Found!") exit(1) print("Select a device:") print("Choice\tSerial #") ndx = 0 for device in devices: print("%d\t\t%s" % (ndx, get_serial_number(device))) choice = input("\nEnter Choice: ") try: device = devices[int(choice)] done = True except Exception as e: print(e) print("Invalid choice, please try again") return device
def __init__(self, serial=None, host="127.0.0.1", port=5037): self._serial = serial self._client = AdbClient(host=host, port=port) try: self._client.version() except RuntimeError: # Can't connect to the adb server, try to start the adb server by command line. self._start_adb_server() if self._serial: self._device = self._client.device(serial) else: # The serial can be None only when there is only one device/emulator. devices = self._client.devices() if len(devices) == 0: raise RuntimeError("Can't find any android device/emulator") elif len(devices) > 1: raise RuntimeError( "more than one device/emulator, please specify the serial number" ) else: device = devices[0] self._serial = device.get_serial_no() self._device = device
def check_process_is_running(process, pscmd, devicename): client = AdbClient(host="127.0.0.1", port=5037) device = client.device(devicename) if device == None: logging.warning( "Device name %s invalid. Check \"adb devices\" to get valid ones", device) raise Exception( "Device name invalid. Check \"adb devices\" to get valid ones") ps = device.shell(pscmd) if process in ps: logging.warning("[+] OK. %s is running" % (process)) else: logging.warning("[+] NOK. It seems like %s is not running..." % (process)) logging.warning("[+] Android_Emuroot stopped") exit(1)
def client(request): logger.info("Connecting to adb server {}:{}...".format(adb_host, adb_port)) client = AdbClient(host=adb_host, port=adb_port) def try_to_connect_to_adb_server(): try: client.version() return True except Exception: return False wait_until_true(try_to_connect_to_adb_server, timeout=60, description="Try to connect to adb server {}:{}".format(adb_host, adb_port)) logger.info("Adb server version: {}".format(client.version())) return client
def get(self): from adb.client import Client as AdbClient client = AdbClient() devices = client.devices() ret = {"success": True, "devices": []} if not devices: self.write({"success": False}) return for device in devices: data = {} data["serial"] = device.serial data["status"] = device.get_state() if device.shell("getprop ro.arch").strip() == "x86": data["emulator"] = True else: data["emulator"] = False ret["devices"].append(data) self.write(ret)
def get(self): from uiautomator2.__main__ import _init_with_serial from uiautomator2.version import __apk_version__, __atx_agent_version__ print("start...") from adb.client import Client as AdbClient client = AdbClient() devices = client.devices() for d in devices: print(d.serial) if not devices: self.write({ "success": False, "serial": "", "deviceId": "", }) return for d in devices: serial = d.get_serial_no() if d.get_state() != 'device': print("Skip invalid device: %s %s", serial, d.get_state()) continue print("Init device %s", serial) # todo:初始化代码优化 try: device = _AndroidDevice(serial) except BaseException: _init_with_serial(serial=serial, apk_version=__apk_version__, agent_version=__atx_agent_version__, server=None, reinstall=False) device = _AndroidDevice(serial) # serial = device._d.wlan_ip + ":7912" id = str(uuid.uuid4()) cached_devices[id] = device socket_url = device._d._host + ":" + str(device._d._port) self.write({ "success": True, "serial": serial, "deviceId": id, "socket_url": socket_url }) return
class getInstalledApps: def __init__(self): self.client = AdbClient(host="127.0.0.1", port=5037) self.adb_device = self.client.devices()[0] self.applist = [] self.apppath = [] self.asset = Assets() def get_Applist(self): self.ltemp = self.adb_device.shell("pm list packages ") # if search_keword is none, print all lists out. temp = self.ltemp.split("\n") del temp[len(temp)-1] self.applist = [x.split(":")[1] for x in temp] #print (self.applist) return self.applist def get_Path(self, pkgid): path_temp = self.adb_device.shell("pm path " + pkgid) path = path_temp.split(":")[1].strip() return path def get_app(self, pkgid): path = self.get_Path(pkgid) tmp_path = os.path.join("./tmp/") + pkgid + '.apk' data = self.adb_device.pull(path, tmp_path) if self.asset.exist(pkgid) == False: self.asset.add(pkgid, "", 0, "") def get_SDKApps(self, pkgid): apkpath = str(self.get_Path(pkgid)) apkfinal_path = str("tmp/" + pkgid + ".apk") self.adb_device.pull(apkpath.strip("\n"), apkfinal_path) cprint('[+] Checking AWS_SDK', 'blue') s = os.popen('/usr/bin/grep -i "aws-android-sdk" {0}'.format(apkfinal_path)).read() if 'matches' in s: cprint ("[!] This Application use AWS_SDK", 'blue') pass else: cprint ("[!] NO AWS_SDK FOUND", 'blue') os.remove(apkfinal_path) def is_AWSSDK(self, pkgid): apkfinal_path = os.path.join("./tmp/") + pkgid + '.apk' if re.search(b'(?i)aws-android-sdk', open(apkfinal_path,"rb").read()): self.asset.exist_sdk(pkgid, True) return True else: self.asset.exist_sdk(pkgid, False) return False
def kernel_version(): client = AdbClient(host="127.0.0.1", port=5037) device = client.device(options.device) if device == None: logging.warning( "Device name %s invalid. Check \"adb devices\" to get valid ones", options.device) raise Exception( "Device name invalid. Check \"adb devices\" to get valid ones") result = device.shell("uname -r") #result = result.encode('ascii','ignore') logging.debug(" kernel_version() : %s", result) result = result.split(".") ver = result[0] + '.' + result[1] ver = float(ver) offset_selinux = [] # case kernel version is <= 3.10 if ver <= 3.10: offset_to_comm = 0x288 offset_to_parent = 0xe0 offset_selinux.append(0xC0A77548) offset_selinux.append(0xC0A7754C) offset_selinux.append(0xC0A77550) ps_cmd = "ps" # case kernel version is > 3.10 et <=3.18 elif ver > 3.10 and ver <= 3.18: offset_to_comm = 0x444 offset_to_parent = 0xe0 offset_selinux.append(0xC0C4F288) offset_selinux.append(0xC0C4F28C) offset_selinux.append(0XC0C4F280) ps_cmd = "ps -A" else: logging.warning("Sorry. Android kernel version %s not supported yet", str(ver)) raise NotImplementedError( "Sorry. Android kernel version not supported yet") return ver, offset_to_comm, offset_to_parent, offset_selinux, ps_cmd
def __init__(self, adb_ip, adb_port, config): """ Starts the connection with the adb server. """ try: self.__adb = AdbClient(host=adb_ip, port=adb_port) self.__adb.devices() except Exception: with colored(colors.RED): print "adb server isn't running, opening." subprocess.Popen([config.get("adb", "adb_location"), "start-server"]) self.__config = config
class PurpleScouter(object): """ Handles the main user loop. """ def __init__(self, adb_ip, adb_port, config): """ Starts the connection with the adb server. """ try: self.__adb = AdbClient(host=adb_ip, port=adb_port) self.__adb.devices() except Exception: with colored(colors.RED): print "adb server isn't running, opening." subprocess.Popen([config.get("adb", "adb_location"), "start-server"]) self.__config = config def start(self): """ Starts the infinite loop. """ print "Welcome to:" with colored(colors.PURPLE): print "Purple Scouter!" time.sleep(1) while True: devices = self.__adb.devices() if devices: with colored(colors.BLUE): print "\nFound {len} connected devices!".format(len=len(devices)) for device in devices: FilePuller(device, self.__config).move_all_scouting_files_from_phone() animate_loading()
def kernel_version(): client = AdbClient(host="127.0.0.1", port=5037) device = client.device("emulator-5554") result = device.shell("uname -r") result = result.encode('ascii','ignore') logging.debug(" kernel_version() : result is %s", result) result = result.split('.') ver = result[0]+'.'+result[1] ver = float(ver) # case kernel version is <= 3.10 if ver <= 3.10 : offset_to_comm = 0x288 offset_to_parent = 0xe0 # case kernel version is > 3.10 et <=3.18 elif ver > 3.10 and ver <= 3.18 : offset_to_comm = 0x444 offset_to_parent = 0xe0 else : logging.debug("Sorry. Android kernel version %s not supported yet", ver) raise NotImplementedError("Sorry. Android kernel version %s not supported yet", ver) return ver,offset_to_comm,offset_to_parent