影刀RPA ADB指令大全:手机自动化操作的底层命令详解

影刀RPA ADB指令大全:手机自动化操作的底层命令详解

作者:林焱


写在前面

ADB(Android Debug Bridge)是Android手机自动化的核心工具。影刀的ADB功能已经封装了常用指令,但很多高级操作还是需要自己写ADB命令。本文整理了ADB在RPA场景中最常用的指令,结合影刀Python节点使用。


一、ADB环境搭建

安装ADB

  1. 下载Android Platform Tools:https://developer.android.com/studio/releases/platform-tools

  2. 解压到本地,如C:\adb\

  3. 将路径加入系统环境变量PATH

  4. 手机开启"开发者选项" → “USB调试”

  5. 连接USB后运行:adb devices,看到设备ID则连接成功

importsubprocessdefrun_adb(command,device_id=None):""" 执行ADB命令 device_id: 多设备时指定设备,单设备可不填 """ifdevice_id:cmd=f"adb -s{device_id}{command}"else:cmd=f"adb{command}"result=subprocess.run(cmd,shell=True,capture_output=True,text=True,encoding='utf-8')returnresult.stdout.strip(),result.returncode# 检查连接的设备devices,_=run_adb("devices")print(devices)

拼多多店群自动化报活动上架!

二、常用ADB指令分类

设备信息

# 获取设备型号model,_=run_adb("shell getprop ro.product.model")print(f"设备型号:{model}")# 获取Android版本android_version,_=run_adb("shell getprop ro.build.version.release")print(f"Android版本:{android_version}")# 获取屏幕分辨率resolution,_=run_adb("shell wm size")print(f"分辨率:{resolution}")# 如 Physical size: 1080x2400# 获取屏幕密度![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/78e023e29af842cc81dd3540fd11e49d.png#pic_center)density,_=run_adb("shell wm density")print(f"屏幕密度:{density}")# 获取电量battery,_=run_adb("shell dumpsys battery | grep level")print(f"电量:{battery}")# 获取当前前台APPcurrent_app,_=run_adb("shell dumpsys window | grep mCurrentFocus")print(f"当前应用:{current_app}")

触控操作

# 点击坐标 (x, y)deftap(x,y):run_adb(f"shell input tap{x}{y}")# 长按deflong_press(x,y,duration_ms=1000):run_adb(f"shell input swipe{x}{y}{x}{y}{duration_ms}")# 滑动 (从x1,y1 滑到 x2,y2)defswipe(x1,y1,x2,y2,duration_ms=500):run_adb(f"shell input swipe{x1}{y1}{x2}{y2}{duration_ms}")# 向上滑动(滚动)defscroll_up(distance=500):swipe(540,1200,540,1200-distance,300)defscroll_down(distance=500):swipe(540,700,540,700+distance,300)# 双击defdouble_tap(x,y):tap(x,y)importtime time.sleep(0.1)tap(x,y)

文字输入

importurllib.parsedefinput_text(text):"""向当前焦点输入框输入文字"""# 对特殊字符进行URL编码encoded=urllib.parse.quote(text)run_adb(f"shell am broadcast -a ADB_INPUT_TEXT --es msg '{encoded}'")# 注意:中文输入需要安装ADBKeyboard输入法definput_text_adbkeyboard(text):"""使用ADBKeyboard输入法输入中文(推荐)"""encoded=urllib.parse.quote(text)run_adb(f"shell am broadcast -a ADB_INPUT_TEXT --es msg '{encoded}'")defclear_input():"""清空当前输入框"""# 全选后删除run_adb("shell input keyevent KEYCODE_CTRL_A")run_adb("shell input keyevent KEYCODE_DEL")

按键事件

# 常用KEYCODE映射KEYCODE={"back":4,"home":3,"menu":82,"volume_up":24,"volume_down":25,"power":26,"enter":66,"del":67,"tab":61,"space":62,"search":84,}![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/fd0bb898172d49fba55c7bdc3441ca73.png#pic_center)defpress_key(key_name):keycode=KEYCODE.get(key_name)ifkeycode:run_adb(f"shell input keyevent{keycode}")else:print(f"未知按键:{key_name}")# 示例press_key("home")# 回到桌面press_key("back")# 返回importtime time.sleep(0.5)

截图与文件传输

deftake_screenshot(save_path="screenshot.png"):"""截取手机屏幕并保存到电脑"""# 先截图到手机run_adb("shell screencap -p /sdcard/screen.png")# 再拉取到电脑run_adb(f"pull /sdcard/screen.png{save_path}")returnsave_pathdefpush_file(local_path,remote_path="/sdcard/"):"""将文件推送到手机"""run_adb(f"push{local_path}{remote_path}")defpull_file(remote_path,local_path="."):"""从手机拉取文件"""run_adb(f"pull{remote_path}{local_path}")

