Python调用aapt解析apk教程(避坑指南)

今天尝试用python调用aapt解析apk,获取包名等信息,使用popen调用aapt一直遇到编码之类的错误,找了许多解决办法都不行,然后又用Popen尝试调用aapt解析,还是遇到了编码问题,尝试使用decode("utf8","ignore")这种方式解码,完美解决了编码的问题。代码如下:

其中aapt因为我是添加了环境变量的原因,可以直接以"aapt"在命令行启动,没添加环境变量的,可以输入:"路径+aapt.exe"的方式调用aapt来解析apk。

# -*- coding: utf-8 -*-
import re
import subprocess
import os

class ApkInfo:
    def __init__(self, apk_path):
        self.apkPath = apk_path
        #self.aapt_path = self.get_aapt()
    def get_apk_base_info(self):
        p = subprocess.Popen("aapt" + " dump badging %s" % self.apkPath, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             stdin=subprocess.PIPE, shell=True)
        (output, err) = p.communicate()
        match = re.compile("package: name='(\S+)'").match(output.decode("utf8","ignore"))
        if not match:
            raise Exception("can't get packageinfo")
        package_name = match.group(1)
        return package_name

    def get_apk_activity(self):
        p = subprocess.Popen("aapt" + " dump badging %s" % self.apkPath, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             stdin=subprocess.PIPE, shell=True)
        (output, err) = p.communicate()
        match = re.compile("launchable-activity: name='(\S+)'").search(output.decode("utf8","ignore"))
        if match is not None:
            return match.group(1)

    def get_apk_sdkVersion(self):
        p = subprocess.Popen("aapt" + " dump badging %s" % self.apkPath, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             stdin=subprocess.PIPE, shell=True)
        (output, err) = p.communicate()
        match = re.compile("sdkVersion:'(\S+)'").search(output.decode("utf8","ignore"))
        return match.group(1)

    def get_apk_targetSdkVersion(self):
        p = subprocess.Popen("aapt" + " dump badging %s" % self.apkPath, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             stdin=subprocess.PIPE, shell=True)
        (output, err) = p.communicate()
        match = re.compile("targetSdkVersion:'(\S+)'").search(output.decode("utf8","ignore"))
        return match.group(1)

if __name__ == '__main__':
    apk_info = ApkInfo(r"D:\pythontest\one\Blued.apk")
    print("Activity:%s"%apk_info.get_apk_activity())
    print("apkName:%s"%apk_info.get_apk_base_info())
    print("sdkVersion:%s"%apk_info.get_apk_sdkVersion())
    print("targetSdkVersion:%s"%apk_info.get_apk_targetSdkVersion())

你可能感兴趣的:(编程,安卓逆向,python,开发语言)