当前位置: 首页 > article >正文

python+adb

#!/usr/bin/python env
# -*- coding: utf-8 -*-
import os
import sys
import subprocess
from time import sleep

import logging
logging.basicConfig(level=logging.DEBUG)
class ScreenCapture():

    def get_screen_size(self):
        """获取手机分辨率"""

        action = subprocess.Popen(['adb', 'shell', 'wm', 'size'], stdout=subprocess.PIPE)
        result = action.stdout.read()
        _, size = result.decode().split(':')
        self.width,self.height = size.strip().split('x')
        print(f'获取到手机分辨率为:{self.width},{self.height}')  # 1080,2436

        # return int(width), int(height)
        # print(f"result是{result}")
        # print(result.decode())
        # ss=result.decode().split(':')
        # aaa=ss[1].strip()

        self.x1=int(self.width)/2

        self.x2=int(self.width)/2
        self.y1=int(self.height)/4
        self.y2=int(self.height)/1.5
        print(f"x1是{self.x1},x2是{self.x2},y1是{self.y1},y2是{self.y2}")

    @staticmethod
    def show_menu():

        print("========================================================== ")
        print("||      <1>远程连接设备       <2>向左滑动       <3>向右滑动    ||\n")
        print("||      <4>向上滑动           <5>向下滑动       <6>跑Monkey    ||\n")
        print("||      <7>单场景chrome测试   <8>               <9>          ||\n")
        print(" ========================================================= \n")
        # subprocess.Popen(
        #     ['adb', 'shell', 'input', 'swipe', str(self.x1), str(self.y1), str(self.x1), str(self.y2), '500'],
        #     stdout=subprocess.PIPE)
        # return int(width), int(height)
        # self.ScreenCapture(y1, y2, height)
        # subprocess.Popen(['adb', 'shell', 'input', 'swipe', str(self.x1), str(self.y1), str(self.x1), str(self.y2), '500'],stdout=subprocess.PIPE)

    def up_swipe(self):
        up_num = int(input("向上滑动多少次,用数字替代:"))
        interval_time = int(input("输入间隔的时间:"))
        for i in range(up_num):
            subprocess.Popen(
                ['adb', 'shell', 'input', 'swipe', str(self.x1), str(self.y1), str(self.x1), str(self.y2), '500'],
                stdout=subprocess.PIPE)
            print("第{}次滑动".format(i + 1))
            sleep(interval_time)
        print("滑动结束,退出。。")
        sys.exit()

    def down_swipe(self):
        up_num = int(input("向下滑动多少次,用数字替代:"))
        interval_time=int(input("输入间隔的时间:"))
        for i in range(up_num):
            subprocess.Popen(
                ['adb', '-s',{self.ip_input},'shell', 'input', 'swipe', str(self.x1), str(self.y2), str(self.x1), str(self.y1), '500'],
                stdout=subprocess.PIPE)
            sleep(interval_time)
        print("滑动结束,退出。。")
        sys.exit()

    def left_swipe(self):
        x1=str(int(self.width)*0.8)
        x2=str(int(self.width)*0.2)
        y1=str(int(self.height)*0.5)
        print(x1)
        print("滑动开始前")
        up_num = int(input("向左滑动多少次,用数字替代:"))
        for i in range(up_num):

            subprocess.Popen(
                ['adb', 'shell', 'input', 'swipe', x2, y1, x1, y1, '500'],
                stdout=subprocess.PIPE)
            print("第{}次滑动".format(i+1))
            sleep(3)
        print("滑动结束,退出。。")
        sys.exit()

    def right_swipe(self):
        x1 = str(int(self.width) * 0.8)
        x2 = str(int(self.width) * 0.2)
        y1 = str(int(self.height) * 0.5)
        print(x1)
        print("滑动开始前")
        up_num = int(input("向左滑动多少次,用数字替代:"))
        for i in range(up_num):
            subprocess.Popen(
                ['adb', 'shell', 'input', 'swipe', x1, y1, x2, y1, '300'],
                stdout=subprocess.PIPE)
            print("第{}次滑动".format(i + 1))
            sleep(3)
        print("滑动结束,退出。。")
        sys.exit()

    def get_device_id(self):
        self.adb_devices=os.popen("adb devices").read()
        self.adb_output = self.adb_devices.split("List of devices attached\n", 1)[1]
        lines = self.adb_output.strip().split('\n')
        # 遍历每一行,提取设备号
        self.device_ids = []
        for line in lines:
            # 如果行不是空的,并且包含"device",则提取设备号
            if line and "device" in line:
                device_id, _ = line.split(maxsplit=1)  # maxsplit=1确保只分割一次
                self.device_ids.append(device_id.strip())
                self.device_ids=self.device_ids[0]
        logging.info(f'device_ids号是: {self.device_ids}')
        return self.device_ids

    def adb_connect(self, device_ip):
        adb_command = ['adb', 'connect', f'{device_ip}:5555']
        try:
            subprocess.Popen("adb tcpip 5555", stdout=subprocess.PIPE)
            # subprocess.check_call("adb -s {} tcp ip 5555", stdout=subprocess.PIPE)  #
            output = subprocess.check_output(adb_command, shell=True, stderr=subprocess.STDOUT)
            print(f"Connected to device at {device_ip}:5555")
            print(output.decode())
        except:
            print(f"Failed to connect to device at {device_ip}:5555", "请检查错误")
            sys.exit()

    def get_and_connect_ip(self):
        # 将原本在if num == 1下的代码移到这个方法中adb de
        ip_command = f'adb -s {self.get_device_id()} shell ip route'
        result = subprocess.check_output(ip_command, shell=True, text=True)
        # 提取 IP 地址(这里假设IP地址是route命令输出的最后一行最后一个元素)
        ip_address = result.strip('\n').strip(' ').split(' ')[-1]
        print(f"Detected IP address: {ip_address},远程连接需拔掉USB设备")

        self.ip_input = input("输入你的IP地址(或者按回车使用检测到的IP):")
        if not self.ip_input:
            self.ip_input = ip_address  # 如果用户没有输入,则使用检测到的IP
        self.adb_connect(self.ip_input)

        self.run() # 连接后重新显示菜单

    def chrome_switch(self):
        os.system("adb devices")
        while True:
            os.system(f'adb -s {self.ip_input} shell am start -a android.intent.action.VIEW -d "http://baidu.com"')
            sleep(5)
            for i in range(20):
                subprocess.Popen(
                    ['adb', '-s',self.ip_input,'shell', 'input', 'swipe', str(self.x1), str(self.y2),
                     str(self.x1), str(self.y1), '500'],
                    stdout=subprocess.PIPE)
                sleep(3)
            os.system(f'adb -s {self.ip_input} shell am start -a android.intent.action.VIEW -d "http://163.com"')
            sleep(5)
            for i in range(20):
                subprocess.Popen(
                    ['adb', '-s', self.ip_input, 'shell', 'input', 'swipe', str(self.x1), str(self.y2),
                     str(self.x1),
                     str(self.y1), '500'],
                    stdout=subprocess.PIPE)
                sleep(3)

    #def adb_connect(self, ip_input):
        # 假设此方法用于连接ADB
        #print(f"Connecting to ADB with IP: {ip_input}")
        # ... 省略实际连接ADB的代码

    def run(self):
        ScreenCapture.show_menu()  # 假设ScreenCapture是另一个模块或类,并且有show_menu方法
        num = int(input("输入你要选择的功能,用数字替代:"))

        # 定义动作字典
        action_mapping = {
            1: self.get_and_connect_ip,
            2: self.left_swipe,
            3: self.right_swipe,
            4: self.up_swipe,
            5: self.down_swipe,
            7: self.chrome_switch,
        }

        # 检查输入是否在映射中
        if num in action_mapping:
            action_mapping[num]()
        elif num == 6:
            # 对于特定的num值,可以直接处理
            pass
        else:
            print("\n\t输入有误!!!\t\n")
            self.run()  # 递归调用,重新显示菜单和接收输入


