def __init__(self, device=None): self.logger = logging.getLogger(self.__class__.__name__) if device is None: from .DeviceHelper import get_available_devices all_devices = get_available_devices() if len(all_devices) == 0: self.logger.warning("ERROR: No device connected.") sys.exit(-1) device = all_devices[0] if "emulator" in device: self.is_emulator = True else: self.is_emulator = False self.device = device self.grant_perm = False ## Grant all permissions while installing. Useful for Android 6.0+ # basic device information self.display_info = None self.sdk_version = None self.release_version = None self.ro_debuggable = None self.ro_secure = None self.connected = True # adapters self.adb = ADB(device=self) self.adapters = { self.adb: True, # self.telnet: False, }
def push_and_start_frida_server(adb: ADB): """ Push and start adb server on device Parameters ---------- adb Returns ------- """ frida_server = os.path.join(os.getcwd(), "resources", "frida-server", "frida-server") try: adb.execute(['root']) except Exception as e: adb.kill_server() logger.error("Error on adb {}".format(e)) logger.info("Push frida server") try: adb.push_file(frida_server, "/data/local/tmp") except Exception as e: pass logger.info("Add execution permission to frida-server") chmod_frida = ["chmod 755 /data/local/tmp/frida-server"] adb.shell(chmod_frida) logger.info("Start frida server") start_frida = ["cd /data/local/tmp && ./frida-server &"] adb.shell(start_frida, is_async=True) time.sleep(4)
def __init__(self, adb_path): self.adb_path = adb_path self.adb = None self.devices = [] self.adb = ADB(adb_path) if NEED_RESTART_ADB: self.restart_adb()
def __init__(self, p2adb, logtype="logcat", pollrate=0.5): self.adb = ADB(p2adb) self.logtype = logtype self.pollrate = pollrate self._event_list = [] self._isRunning = False self.logcat_monitor_tread = None self.cacheMutex = Lock() self.cacheLineNum = 0
def test_install(self): adb = ADB() adb.set_adb_path() _, ds = adb.get_devices() device_id = ds[0] adb.set_target_device(device_id) adb.enable_debug() output = adb.install(reinstall=True, pkgapp='ctssetup.apk') print("output: " + str(output))
def install_app_and_install_frida(app_path): app = APK(app_path) package_name = app.get_package() logger.info("Start ADB") adb = ADB() logger.info("Install APP") adb.install_app(app_path) logger.info("Frida Initialize") push_and_start_frida_server(adb) return package_name
def ping(): trytime = 30 success = 0 adb = ADB() cmd = "ping -c 4 {0} | grep -q 'ttl=' && echo '{0} ok' || echo '{0} failed'".format( '61.135.169.125') print(cmd) for i in range(trytime): result = adb.shell(cmd) if 'ok' in result[1]: success += 1 print(result) return success
def catchSysLog(): powerUsbController.OPEN_MAIN_POWER() powerUsbController.OPEN_KL15() powerUsbController.USB_ON() time.sleep(20) logging.info("swith to Diagnostics Mode") openADB(TBOX_IP, TBOX_DIAG_KEY) time.sleep(20) adb = ADB() logPath = os.path.join( LOG_DIR, time.strftime('sysLog-%m-%d-%H_%M_%S', time.localtime(time.time()))) adb.pull('/logfs', logPath, TBOX_ADB_SN)
def run(self): adb1 = ADB() sender = Sender() while True: if "{}" not in str(adb1.get_devices()): pass else: try: sender.send("android-remove", json.loads("{}")) print "Android remove event was sent" except Exception as e: print e return time.sleep(self.interval)
def __init__(self, adb): self._adb = adb self._device_id = adb.device_name self._is_local_device = ADB.is_local_device(self._device_id) self._client = None self._server_pid = 0 self._timeout = 40
def test_get_pid_on_device(self): adb = ADB() adb.enable_debug() adb.set_adb_path() adb.set_target_device() pid = utils.get_pid_on_device(adb, 'com.android.commands.monkey') utils.kill_proc_on_device(adb, pid) print(pid)
def main(): # creates the ADB object adb = ADB() # IMPORTANT: You should supply the absolute path to ADB binary if adb.set_adb_path('/home/bigzhang/Android/Sdk/platform-tools/adb') is True: print "Version: %s" % adb.get_version() else: print "Check ADB binary path" devices_all = get_devices(adb) #print devices_all functions = [] functions.append(push_iozone) functions.append(push_iozone) for devs in devices_all: do_work(adb, functions, devs)
def push_api_monitor_xposed(adb: ADB, package_name: str, dir_hook_file: str): """ push file on emulator needed to api monitor Parameters ---------- adb package_name dir_hook_file Returns ------- """ logger.info("Push files needed to API Monitor") adb.push_file(os.path.join(dir_hook_file, "hooks.json"), "/data/local/tmp") adb.shell(['echo', '"{0}"'.format(package_name), '>', '/data/local/tmp/package.name'])
def list_local_devices(): '''获取本地设备列表 ''' from adb import ADB result = [] for device_id in ADB.list_device(): result.append(AndroidDevice(device_id)) return result
def _get_sys_meminfo(self) -> dict: sys_meminfo = {} raw_sys_meminfo = ADB.get_meminfo(self.dev_id) for line in raw_sys_meminfo: if "Free RAM:" in line: sys_meminfo["Free RAM"] = line.split()[2] elif "Used RAM:" in line: sys_meminfo["Used RAM"] = line.split()[2] return sys_meminfo
def test_get_devices(self): adb = ADB() adb.set_adb_path() adb.start_server() err, devices = adb.get_devices() print(str(err)) if len(devices) > 0: print(str(devices))
def install_app_and_install_frida(app_path): """ Install app and Frida script Parameters ---------- app_path Returns ------- """ app = APK(app_path) package_name = app.get_package() logger.info("Start ADB") adb = ADB() logger.info("Install APP") adb.install_app(app_path) logger.info("Frida Initialize") push_and_start_frida_server(adb) return package_name
def amdh(): arguments = args_parse() if arguments.adb_path: adb_path = arguments.adb_path dump_apks = False apks_dump_folder = "" if arguments.apks_dump_folder: dump_apks = True apks_dump_folder = arguments.apks_dump_folder adb_instance = ADB(adb_path) device_id = device_choice(adb_instance) adb_instance = ADB(adb_path, device_id) settings_check = None packages = [] if arguments.app_type: packages = adb_instance.list_installed_packages(arguments.app_type) report_apps = {} for package in packages: dumpsys_out = adb_instance.dumpsys(["package", package]) perm_list = adb_instance.get_req_perms_dumpsys_package(dumpsys_out) app = App(adb_instance, package, dump_apks, apks_dump_folder, perm_list) perms, dangerous_perms = app.check_apps() print("") if dangerous_perms.items(): print_warning_header("Package " + package + " have some dangerous permissions: ") for perm, desc in dangerous_perms.items(): print_warning("\t " + perm + " : ") print_warning("\t\t" + desc) report_apps[package] = { "permissions": perms, "dangerous_perms": dangerous_perms } print("") print( "************************************************************************" ) else: print_info("Package " + package + " have no dangerous permissions") print("") print( "************************************************************************" ) if arguments.H: settings_check = Settings(settings_file, adb_instance, True) else: settings_check = Settings(settings_file, adb_instance) settings_check.check()
def loopInit(): powerUsbController.OPEN_MAIN_POWER() powerUsbController.OPEN_KL15() powerUsbController.USB_ON() time.sleep(20) logging.info("swith to Diagnostics Mode") openADB(TBOX_IP, TBOX_DIAG_KEY) time.sleep(20) powerUsbController.SHUTDOWN_KL15() time.sleep(2) adb = ADB() #adb.stopAdb() #adb.startAdb() logging.info( "adb shell zte_topsw_mcutest 29 02000600060002000200020004000000") ret = adb.shell("zte_topsw_mcutest 29 02000600060002000200020004000000", TBOX_ADB_SN) if (0 != ret[0]): raise Exception("send adb shell zte_topsw_mcutest failed! " + ret[2]) logging.info(ret[1]) time.sleep(1)
def adb_init(): adb = ADB() adb.set_adb_path(parameter.variables.executable_path) adb.DEFAULT_TCP_PORT = parameter.variables.default_tcp_port adb.DEFAULT_TCP_HOST = parameter.variables.wireless_address if not adb.get_version(): raise ConnectionError("Unable to communicate with adb daemon!") return adb
def __init__(self, device_id): self._device_id = device_id from adb import ADB self._is_local_device = ADB.is_local_device(device_id) self._adb = None self._client = None self._use_socket = True self._module = '' self._system_version = '' self._sdk_version = 0 self._cpu_type = None self._imei = '' self._width = 0 self._height = 0
def install_app_and_install_frida(app_path, is_google_emulator: bool = False): """ Install app and Frida script Parameters ---------- app_path Returns ------- """ app = APK(app_path) package_name = app.get_package() logger.info("[*] Start ADB") adb = ADB() logger.info(f"[*] Install App {package_name}") adb.install_app(app_path) logger.info("[*] Frida Initialization") if not is_google_emulator: push_and_start_frida_server(adb) else: push_and_start_frida_server_google_emulator(adb) return package_name
def install_package(self, pkg_path, overwrite=False): '''安装应用 ''' from util import get_file_md5 if not os.path.exists(pkg_path): raise RuntimeError('APK: %r not exist' % pkg_path) pkg_size = os.path.getsize(pkg_path) pkg_md5 = get_file_md5(pkg_path) pkg_name = ADB._get_package_name(pkg_path) if self.is_package_installed(pkg_name, pkg_size, pkg_md5): logger.info('APP %s [%d]%s is installed' % (pkg_name, pkg_size, pkg_md5)) return True self.adb.install_apk(pkg_path, overwrite) return True
def create_adb_and_start_frida(package_name): """ Parameters ---------- package_name Returns ------- """ logger.info(f"App Already Installed, start to monitoring ${package_name}") adb = ADB() logger.info("Frida Initialize") push_and_start_frida_server(adb) return package_name
def create_adb_and_start_frida(package_name, is_google_emulator: bool = False): """ Parameters ---------- package_name Returns ------- """ logger.warning( f"[*] App Already Installed, start to monitoring ${package_name}") adb = ADB() logger.info("[*] Frida Initialization") if not is_google_emulator: push_and_start_frida_server(adb) else: push_and_start_frida_server_google_emulator(adb) return package_name
def _get_ps_meminfo(self, ps) -> dict: meminfo = {} raw_meminfo = ADB.get_meminfo(self.dev_id, ps) for line in raw_meminfo: if "Java Heap:" in line: meminfo["Java Heap"] = line.split()[2] elif "Native Heap:" in line: meminfo["Native Heap"] = line.split()[2] elif "Code:" in line: meminfo["Code"] = line.split()[1] elif "Stack:" in line: meminfo["Stack"] = line.split()[1] elif "Graphics:" in line: meminfo["Graphics"] = line.split()[1] elif "Private Other:" in line: meminfo["Private Other"] = line.split()[2] elif "System:" in line: meminfo["System"] = line.split()[1] elif "TOTAL:" in line: meminfo["Total"] = line.split()[1] return meminfo
def run_app(adb: ADB, cfg: Config): devices = adb.get_devices()[1] if len(devices) > 1: for device in devices: disconnect_client(adb, device) response = connect_client(adb, cfg.wireless.wireless_address) if response.startswith('unable'): return (response) elif "already" in response: if "-f" in sys.argv: response = reconnect(adb, cfg) return (response) else: if '-s' not in sys.argv: return ("Reconnect using -f if needed") elif response.startswith('connected to'): return ("Connection restored") else: return ("Unknown error: " + response)
def pull_api_monitor_xposed(adb: ADB, package_name: str, result_directory: str, md5_app: str = None): """ Parameters ---------- adb package_name result_directory md5_app Returns ------- """ extracted_log_path = os.path.join(result_directory, 'monitoring_api_{}.log'.format(md5_app)) try: adb.execute(['root']) except Exception: adb.kill_server() adb.pull_file('/data/data/{0}/TalosApiMonitor/apimonitor.log'.format(package_name), extracted_log_path)
class ADB_Wrapper(object): def __init__(self, adb_path): self.adb_path = adb_path self.adb = None self.devices = [] self.adb = ADB(adb_path) if NEED_RESTART_ADB: self.restart_adb() def restart_adb(self): print '[+] Restarting ADB server as ROOT...' self.adb.set_adb_root(1) if self.adb.lastFailed(): print '\t Restart ADB ERROR\n' exit(-3) print 'Restart ADB as ROOT successed!' def get_detected_devices(self): self.devices = None dev = 0 while dev is 0: print '[+] Detecting devices...' error, devices = self.adb.get_devices() if error is 1: print 'No devices connnected' print '[+] Waiting for deices...' self.adb.wait_for_device() continue elif error is 2: print "You haven't enought permissions!" exit(-3) # If devices is ['*', 'deamon', 'start', 'successfully'.....], # means that we should restart adb untill we get valid devices if len(devices ) > 3 and devices[0] == '*' and devices[1] == 'daemon': print '[W] get devices error, we should restart the adb' continue print '[+] Get devices successfully' self.devices = devices dev = 1 def set_target_device(self): devices_count = 0 for dev in self.devices: print '\t%d: %s' % (devices_count, dev) if dev != 'offline': devices_count += 1 # For the cmd 'adb forward ......' can exec successly only when there is one device/emulator, # so if there are more than one devices, we exit. if devices_count > 1: print '[Error] More than one devices/emulators, please shut down others!' exit(-3) # set target device dev_index = 0 try: self.adb.set_target_device(self.devices[dev_index]) except Exception, e: print '[E] Set target devices error, error info:', e print '==== Do not warry, just try again!===' exit(-5) print "\n[+] Using '%s' as target device" % self.devices[dev_index]
def push_and_start_frida_server_google_emulator(adb: ADB): """ Parameters ---------- adb Returns ------- """ frida_server = os.path.join(os.path.dirname(__file__), "resources", "frida-server-15-1-17", "frida-server") logger.info("[*] Checking if frida-server is already running") cmd_output = adb.shell("ps -e | grep frida") if "frida-server" in cmd_output: logger.warning("[*] frida-server is already running on device") return logger.info("[*] Push frida-server (google-emulator)") try: adb.push_file(frida_server, "/sdcard") adb.shell_su("mv /sdcard/frida-server /data/local/tmp/frida-server") except Exception as e: pass cmd_set_enforce = "setenforce 0" adb.shell_su(cmd_set_enforce) cmd_enforce_echo = "echo 0 > /sys/fs/selinux/enforce" adb.shell_su(cmd_enforce_echo) chmod_frida = "chmod 755 /data/local/tmp/frida-server" adb.shell_su(chmod_frida) logger.info("[*] Start frida server") start_frida = "/data/local/tmp/frida-server &" adb.shell_su(start_frida, is_async=True) time.sleep(4)
def main(): path = r'adb' adb = ADB(path) # set ADB path #adb.set_adb_path('~/android-sdk-linux/platform-tools/adb') print "[+] Using PyADB version %s" % adb.pyadb_version() # verity ADB path print "[+] Verifying ADB path...", if adb.check_path() is False: print "ERROR" exit(-2) print "OK" # print ADB Version print "[+] ADB Version: %s" % adb.get_version() print "" # restart server (may be other instances running) print "[+] Restarting ADB server..." adb.restart_server() if adb.lastFailed(): print "\t- ERROR\n" exit(-3) # get detected devices dev = 0 while dev is 0: print "[+] Detecting devices..." , error,devices = adb.get_devices() if error is 1: # no devices connected print "No devices connected" print "[+] Waiting for devices..." adb.wait_for_device() continue elif error is 2: print "You haven't enought permissions!" exit(-3) print "OK" dev = 1 # this should never be reached if len(devices) == 0: print "[+] No devices detected!" exit(-4) # show detected devices i = 0 for dev in devices: print "\t%d: %s" % (i,dev) i += 1 # if there are more than one devices, ask to the user to choose one of them if i > 1: dev = i + 1 while dev < 0 or dev > int(i - 1): print "\n[+] Select target device [0-%d]: " % int(i - 1) , dev = int(stdin.readline()) else: dev = 0 # set target device try: adb.set_target_device(devices[dev]) except Exception,e: print "\n[!] Error:\t- ADB: %s\t - Python: %s" % (adb.get_error(),e.args) exit(-5)
class ADB_Wrapper(object): def __init__(self, adb_path): self.adb_path = adb_path self.adb = None self.devices = [] self.adb = ADB(adb_path) if NEED_RESTART_ADB: self.restart_adb() def restart_adb(self): print '[+] Restarting ADB server as ROOT...' self.adb.set_adb_root(1) if self.adb.lastFailed(): print '\t Restart ADB ERROR\n' exit(-3) print 'Restart ADB as ROOT successed!' def get_detected_devices(self): self.devices = None dev = 0 while dev is 0: print '[+] Detecting devices...' error, devices = self.adb.get_devices() if error is 1: print 'No devices connnected' print '[+] Waiting for deices...' self.adb.wait_for_device() continue elif error is 2: print "You haven't enought permissions!" exit(-3) # If devices is ['*', 'deamon', 'start', 'successfully'.....], # means that we should restart adb untill we get valid devices if len(devices) > 3 and devices[0] == '*' and devices[1] == 'daemon': print '[W] get devices error, we should restart the adb' continue print '[+] Get devices successfully' self.devices = devices dev = 1 def set_target_device(self): devices_count = 0 for dev in self.devices: print '\t%d: %s' % (devices_count, dev) if dev != 'offline': devices_count += 1 # For the cmd 'adb forward ......' can exec successly only when there is one device/emulator, # so if there are more than one devices, we exit. if devices_count > 1: print '[Error] More than one devices/emulators, please shut down others!' exit(-3) # set target device dev_index = 0 try: self.adb.set_target_device(self.devices[dev_index]) except Exception, e: print '[E] Set target devices error, error info:', e print '==== Do not warry, just try again!===' exit(-5) print "\n[+] Using '%s' as target device" % self.devices[dev_index]
def main1(): # set ADB path path = r'adb' adb = ADB(path) print path adb.set_adb_path(path) print "[+] Using PyADB version %s" % adb.pyadb_version() # verity ADB path print "[+] Verifying ADB path...", if adb.check_path() is False: print "ERROR" exit(-2) print "OK" # print ADB Version print "[+] ADB Version: %s" % adb.get_version() print "" # restart server (may be other instances running) print "[+] Restarting ADB server..." adb.restart_server() if adb.lastFailed(): print "\t- ERROR\n" exit(-3) # get detected devices dev = 0 while dev is 0: print "[+] Detecting devices..." , error,devices = adb.get_devices() if error is 1: # no devices connected print "No devices connected" print "[+] Waiting for devices..." adb.wait_for_device() continue elif error is 2: print "You haven't enought permissions!" exit(-3) print "OK" dev = 1 # this should never be reached if len(devices) == 0: print "[+] No devices detected!" exit(-4) # # show detected devices # i = 0 # for dev in devices: # print "\t%d: %s" % (i,dev) # i += 1 # # # if there are more than one devices, ask to the user to choose one of them # if i > 1: # dev = i + 1 # while dev < 0 or dev > int(i - 1): # print "\n[+] Select target device [0-%d]: " % int(i - 1) , # dev = int(stdin.readline()) # else: # dev = 0 # # # set target device # try: # adb.set_target_device(devices[dev]) # except Exception,e: # print "\n[!] Error:\t- ADB: %s\t - Python: %s" % (adb.get_error(),e.args) # exit(-5) # # print "\n[+] Using \"%s\" as target device" % devices[dev] # # # check if 'su' binary is available # print "[+] Looking for 'su' binary: ", # supath = adb.find_binary("su") # # if supath is not None: # print "%s" % supath # else: # print "Error: %s" % adb.get_error() # # # 'su' binary has been found # if supath is not None: # print "[+] Checking if 'su' binary can give root access:" # rootid = adb.shell_command('%s -c id' % supath) # if adb.lastFailed() is False and 'root' in rootid.replace('(',')').split(')'): # it can provide root privileges # print "\t- Yes" # get_whatsapp_root(adb,supath) # else: # only have normal-user # print "\t- No: %s" % adb.get_error() # get_whatsapp_nonroot(adb) # else: # get_whatsapp_nonroot(adb) exit(0)
from adb import ADB debug = ADB() print debug.devices() debug.shell("input keyevent 26") debug.shell("input keyevent 82") debug.shell("input swipe 50 50 800 50") #debug.screenShot("./ss.png")
def push_and_start_frida_server(adb: ADB): """ Push and start adb server on device Parameters ---------- adb Returns ------- """ frida_server = os.path.join(os.path.dirname(__file__), "resources", "frida-server", "frida-server") cmd_output = adb.shell("ps -e | grep frida".split()) if "frida-server" in cmd_output: logger.warning("[*] frida-server is already running on device") return try: adb.execute(["root"]) except Exception as e: adb.kill_server() logger.error("Error on adb {}".format(e)) logger.info("[*] Push frida server") try: adb.push_file(frida_server, "/data/local/tmp") except Exception as e: pass logger.info("[*] Add execution permission to frida-server") chmod_frida = ["chmod 755 /data/local/tmp/frida-server"] adb.shell(chmod_frida) logger.info("Start frida server") start_frida = ["cd /data/local/tmp && ./frida-server &"] adb.shell(start_frida, is_async=True) time.sleep(4)