PythonTermux adb打造手机自动化工作流从定时打卡到智能备份每天早上七点半我的手机都会自动执行一系列操作关闭勿扰模式、打开钉钉完成打卡、给女友发送早安问候、备份微信聊天记录到私有云。这一切都通过Python脚本和Termux中的adb功能实现完全自动化运行。本文将带你从零构建这样的智能工作流无需ROOT权限用技术真正解放双手。1. 环境搭建Termux与adb的完美结合在开始自动化脚本编写前我们需要搭建一个可靠的基础环境。Termux作为Android上的Linux终端模拟器配合adb工具可以突破手机操作的限制。1.1 Termux基础配置首先从F-Droid安装TermuxGoogle Play版本已停止更新然后执行以下基础配置pkg update pkg upgrade pkg install python android-tools pip install --upgrade pip注意建议使用Termux官方仓库而非第三方源避免兼容性问题关键工具安装完成后需要配置adb环境。由于我们是在手机本地使用adb与传统电脑连接手机的方式有所不同adb tcpip 5555 adb connect localhost:5555验证连接是否成功adb devices正常应显示类似以下输出List of devices attached localhost:5555 device1.2 Python环境准备我们将使用Python作为主要开发语言因其丰富的库支持和易用性pkg install python pip install schedule pyautogui pillow numpy为方便调试建议安装code-server或配置SSHpkg install openssh sshd passwd # 设置访问密码现在可以通过电脑浏览器访问http://手机IP:8022进行远程开发。2. 核心自动化技术解析理解adb的基本操作原理是构建自动化工作流的关键。adb(Android Debug Bridge)提供了与设备交互的丰富接口。2.1 adb常用命令深度应用掌握这些核心命令可以完成90%的自动化操作输入控制import os # 点击操作 os.system(adb shell input tap 500 1200) # 滑动操作(起始x,y 结束x,y 持续时间ms) os.system(adb shell input swipe 300 1000 300 500 300) # 文本输入 os.system(adb shell input text HelloWorld)屏幕与界面操作# 截图并保存到Termux os.system(adb exec-out screencap -p /sdcard/screen.png) # 按键事件(3HOME, 4BACK, 26POWER) os.system(adb shell input keyevent 26)应用管理# 启动应用 os.system(adb shell am start -n com.tencent.mm/.ui.LauncherUI) # 停止应用 os.system(adb shell am force-stop com.tencent.mm)2.2 图像识别增强自动化单纯基于坐标的点击不够健壮结合图像识别可以构建更可靠的自动化流程from PIL import Image import numpy as np import cv2 def find_image_pos(template_path, threshold0.8): # 获取当前屏幕截图 os.system(adb exec-out screencap -p current.png) img cv2.imread(current.png, 0) # 加载模板图像 template cv2.imread(template_path, 0) w, h template.shape[::-1] # 模板匹配 res cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED) loc np.where(res threshold) if len(loc[0]) 0: return (loc[1][0]w//2, loc[0][0]h//2) # 返回中心坐标 return None这个函数可以在屏幕上寻找特定图标或按钮的位置比固定坐标更可靠。3. 实战案例微信自动化工作流让我们实现一个完整的微信自动化案例包含收取蚂蚁森林能量和自动备份聊天记录。3.1 自动收取蚂蚁森林能量import time import os def collect_ant_forest(): # 启动微信 os.system(adb shell am start -n com.tencent.mm/.ui.LauncherUI) time.sleep(3) # 进入蚂蚁森林 os.system(adb shell input tap 300 1200) # 点击发现 time.sleep(1) os.system(adb shell input tap 300 800) # 点击蚂蚁森林 time.sleep(5) # 识别并收取能量 for _ in range(10): # 最多尝试10次 pos find_image_pos(energy_template.png) if pos: os.system(fadb shell input tap {pos[0]} {pos[1]}) time.sleep(0.5) # 返回主页 os.system(adb shell input keyevent 4) os.system(adb shell input keyevent 4) # 定时执行 schedule.every().day.at(07:30).do(collect_ant_forest)3.2 微信聊天记录备份def backup_wechat_data(): # 创建备份目录 backup_dir /sdcard/WeChatBackup/time.strftime(%Y%m%d) os.system(fmkdir -p {backup_dir}) # 备份文本消息 os.system(adb pull /sdcard/Android/data/com.tencent.mm/MicroMsg {backup_dir}) # 备份媒体文件 os.system(fadb pull /sdcard/DCIM/Camera {backup_dir}/Camera) os.system(fadb pull /sdcard/Pictures/WeiXin {backup_dir}/WeiXin) # 压缩并上传到云存储 os.system(ftar -czf {backup_dir}.tar.gz {backup_dir}) os.system(frclone copy {backup_dir}.tar.gz mydrive:/Backups/WeChat/) # 每周日凌晨3点执行 schedule.every().sunday.at(03:00).do(backup_wechat_data)4. 进阶技巧打造智能情景模式结合传感器和条件判断可以实现更智能的自动化场景。4.1 自动静音与勿扰模式def check_and_set_silent(): current_hour time.localtime().tm_hour if 23 current_hour or current_hour 7: # 夜间自动静音 os.system(adb shell settings put system volume_system 0) os.system(adb shell settings put system volume_ring 0) os.system(adb shell settings put system volume_notification 0) else: # 白天恢复音量 os.system(adb shell settings put system volume_system 5) os.system(adb shell settings put system volume_ring 5) os.system(adb shell settings put system volume_notification 3) schedule.every().hour.do(check_and_set_silent)4.2 基于位置的自动化通过WiFi连接状态判断位置执行不同操作def check_location(): # 获取当前连接的WiFi result os.popen(adb shell dumpsys wifi | grep SSID:).read() if Home_WiFi in result: # 在家时自动开启智能家居 os.system(adb shell am start -n com.xiaomi.smarthome/.SmartHomeMainActivity) elif Office_WiFi in result: # 在公司时关闭娱乐应用通知 os.system(adb shell appops set com.douban.movie RUN_IN_BACKGROUND ignore) schedule.every(30).minutes.do(check_location)5. 系统优化与错误处理确保自动化脚本长期稳定运行需要完善的错误处理机制。5.1 自动化监控与恢复def monitor_automation(): # 检查adb连接状态 devices os.popen(adb devices).read().strip().split(\n) if len(devices) 2: os.system(adb kill-server) os.system(adb connect localhost:5555) # 检查Termux运行状态 if not os.popen(pgrep termux).read(): os.system(am start -n com.termux/.app.TermuxActivity) # 记录运行状态 with open(/sdcard/automation.log, a) as f: f.write(f{time.ctime()}: Automation check passed\n) schedule.every(6).hours.do(monitor_automation)5.2 性能优化技巧长时间运行的Python脚本需要注意资源管理# 内存优化 import gc def optimize_memory(): gc.collect() # 清理临时文件 os.system(rm -f /tmp/*.png) # 每6小时执行一次内存优化 schedule.every(6).hours.do(optimize_memory) # 使用低功耗模式 def set_low_power(): os.system(adb shell settings put global low_power 1) os.system(adb shell settings put global wifi_scan_throttle_enabled 1) # 夜间启用省电模式 schedule.every().day.at(23:00).do(set_low_power) schedule.every().day.at(07:00).do( lambda: os.system(adb shell settings put global low_power 0) )6. 安全与隐私保护自动化脚本处理个人数据时安全措施必不可少。6.1 敏感数据加密from cryptography.fernet import Fernet # 生成密钥(仅首次运行需要) # key Fernet.generate_key() # with open(/sdcard/secret.key, wb) as key_file: # key_file.write(key) def encrypt_file(file_path): with open(/sdcard/secret.key, rb) as key_file: key key_file.read() fernet Fernet(key) with open(file_path, rb) as f: original f.read() encrypted fernet.encrypt(original) with open(file_path .enc, wb) as f: f.write(encrypted) os.remove(file_path) def decrypt_file(encrypted_path): with open(/sdcard/secret.key, rb) as key_file: key key_file.read() fernet Fernet(key) with open(encrypted_path, rb) as f: encrypted f.read() decrypted fernet.decrypt(encrypted) with open(encrypted_path[:-4], wb) as f: # 移除.enc后缀 f.write(decrypted)6.2 自动化脚本权限控制# 设置Termux文件权限 os.system(chmod 700 ~/.termux) os.system(chmod 600 ~/.termux/*) # 敏感脚本加密存储 important_scripts [backup_wechat.py, auto_login.py] for script in important_scripts: encrypt_file(f/sdcard/scripts/{script}) # 仅在使用时解密 def run_protected_script(script_name): decrypt_file(f/sdcard/scripts/{script_name}.enc) os.system(fpython /sdcard/scripts/{script_name}) encrypt_file(f/sdcard/scripts/{script_name})