if __name__ == '__main__':
    ScreenCapture().run()

http://www.kler.cn/news/306063.html

相关文章:

  • IP池对数据爬取工作的帮助
  • 【Android Studio】使用雷电模拟器调试
  • Acrobat XI 安装教程
  • 后端入门 (JQuery基础) 01
  • 3.1 通信协议
  • 多线程进阶
  • 随想录笔记-二叉树练习题
  • 服务器出现访问卡慢的原因有哪些
  • Nature Communications 可远程操控食欲的口服软体机器人
  • gogps 利用广播星历解算卫星位置matlab函数satellite_orbits详细注解版
  • 【Android 13源码分析】WindowContainer窗口层级-2-构建流程
  • 详细介绍 Servlet 基本概念——以餐厅服务员为喻
  • Linux下write函数
  • PG表空间
  • Android命令行查看CPU频率和温度
  • 鲸天科技外卖会员卡系统更专业
  • Spring源码(12)-- Aop源码
  • 【Linux 从基础到进阶】自动化部署工具(Jenkins、GitLab CI/CD)
  • jdk知识
  • Excel数据清洗工具:提高数据处理效率的利器
  • verilog运算符优先级
  • TCP/IP网络编程概念及Java实现TCP/IP通讯Demo
  • 论文速递!Auto-CNN-LSTM!新的锂离子电池(LIB)剩余寿命预测方法
  • WEB打点
  • Metacritic 网站中的游戏开发者和类型信息爬取
  • OpenCV-轮廓检测
  • 《深度学习》PyTorch 手写数字识别 案例解析及实现 <下>
  • 编写并运行第一个spark java程序
  • 【JavaEE】初识⽹络原理
  • 计算机毕业设计 二手闲置交易系统的设计与实现 Java实战项目 附源码+文档+视频讲解