监控python logcat关键字-LMLPHP

本文主要介绍使用Python调用ADB命令实现实时监控logcat关键字的功能

采用多进程,可同时监控多个设备,监控多个关键字。

需要配置ADB环境,具体配置就不多介绍,随便搜一下一大把,直接上代码

通过一个全局变量控制开启和关闭监控功能, INSTRUCTION 用于根据指令获取对应的方法名

import os, threading, datetime

# 获取当前文件所在目录,拼接出LOG路径
LOG_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "log")

# 配置需要监控的关键字
KEYWORDS = ["ANR ", "NullPointerException", "CRASH", "Force Closed"]

# 控制开启和关闭
STOP_LOGCAT = True

# 指令对应具体操作
INSTRUCTION = {
               "1": "filter_keywords",
               "2": "stop_filter_keywords",
               "3": "exit"
               }


def filter_keywords():
    global STOP_LOGCAT
    STOP_LOGCAT = False
    devices = get_devices()  # 先获取所有连接的设备
    print("开始监控关键字")
    for device in devices:
        t = threading.Thread(target=filter_keyword, args=(device,))
        t.start()


def stop_filter_keywords():
    global STOP_LOGCAT
    if STOP_LOGCAT:
        print("没有正在执行的任务\n")
    else:
        STOP_LOGCAT = True
        print("正在停止关键字监控\n")
登录后复制

监控关键字主函数,

def filter_keyword(device):
    print("设备%s关键字监控已开启" % str(device))
    sub = logcat(device)
    with sub:
        for line in sub.stdout: # 子进程会持续输出日志,对子进程对象.stdout进行循环读取
            for key in KEYWORDS:
                if line.decode("utf-8").find(key) != -1: # stdout输出为字节类型,需要转码
                    message = "设备:%s 检测到:%s\n" % (device, key)# 设备:192.168.56.104:5555 检测到:ANR
                    path = get_log_path("bugreport") # 根据时间创建文件夹
                    bugreport(device, path)# 拉取完整日志压缩包到创建的文件夹内
                    send_message(message) # 这里可以换成自己要做的事情,比如发送邮件或钉钉通知
            if STOP_LOGCAT:
                break
        print("设备%s关键字监控已停止" % str(device))
        sub.kill()
登录后复制

通过 subprocess.Popen 创建进程执行命令,持续输出日志到 stdout

# logcat持续输出日志
def logcat(device):
    command = "adb -s " + str(device) + " logcat -v time"
    sub = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    return sub
登录后复制

获取所有已连接设备的方法,执行"adb devices"后输出如下,通过对命令执行拿到的字符串切割获取所有设备号以列表方式存储

监控python logcat关键字-LMLPHP

# 获取所有device
def get_devices():
    command = "adb devices"
    res = os.popen(command).read()
    devices = []
    res = res.split("\n")
    for i in res:
        if i.endswith("device"):
            devices.append(i.split('\t')[0])
    return devices
登录后复制
# 打包下载所有日志到当前目录
def bugreport(device, path):
    os.chdir(path)# bugreport会下载日志到当前文件夹,所以需要先切换到已经创建的目录
    command = "adb -s " + str(device) + " bugreport"
    subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1)
    print("设备:%s 日志路径:%s" % (str(device), path))
登录后复制

以 当前文件所在目录/年/月/日 格式获取日志路径,如果不存在自动创建

# 获取日志存放路径,如果不存在则按日期创建
def get_log_path(tag):
    year = datetime.datetime.now().strftime('%Y')
    month = datetime.datetime.now().strftime('%m')
    day = datetime.datetime.now().strftime('%d')
    path = os.path.join(LOG_PATH, tag, year, month, day)
    if not os.path.exists(path):
        os.makedirs(path)
    return path
登录后复制

main函数,循环接收指令,根据接收的指令拿到方法名,并通过eval()方法执行。

def main():
    while True:
        print("-" * 100)
        print("1:开启关键字监控\n2:停止关键字监控\n3:退出")
        print("-" * 100)
        instruction = str(input("\n\n请输入要进行的操作号:\n"))
        print("-" * 100)
        while instruction not in INSTRUCTION.keys():
            instruction = str(input("\n\n输入无效,请重新输入:"))
        if int(instruction) == 9:
            exit()  # TODO 退出前需要判断是否有正在执行的monkey任务和关键字监控任务
        eval(INSTRUCTION[str(instruction)] + "()")


if __name__ == '__main__':
    main()
登录后复制

代码分段之后有点凌乱,看不明白可以把代码复制到一个文件里捋一下就明白了

以上就是监控python logcat关键字的详细内容,更多请关注Work网其它相关文章!

09-14 15:27