[1341]python ppadb简单使用

71 阅读4分钟

@[toc] 以下是 python-ppadb 的详细使用教程,这是一个用于通过 ADB(Android Debug Bridge)控制 Android 设备的 Python 库。

1. 📦 安装和环境配置

安装 python-ppadb

pip install pure-python-adb

# 或者从源码安装
pip install git+https://github.com/Swind/pure-python-adb

配置 ADB 环境

# 检查 ADB 是否安装
adb version

# 启动 ADB 服务
adb start-server

# 查看连接的设备
adb devices

2. 🔌 基础连接和设备管理

初始化连接

from ppadb.client import Client as AdbClient

def connect_device():
    # 默认连接本地ADB服务
    client = AdbClient(host="127.0.0.1", port=5037)
    
    # 获取设备列表
    devices = client.devices()
    
    if len(devices) == 0:
        print("没有找到连接的设备")
        return None
    
    device = devices[0]
    print(f"连接到设备: {device.serial}")
    return device

# 连接设备
device = connect_device()

设备信息获取

def get_device_info(device):
    # 获取设备基本信息
    print(f"设备序列号: {device.serial}")
    print(f"设备状态: {device.get_state()}")
    
    # 获取设备属性
    print(f"产品型号: {device.get_property('ro.product.model')}")
    print(f"Android版本: {device.get_property('ro.build.version.release')}")
    print(f"品牌: {device.get_property('ro.product.brand')}")
    print(f"分辨率: {device.shell('wm size')}")
    print(f"电量: {device.shell('dumpsys battery | grep level')}")

get_device_info(device)

3. 🎯 基本设备操作

输入操作

def basic_operations(device):
    # 按键操作
    device.shell('input keyevent 3')  # HOME键
    device.shell('input keyevent 4')  # 返回键
    device.shell('input keyevent 26')  # 电源键
    
    # 触摸操作
    device.shell('input tap 500 500')  # 点击坐标 (500, 500)
    
    # 滑动操作
    device.shell('input swipe 300 1000 300 500')  # 向上滑动
    device.shell('input swipe 500 500 300 500')   # 向左滑动
    
    # 文本输入
    device.shell('input text "hello"')

basic_operations(device)

屏幕操作

def screen_operations(device):
    # 截图
    result = device.screencap()
    with open('screenshot.png', 'wb') as f:
        f.write(result)
    
    # 点亮/关闭屏幕
    device.shell('input keyevent 26')  # 电源键切换
    
    # 获取屏幕尺寸
    size_output = device.shell('wm size')
    print(f"屏幕尺寸: {size_output}")

screen_operations(device)

4. 📱 APP 管理

APP 安装和卸载

def app_management(device):
    # 安装APK
    device.install('app.apk')
    
    # 卸载APP
    device.uninstall('com.example.package')
    
    # 启动APP
    device.shell('am start -n com.android.chrome/.MainActivity')
    
    # 强制停止APP
    device.shell('am force-stop com.android.chrome')
    
    # 获取当前活动
    current_activity = device.shell('dumpsys window windows | grep -E mCurrentFocus')
    print(f"当前活动: {current_activity}")

app_management(device)

APP 信息获取

def get_app_info(device):
    # 获取已安装应用列表
    apps = device.shell('pm list packages -3')  # 第三方应用
    print("已安装应用:")
    print(apps)
    
    # 获取正在运行的应用
    running_apps = device.shell('ps | grep u0_a')
    print("运行中的应用:")
    print(running_apps)

get_app_info(device)

5. 📁 文件操作

文件传输

def file_operations(device):
    # 推送文件到设备
    device.push('local_file.txt', '/sdcard/remote_file.txt')
    
    # 从设备拉取文件
    device.pull('/sdcard/remote_file.txt', 'local_copy.txt')
    
    # 列出目录内容
    ls_result = device.shell('ls /sdcard/')
    print(f"SD卡内容: {ls_result}")
    
    # 创建目录
    device.shell('mkdir /sdcard/my_folder')

file_operations(device)

6. 🔍 高级功能

监控日志

def monitor_logs(device):
    # 获取系统日志
    logcat = device.shell('logcat -d -v time')
    print("系统日志:")
    print(logcat)
    
    # 实时监控日志(需要多线程)
    import threading
    
    def log_monitor():
        for line in device.shell('logcat -v time', stream=True):
            print(f"LOG: {line}", end='')
    
    thread = threading.Thread(target=log_monitor)
    thread.daemon = True
    thread.start()