三、应用管理

definstall_apk(apk_path):"""安装APK"""output,code=run_adb(f"install -r{apk_path}")print(f"安装结果:{output}")returncode==0defuninstall_app(package_name):"""卸载应用"""run_adb(f"uninstall{package_name}")deflaunch_app(package_name,activity=None):"""启动应用"""ifactivity:run_adb(f"shell am start -n{package_name}/{activity}")else:run_adb(f"shell monkey -p{package_name}-c android.intent.category.LAUNCHER 1")defstop_app(package_name):"""强制停止应用"""run_adb(f"shell am force-stop{package_name}")defclear_app_data(package_name):"""清除应用数据(相当于卸载重装)"""run_adb(f"shell pm clear{package_name}")# 列出所有已安装的应用deflist_installed_apps(system_apps=False):flag=""ifsystem_appselse"-3"# -3 只列第三方应用output,_=run_adb(f"shell pm list packages{flag}")packages=[line.replace("package:","").strip()forlineinoutput.split("\n")]returnpackages# 获取应用版本defget_app_version(package_name):output,_=run_adb(f"shell dumpsys package{package_name}| grep versionName")returnoutput.strip()

四、实战案例:多台设备批量操作

defget_connected_devices():"""获取所有已连接的设备ID"""output,_=run_adb("devices")lines=output.split("\n")devices=[]forlineinlines[1:]:# 跳过第一行 "List of devices attached"if"\tdevice"inline:device_id=line.split("\t")[0].strip()devices.append(device_id)returndevicesdefbatch_operation(devices,operation_func):"""在多台设备上批量执行操作"""results={}fordevice_idindevices:try:print(f"正在操作设备:{device_id}")result=operation_func(device_id)results[device_id]={"success":True,"result":result}exceptExceptionase:results[device_id]={"success":False,"error":str(e)}returnresults# 在所有设备上安装APPconnected_devices=get_connected_devices()print(f"已连接{len(connected_devices)}台设备:{connected_devices}")definstall_on_device(device_id):output,_=run_adb(f"install -r app.apk",device_id=device_id)returnoutput results=batch_operation(connected_devices,install_on_device)fordevice_id,resultinresults.items():status="✅成功"ifresult["success"]elsef"❌失败:{result.get('error')}"print(f"设备{device_id}{status}")

五、ADB无线连接(不用USB线)

# 步骤1:先用USB连接,开启无线调试run_adb("tcpip 5555")importtime time.sleep(1)# 步骤2:获取设备IPip_output,_=run_adb("shell ip addr show wlan0 | grep 'inet '")# 从输出中提取IP地址importre ![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/69e941ba75de42cca4a8537ceab4237d.png#pic_center)ip_match=re.search(r'inet (\d+\.\d+\.\d+\.\d+)',ip_output)ifip_match:device_ip=ip_match.group(1)print(f"设备IP:{device_ip}")# 步骤3:断开USB,通过网络连接connect_result,_=run_adb(f"connect{device_ip}:5555")print(f"无线连接结果:{connect_result}")

TEMU店群矩阵自动化运营核价报活动

六、踩坑记录

坑1:中文输入乱码
标准ADB input text不支持中文。解决方案:安装ADBKeyboard(一款专为ADB设计的输入法),然后切换到该输入法后发送broadcast指令输入中文。

坑2:不同手机坐标不同
手机屏幕分辨率不同,坐标需要按分辨率换算。用百分比坐标更通用:

deftap_by_ratio(x_ratio,y_ratio):"""按屏幕比例点击,x_ratio和y_ratio都是0-1之间"""w,h=get_screen_size()![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/4721125f76d849539a85c48c06866e4a.png#pic_center)tap(int(w*x_ratio),int(h*y_ratio))

坑3:ADB连接不稳定
USB连接中途断开很常见。加重连逻辑:

defensure_connected(device_id=None,max_retry=3):foriinrange(max_retry):devices,_=run_adb("devices")ifdevice_idanddevice_idindevices:returnTruerun_adb("kill-server")time.sleep(1)run_adb("start-server")time.sleep(2)returnFalse

坑4:系统弹窗拦截
手机操作中经常出现权限请求弹窗、系统更新提示等。用截图识别弹窗后自动关闭:

defdismiss_popups():screenshot=take_screenshot()# 识别常见弹窗按钮("取消"、"不再提示"、"关闭")# 用影刀OCR识别或图像匹配

总结

ADB是手机自动化的基础工具,掌握这些指令后,配合截图+图像识别,可以实现大多数手机App的自动化操作。核心原则:先截图确认当前状态,操作后等待并截图验证,异常时保存截图方便调试。

署名:林焱