将jar转换为dex
# 概述
帮师兄处理数据,需要批量将jar包转换为dex,通过android sdk的d8工具进行转换,写了python代码进行批量处理。
# 具体代码
import os
import subprocess
import shutil
def convert_jars_to_dex():
prefix = r'D:\user\obfAndOriApk\jarsDir'
jars_dir = prefix + "\jars"
output_dir = prefix + "\dex"
d8_path = r"D:\AndroidStudio\sdk\build-tools\35.0.0\d8.bat"
try:
subprocess.run([d8_path, "--version"], capture_output=True, check=True)
except (subprocess.CalledProcessError, FileNotFoundError):
return
os.makedirs(output_dir, exist_ok=True)
jar_files = [os.path.join(root, f) for root, _, files in os.walk(jars_dir) for f in files if f.lower().endswith('.jar')]
if not jar_files:
return
temp_dir = "temp_dex"
os.makedirs(temp_dir, exist_ok=True)
success_count = 0
for i, jar_file in enumerate(jar_files, 1):
try:
base_name = os.path.splitext(os.path.basename(jar_file))[0]
for f in os.listdir(temp_dir):
os.remove(os.path.join(temp_dir, f))
result = subprocess.run([d8_path, jar_file, "--output", temp_dir], capture_output=True, text=True)
if result.returncode == 0:
dex_files = [f for f in os.listdir(temp_dir) if f.endswith('.dex')]
for dex_file in dex_files:
dest = os.path.join(output_dir, f"{base_name}.dex" if dex_file == "classes.dex" else dex_file)
shutil.move(os.path.join(temp_dir, dex_file), dest)
success_count += 1
except:
pass
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
if __name__ == "__main__":
convert_jars_to_dex()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47