当前位置:   article > 正文

Python调用aapt解析apk教程(避坑指南)_python执行aapt命令

python执行aapt命令

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

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

  1. # -*- coding: utf-8 -*-
  2. import re
  3. import subprocess
  4. import os
  5. class ApkInfo:
  6. def __init__(self, apk_path):
  7. self.apkPath = apk_path
  8. #self.aapt_path = self.get_aapt()
  9. def get_apk_base_info(self):
  10. p = subprocess.Popen("aapt" + " dump badging %s" % self.apkPath, stdout=subprocess.PIPE,
  11. stderr=subprocess.PIPE,
  12. stdin=subprocess.PIPE, shell=True)
  13. (output, err) = p.communicate()
  14. match = re.compile("package: name='(\S+)'").match(output.decode("utf8","ignore"))
  15. if not match:
  16. raise Exception("can't get packageinfo")
  17. package_name = match.group(1)
  18. return package_name
  19. def get_apk_activity(self):
  20. p = subprocess.Popen("aapt" + " dump badging %s" % self.apkPath, stdout=subprocess.PIPE,
  21. stderr=subprocess.PIPE,
  22. stdin=subprocess.PIPE, shell=True)
  23. (output, err) = p.communicate()
  24. match = re.compile("launchable-activity: name='(\S+)'").search(output.decode("utf8","ignore"))
  25. if match is not None:
  26. return match.group(1)
  27. def get_apk_sdkVersion(self):
  28. p = subprocess.Popen("aapt" + " dump badging %s" % self.apkPath, stdout=subprocess.PIPE,
  29. stderr=subprocess.PIPE,
  30. stdin=subprocess.PIPE, shell=True)
  31. (output, err) = p.communicate()
  32. match = re.compile("sdkVersion:'(\S+)'").search(output.decode("utf8","ignore"))
  33. return match.group(1)
  34. def get_apk_targetSdkVersion(self):
  35. p = subprocess.Popen("aapt" + " dump badging %s" % self.apkPath, stdout=subprocess.PIPE,
  36. stderr=subprocess.PIPE,
  37. stdin=subprocess.PIPE, shell=True)
  38. (output, err) = p.communicate()
  39. match = re.compile("targetSdkVersion:'(\S+)'").search(output.decode("utf8","ignore"))
  40. return match.group(1)
  41. if __name__ == '__main__':
  42. apk_info = ApkInfo(r"D:\pythontest\one\Blued.apk")
  43. print("Activity:%s"%apk_info.get_apk_activity())
  44. print("apkName:%s"%apk_info.get_apk_base_info())
  45. print("sdkVersion:%s"%apk_info.get_apk_sdkVersion())
  46. print("targetSdkVersion:%s"%apk_info.get_apk_targetSdkVersion())

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/675666
推荐阅读
相关标签
  

闽ICP备14008679号