安卓免Root自动化进阶:在Termux的Ubuntu里用Python调用adb,打造私人助理

张开发
2026/4/21 15:07:00 15 分钟阅读
安卓免Root自动化进阶:在Termux的Ubuntu里用Python调用adb,打造私人助理
安卓免Root自动化进阶在Termux的Ubuntu里用Python调用adb打造私人助理在移动设备上实现自动化操作一直是技术爱好者的追求但传统方法往往需要Root权限既存在安全风险又可能影响设备保修。如今借助Termux和Python的组合我们可以在不获取Root权限的情况下构建强大的手机自动化系统。这种方案特别适合那些希望在移动端进行轻量级脚本开发又不想折腾系统底层的技术爱好者。想象一下你的手机能够自动识别屏幕内容并做出相应操作或者根据应用状态自动执行预设任务——这些都不再是梦想。本文将带你深入探索如何利用Termux中的Ubuntu环境通过Python脚本与adb交互打造属于你自己的智能私人助理系统。1. 环境搭建与基础配置1.1 Termux与Ubuntu环境准备要在Android设备上运行完整的Ubuntu系统Termux是最佳选择。首先通过F-Droid或Google Play安装Termux应用。安装完成后执行以下命令更新软件包并安装必要组件pkg update pkg upgrade pkg install proot-distro proot-distro install ubuntu proot-distro login ubuntu进入Ubuntu环境后建议先进行基础配置apt update apt upgrade apt install python3 python3-pip vim git提示Termux的Ubuntu环境虽然是容器化的但提供了近乎完整的Linux体验包括软件包管理和文件系统操作。1.2 ADB环境配置在Ubuntu环境中安装adb工具是自动化操作的关键apt install android-tools-adb配置完成后需要通过USB调试模式连接手机。在开发者选项中启用USB调试和网络ADB调试然后执行adb tcpip 5555 adb connect 127.0.0.1:5555验证连接是否成功adb devices常见连接问题及解决方案问题现象可能原因解决方法设备未列出USB调试未启用检查开发者选项设置连接超时网络ADB未开启执行adb tcpip 5555权限拒绝未授权设备手机端确认授权对话框2. Python与ADB交互基础2.1 基本命令调用Python中调用adb命令最简单的方式是使用os.systemimport os def run_adb_command(command): result os.system(fadb {command}) return result # 示例获取设备信息 device_info run_adb_command(shell getprop ro.product.model)然而这种方法无法直接获取命令输出。更推荐使用subprocess模块import subprocess def get_adb_output(command): process subprocess.Popen( [adb] command.split(), stdoutsubprocess.PIPE, stderrsubprocess.PIPE ) stdout, stderr process.communicate() return stdout.decode(utf-8).strip() # 示例获取当前活动窗口 current_activity get_adb_output(shell dumpsys window windows | grep -E mCurrentFocus)2.2 常用ADB操作封装为了提高代码复用性我们可以将常用ADB操作封装成类class ADBHelper: def __init__(self): self.check_connection() def check_connection(self): devices self._run_command(devices) if device not in devices: raise ConnectionError(ADB设备未连接) def _run_command(self, command): return subprocess.getoutput(fadb {command}) def tap(self, x, y): self._run_command(fshell input tap {x} {y}) def swipe(self, x1, y1, x2, y2, duration300): self._run_command(fshell input swipe {x1} {y1} {x2} {y2} {duration}) def screenshot(self, save_path/sdcard/screen.png): self._run_command(fshell screencap -p {save_path}) self._run_command(fpull {save_path} ./screenshot.png) return ./screenshot.png def get_current_package(self): output self._run_command(shell dumpsys window windows | grep -E mCurrentFocus) return output.split()[-1].split(/)[0]3. 高级自动化场景实现3.1 屏幕信息分析与响应结合Python的图像处理库我们可以实现基于屏幕内容的智能响应from PIL import Image import cv2 import numpy as np def analyze_screenshot(): # 获取截图 screenshot_path adb.screenshot() # 使用OpenCV处理图像 img cv2.imread(screenshot_path) gray cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 示例检测特定按钮 template cv2.imread(button_template.png, 0) res cv2.matchTemplate(gray, template, cv2.TM_CCOEFF_NORMED) threshold 0.8 loc np.where(res threshold) if len(loc[0]) 0: # 找到按钮位置点击中心点 center_x loc[1][0] template.shape[1] // 2 center_y loc[0][0] template.shape[0] // 2 adb.tap(center_x, center_y) return True return False3.2 应用状态监控与自动化通过监控应用状态可以实现更智能的自动化流程import time class AppMonitor: def __init__(self, target_package): self.target_package target_package self.adb ADBHelper() def monitor_loop(self, interval5): while True: current_pkg self.adb.get_current_package() if current_pkg self.target_package: self.handle_target_app() time.sleep(interval) def handle_target_app(self): # 自定义应用处理逻辑 screenshot_path self.adb.screenshot() if self.detect_specific_condition(screenshot_path): self.adb.tap(100, 200) # 示例操作 def detect_specific_condition(self, image_path): # 实现特定的条件检测逻辑 pass4. 性能优化与错误处理4.1 减少ADB调用延迟频繁的ADB调用会导致明显的延迟以下优化策略可以显著提升性能批量执行命令将多个命令合并为一个shell脚本执行保持ADB连接避免频繁建立/断开连接本地缓存缓存不常变化的信息如设备型号异步执行对非顺序依赖的命令使用多线程示例批量命令执行def execute_commands(commands): script .join(commands) return subprocess.getoutput(fadb shell {script}) # 使用示例 results execute_commands([ input tap 100 200, am start -n com.example.app/.MainActivity, pm list packages ])4.2 健壮的错误处理机制自动化脚本需要处理各种异常情况class ADBError(Exception): pass def safe_adb_operation(func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except subprocess.CalledProcessError as e: raise ADBError(fADB命令执行失败: {e.cmd}) except FileNotFoundError: raise ADBError(ADB命令未找到请检查环境配置) except Exception as e: raise ADBError(f未知错误: {str(e)}) return wrapper safe_adb_operation def reliable_adb_command(command): result subprocess.run( [adb] command.split(), checkTrue, stdoutsubprocess.PIPE, stderrsubprocess.PIPE, textTrue ) return result.stdout5. 项目架构与扩展思路5.1 模块化脚本设计良好的项目结构可以大大提高脚本的可维护性/automation_project │── /modules │ ├── adb_utils.py # ADB基础操作封装 │ ├── image_utils.py # 图像处理功能 │ └── app_monitor.py # 应用监控逻辑 │── /configs │ ├── device_config.json # 设备特定配置 │ └── app_profiles.json # 应用行为配置 │── main.py # 主程序入口 │── requirements.txt # 依赖列表5.2 扩展功能思路OCR集成使用Tesseract等库实现文本识别语音控制结合语音识别库增加语音指令支持云端同步将脚本配置和日志同步到云端规则引擎实现基于条件的复杂自动化规则机器学习引入简单模型实现智能决策示例OCR集成import pytesseract def extract_text_from_screen(regionNone): screenshot adb.screenshot() img Image.open(screenshot) if region: img img.crop(region) text pytesseract.image_to_string(img) return text.strip() # 使用示例 battery_text extract_text_from_screen((50, 100, 200, 150))在实际项目中我发现将常用操作封装成高阶函数能极大提升开发效率。比如创建一个wait_then_tap函数可以等待特定图像出现后再执行点击操作这种组合操作在实际自动化场景中非常实用。另一个经验是保持ADB命令的日志记录对于调试复杂自动化流程至关重要——当脚本没有按预期工作时详细的执行日志能帮你快速定位问题所在。

更多文章