Android USB调试 转WIFI无线调试

import subprocess,re,time,sys
try:
    import uiautomator2 as u2
except ImportError:
    subprocess.run([sys.executable, '-m', 'pip', 'install', 'uiautomator2'], check=True)
    import uiautomator2 as u2

class WiFiDebugger:
    def __init__(self):
        self.device_ip = None
        self.port = 5555
    
    def run_adb_command(self, command):
        try:
            result = subprocess.run(f"adb {command}", shell=True, capture_output=True, text=True, timeout=10)
            return result.stdout.strip(), result.stderr.strip(), result.returncode
        except Exception as e:
            return "", str(e), 1
    
    def check_device_connected(self):
        stdout, stderr, code = self.run_adb_command("devices")
        if code != 0:
            print(f"错误: {stderr}")
            return False, []
        devices = [line.split('\t')[0] for line in stdout.split('\n')[1:] if line.strip() and 'device' in line]
        return len(devices) > 0, devices
    
    def get_device_ip(self):
        commands = ["shell ifconfig wlan0", "shell ip addr show wlan0", "shell ifconfig", "shell ip addr show"]
        for cmd in commands:
            stdout, _, _ = self.run_adb_command(cmd)
            if stdout:
                ip_match = re.search(r'inet\s*(?:addr:)?\s*(\d+\.\d+\.\d+\.\d+)', stdout)
                if ip_match:
                    self.device_ip = ip_match.group(1)
                    return self.device_ip
        try:
            user_input = input("请输入设备IP地址: ")
            if re.match(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$', user_input):
                self.device_ip = user_input
                return user_input
        except KeyboardInterrupt:
            pass
        return None
    
    def setup_wireless_debugging(self):
        connected, _ = self.check_device_connected()
        if not connected:
            return False, "未检测到设备"
        
        ip = self.get_device_ip()
        if not ip:
            return False, "无法获取设备IP"
        
        self.run_adb_command("kill-server")
        time.sleep(1)
        self.run_adb_command("start-server")
        
        _, stderr, code = self.run_adb_command(f"tcpip {self.port}")
        if code != 0:
            return False, f"启用TCP/IP失败"
        
        time.sleep(2)
        for _ in range(3):
            stdout, _, code = self.run_adb_command(f"connect {ip}:{self.port}")
            if code == 0 and 'connected' in stdout:
                return True, f"成功连接到 {ip}:{self.port}"
            time.sleep(1)
        return False, "连接失败"
    
    def verify_wireless_connection(self):
        stdout, _, code = self.run_adb_command("devices")
        if code != 0:
            return False, "无法获取设备列表"
        wireless_devices = [line.split('\t')[0] for line in stdout.split('\n')[1:] if line.strip() and ':' in line and 'device' in line]
        return bool(wireless_devices), f"设备: {', '.join(wireless_devices)}" if wireless_devices else "无线连接失败"
    
    def open_xiaohongshu(self):
        stdout, _, code = self.run_adb_command("devices")
        if code != 0:
            return False, "无法获取设备列表"
        
        devices = [line.split('\t')[0] for line in stdout.split('\n')[1:] if line.strip() and 'device' in line]
        if not devices:
            return False, "未检测到设备"
        
        try:
            d = u2.connect(devices[0])
            d.app_start('com.xingin.xhs')
            time.sleep(5)
            return True, "小红书已打开"
        except:
            adb_stdout, adb_stderr, adb_code = self.run_adb_command("shell am start -n com.xingin.xhs/.activity.SplashActivity")
            if adb_code == 0:
                time.sleep(5)
                return True, "使用ADB打开小红书"
            return False, "无法打开小红书"


def main():
    debugger = WiFiDebugger()
    
    already_wireless, message = debugger.verify_wireless_connection()
    if already_wireless:
        print(f"已连接: {message}")
        success, msg = debugger.open_xiaohongshu()
        print(f"✓ {msg}" if success else f"✗ {msg}")
        return
    
    connected, devices = debugger.check_device_connected()
    if connected:
        ip = debugger.get_device_ip()
        if ip:
            success, msg = debugger.setup_wireless_debugging()
            if success:
                print(f"✓ {msg}")
                time.sleep(2)
                success, msg = debugger.verify_wireless_connection()
                if success:
                    print(f"✓ {msg}")
                    success, msg = debugger.open_xiaohongshu()
                    print(f"✓ {msg}" if success else f"✗ {msg}")


if __name__ == "__main__":
    main()
已连接: 设备: 192.168.101.28:5555
✓ 小红书已打开
posted @ 2025-11-15 13:38  zhangdingqu  阅读(4)  评论(0)    收藏  举报