monitor_logs(device)

输入法操作

def input_methods(device):
    # 显示软键盘
    device.shell('ime set com.android.inputmethod.latin/.LatinIME')
    
    # 隐藏软键盘
    device.shell('input keyevent 111')  # ESC键

input_methods(device)

7. 🎮 自动化脚本示例

简单的自动化流程

def automate_app(device, app_package, app_activity):
    """自动化APP操作示例"""
    
    # 1. 启动APP
    device.shell(f'am start -n {app_package}/{app_activity}')
    time.sleep(3)
    
    # 2. 执行一系列操作
    operations = [
        ('tap', 100, 200),      # 点击某个按钮
        ('text', '搜索内容'),    # 输入文本
        ('swipe', 500, 1500, 500, 500),  # 滑动
        ('keyevent', 4),        # 返回
    ]
    
    for op in operations:
        if op[0] == 'tap':
            device.shell(f'input tap {op[1]} {op[2]}')
        elif op[0] == 'text':
            device.shell(f'input text "{op[1]}"')
        elif op[0] == 'swipe':
            device.shell(f'input swipe {op[1]} {op[2]} {op[3]} {op[4]}')
        elif op[0] == 'keyevent':
            device.shell(f'input keyevent {op[1]}')
        
        time.sleep(1)

# 使用示例
automate_app(device, 'com.tencent.mm', '.ui.LauncherUI')

8. 🛠️ 错误处理

完善的错误处理

from ppadb.client import Client as AdbClient
import time

class AndroidController:
    def __init__(self):
        self.client = None
        self.device = None
        self.connect()
    
    def connect(self, max_retries=3):
        """连接设备,支持重试"""
        for attempt in range(max_retries):
            try:
                self.client = AdbClient(host="127.0.0.1", port=5037)
                devices = self.client.devices()
                
                if not devices:
                    print("等待设备连接...")
                    time.sleep(2)
                    continue
                
                self.device = devices[0]
                print(f"成功连接到设备: {self.device.serial}")
                return True
                
            except Exception as e:
                print(f"连接失败,尝试 {attempt + 1}/{max_retries}: {e}")
                time.sleep(2)
        
        print("无法连接到设备")
        return False
    
    def safe_shell(self, command, timeout=10):
        """安全的shell命令执行"""
        try:
            result = self.device.shell(command, timeout=timeout)
            return result.strip()
        except Exception as e:
            print(f"命令执行失败: {command}, 错误: {e}")
            return None

# 使用示例
controller = AndroidController()
if controller.device:
    result = controller.safe_shell('echo "Hello ADB"')
    print(result)

9. 📊 实际应用案例

数据采集脚本

def collect_app_data(device, package_name):
    """采集APP数据"""
    
    # 启动APP
    device.shell(f'monkey -p {package_name} -c android.intent.category.LAUNCHER 1')
    time.sleep(5)
    
    # 执行数据采集操作
    data_points = []
    
    # 采集屏幕信息
    screenshot = device.screencap()
    with open(f'screenshot_{int(time.time())}.png', 'wb') as f:
        f.write(screenshot)
    
    # 采集当前活动
    activity = device.shell('dumpsys activity top | grep ACTIVITY')
    data_points.append(activity)
    
    # 采集网络状态
    network = device.shell('dumpsys connectivity')
    data_points.append(network)
    
    return data_points

# 使用示例
data = collect_app_data(device, 'com.example.targetapp')

10. ⚠️ 注意事项

权限和配置

  1. 开启USB调试:在开发者选项中启用
  2. 授权电脑:首次连接时在手机上授权
  3. 网络ADB:可通过WiFi连接 adb tcpip 5555

常见问题解决

# 检查设备连接状态
def check_connection(device):
    try:
        state = device.get_state()
        return state == 'device'
    except:
        return False

# 重启ADB服务
import subprocess
subprocess.run(['adb', 'kill-server'])
subprocess.run(['adb', 'start-server'])

这个教程涵盖了 python-ppadb 的主要功能,你可以根据具体需求选择合适的操作来实现 Android 设备的自动化控制。