应用场景
如果需要批量分析apk以及每个apk文件中的classes.dex 文件。怎么提取出它们?将apk改后缀名变为.zip文件,之后在解压,提取出每个apk文件中的classes.dex文件,这是一个可行的方案。但是中间解压大量的apk文件会占据我们的大量磁盘存储空间,怎么在不解压文件的情况下提取出dex文件?在这里使用python自带的zipfile类,可以轻松的解决这个问题。
代码实现:
#!/usr/bin/env python
# coding=utf-8
'''
@author : Chicho
@version : 1.0
@ date : Jan 4, 2015 01:54
@function : extract dexs file from apk files
* create a new directory to store all dex files
@running : python dex_extract.py
'''
import os
import zipfile
path="/home/chicho/test/test/" # this is apk files' store path
dex_path="/home/chicho/test/test/dex/" # a directory store dex files
apklist = os.listdir(path) # get all the names of apps
if not os.path.exists(dex_path):
os.makedirs(dex_path)
for APK in apklist:
portion = os.path.splitext(APK)
if portion[1] == ".apk":
newname = portion[0] + ".zip" # change them into zip file to extract dex files
os.rename(APK,newname)
if APK.endswith(".zip"):
apkname = portion[0]
zip_apk_path = os.path.join(path,APK) # get the zip files
z = zipfile.ZipFile(zip_apk_path, 'r') # read zip files
for filename in z.namelist():
if filename.endswith(".dex"):
dexfilename = apkname + ".dex"
dexfilepath = os.path.join(dex_path, dexfilename)
f = open(dexfilepath, 'w+') # eq: cp classes.dex dexfilepath
f.write(z.read(filename))
print "all work done!"
利用这个方法还可以从apk文件中批量的提取出其他文件。比如说so文件等。
转载注明出处:http://blog.csdn.net/chichoxian/article/details/42382695