-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
433 lines (362 loc) · 16.5 KB
/
main.py
File metadata and controls
433 lines (362 loc) · 16.5 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
import os
import platform
import re
import subprocess
import xml.etree.ElementTree as ET
import shutil
import tempfile
import uuid
import json
# ======================== 配置区 (只需修改这里) ========================
APK_INPUT_PATH = "template.apk" # 待修改的原始APK路径
CONFIG_FILE_PATH = "config.json" # 配置文件路径
OUTPUT_DIR = "output" # 输出文件夹路径
AS_KEYSTORE_PASS = "android"
AS_KEY_ALIAS = "androiddebugkey"
AS_KEY_PASS = "android"
AS_DNAME = "CN=Android Debug, OU=Android, O=Android, L=Mountain View, ST=California, C=US"
def get_system_sep():
"""获取系统路径分隔符"""
return "\\" if platform.system() == "Windows" else "/"
# =====================================================================
def load_configs():
"""从JSON文件加载配置"""
if not os.path.exists(CONFIG_FILE_PATH):
# 如果不存在,生成一个示例文件并退出
example_configs = [
["com.xunmeng.pinduoduo", "NoPDD", 9999, "9999.0.0"],
["com.baidu.searchbox", "NoBaidu", 9999, "9999.0.0"]
]
with open(CONFIG_FILE_PATH, 'w', encoding='utf-8') as f:
json.dump(example_configs, f, ensure_ascii=False, indent=4)
print(f"⚠️ 未找到配置文件,已在当前目录生成默认配置文件:{CONFIG_FILE_PATH}")
print("请按需修改 json 配置文件后,重新运行本程序!")
exit(1)
try:
with open(CONFIG_FILE_PATH, 'r', encoding='utf-8') as f:
configs = json.load(f)
return configs
except Exception as e:
print(f"❌ 读取配置文件 {CONFIG_FILE_PATH} 失败:{e}")
exit(1)
def get_jdk_version():
"""获取JDK版本(适配8/11/17+)"""
try:
result = subprocess.run(
["java", "-version"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True
)
version_output = result.stdout
# 匹配JDK版本(如 1.8.0_301、11.0.18、17.0.9)
version_match = re.search(r'version "(\d+(\.\d+)*)"', version_output)
if version_match:
version_str = version_match.group(1)
# 处理JDK8的格式(1.8.x → 8)
if version_str.startswith("1.8."):
return 8
# 处理JDK11+/17+
main_version = int(version_str.split('.')[0])
return main_version
except Exception as e:
print(f"⚠️ 检测JDK版本失败:{e},默认按JDK11+处理")
return 11 # 默认按新版JDK处理
def check_dependencies():
"""检查必需的工具是否安装"""
print(os.environ["PATH"])
required_tools = ["apktool", "keytool", "jarsigner", "zipalign"]
missing_tools = []
for tool in required_tools:
try:
subprocess.run([tool], capture_output=True, check=True)
except FileNotFoundError:
print(f"❌ 工具未找到:{tool}")
missing_tools.append(tool)
except subprocess.CalledProcessError as e:
pass
if missing_tools:
print(f"❌ 缺少必需工具:{', '.join(missing_tools)}")
print("请确保:")
print("1. apktool 已配置到环境变量(https://github.com/iBotPeaches/Apktool)")
print("2. JDK 已安装(keytool/jarsigner 自带)")
print("3. zipalign 在 Android SDK build-tools 目录下,并配置到环境变量")
exit(1)
print("✅ 所有依赖工具检查通过")
return get_jdk_version()
def generate_as_style_keystore(jdk_version):
"""生成和Android Studio完全一致的Debug签名文件(适配JDK版本)"""
# 生成临时keystore路径
temp_keystore = os.path.join(tempfile.gettempdir(), f"as_debug_{os.getpid()}.keystore")
# 构建keytool命令(适配JDK8和JDK11+)
keytool_base_cmd = (
f'keytool -genkeypair -v '
f'-keystore "{temp_keystore}" '
f'-alias {AS_KEY_ALIAS} '
f'-keyalg RSA '
f'-keysize 2048 '
f'-validity 10000 '
f'-storepass {AS_KEYSTORE_PASS} '
f'-keypass {AS_KEY_PASS} '
f'-dname "{AS_DNAME}" '
f'-noprompt '
f'-sigalg SHA256withRSA'
)
# JDK8需要加-digestalg,JDK11+移除该参数
if jdk_version == 8:
keytool_cmd = keytool_base_cmd + ' -digestalg SHA-256'
else:
keytool_cmd = keytool_base_cmd
try:
subprocess.run(keytool_cmd, shell=True, check=True, capture_output=True, text=True)
print(f"✅ 生成AS标准签名文件:{temp_keystore}(适配JDK{jdk_version})")
return temp_keystore
except subprocess.CalledProcessError as e:
print(f"❌ 生成签名失败:{e.stdout if e.stdout else e.stderr}")
exit(1)
def run_command(cmd, desc):
"""执行系统命令并处理异常"""
print(f"🔧 {desc}")
try:
result = subprocess.run(cmd, shell=True, check=True, capture_output=True, text=True)
if result.stdout:
print(f"输出:{result.stdout[:200]}...") # 只打印前200字符避免刷屏
return True
except subprocess.CalledProcessError as e:
print(f"❌ {desc}失败:{e.stderr}")
return False
def modify_manifest(decode_dir, new_package_name, new_version_code, new_version_name):
"""修改AndroidManifest.xml(包名、版本号)"""
manifest_path = os.path.join(decode_dir, "AndroidManifest.xml")
if not os.path.exists(manifest_path):
print(f"❌ 未找到AndroidManifest.xml:{manifest_path}")
return None
# 注册Android命名空间,防止xml解析异常
ET.register_namespace('android', 'http://schemas.android.com/apk/res/android')
tree = ET.parse(manifest_path)
root = tree.getroot()
# 1. 修改包名
old_package = root.attrib.get('package')
if not old_package:
print("❌ 未读取到原始包名")
return None
root.set('package', new_package_name)
print(f"📦 包名修改:{old_package} → {new_package_name}")
# 2. 修改versionCode和versionName
ns = {'android': 'http://schemas.android.com/apk/res/android'}
root.set(f"{{{ns['android']}}}versionCode", str(new_version_code))
root.set(f"{{{ns['android']}}}versionName", new_version_name)
print(f"🔢 版本信息修改:versionCode={new_version_code}, versionName={new_version_name}")
# 保存修改
tree.write(manifest_path, encoding='utf-8', xml_declaration=True)
return old_package
def modify_app_name(decode_dir, new_app_name):
"""修改应用名称(优先strings.xml,其次Manifest)"""
# 优先修改res/values/strings.xml中的app_name
strings_paths = [
os.path.join(decode_dir, "res", "values", "strings.xml"),
os.path.join(decode_dir, "res", "values-zh-rCN", "strings.xml") # 中文适配
]
for strings_path in strings_paths:
if os.path.exists(strings_path):
tree = ET.parse(strings_path)
root = tree.getroot()
found = False
for child in root:
if child.tag == 'string' and child.attrib.get('name') == 'app_name':
child.text = new_app_name
found = True
break
if found:
tree.write(strings_path, encoding='utf-8', xml_declaration=True)
print(f"📝 应用名称修改成功:{new_app_name}(路径:{strings_path})")
return
# 如果没找到app_name,尝试修改Manifest的label
manifest_path = os.path.join(decode_dir, "AndroidManifest.xml")
tree = ET.parse(manifest_path)
root = tree.getroot()
ns = {'android': 'http://schemas.android.com/apk/res/android'}
for application in root.findall('application', ns):
application.set(f"{{{ns['android']}}}label", new_app_name)
tree.write(manifest_path, encoding='utf-8', xml_declaration=True)
print(f"📝 应用名称修改(Manifest):{new_app_name}")
return
print("⚠️ 未找到应用名称配置项,可能已混淆")
def replace_package_in_smali(decode_dir, old_package, new_package):
"""批量替换Smali/XML中的包名引用"""
old_package_path = old_package.replace('.', '/')
new_package_path = new_package.replace('.', '/')
print(f"🔍 开始替换Smali中的包名引用:{old_package_path} → {new_package_path}")
# 遍历所有文件
file_count = 0
for root_dir, _, files in os.walk(decode_dir):
for file in files:
if file.endswith(('.smali', '.xml', '.txt')):
file_path = os.path.join(root_dir, file)
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
# 替换包名(两种格式:点分隔和路径分隔)
new_content = content.replace(old_package, new_package).replace(old_package_path, new_package_path)
if new_content != content:
with open(file_path, 'w', encoding='utf-8') as f:
f.write(new_content)
file_count += 1
except Exception as e:
continue # 忽略无法读取的文件
print(f"✅ 共替换 {file_count} 个文件中的包名引用")
# 重命名Smali目录结构
smali_dir = os.path.join(decode_dir, 'smali')
old_smali_path = os.path.join(smali_dir, old_package_path)
new_smali_path = os.path.join(smali_dir, new_package_path)
if os.path.exists(old_smali_path):
# 创建新的目录结构
os.makedirs(new_smali_path, exist_ok=True)
# 移动所有文件
for file in os.listdir(old_smali_path):
old_file = os.path.join(old_smali_path, file)
new_file = os.path.join(new_smali_path, file)
if os.path.isfile(old_file):
shutil.move(old_file, new_file)
# 删除旧的目录结构
shutil.rmtree(old_smali_path)
print(f"✅ 重命名Smali目录结构:{old_smali_path} → {new_smali_path}")
def process_apk_config(config):
"""处理单个APK配置"""
new_package_name, new_app_name, new_version_code, new_version_name = config
# 修改:将输出 APK 的路径指向 OUTPUT_DIR 目录
output_apk_name = os.path.join(OUTPUT_DIR, f"{new_package_name}.apk")
# 1. 检查依赖并获取JDK版本
jdk_version = check_dependencies()
# 2. 生成和AS一致的签名文件(适配JDK版本)
temp_keystore = generate_as_style_keystore(jdk_version)
# 3. 定义临时文件路径
base_name = os.path.splitext(os.path.basename(APK_INPUT_PATH))[0]
decode_dir = f"{base_name}_decoded_temp_{uuid.uuid4().hex[:8]}"
unsigned_apk = f"temp_unsigned_{uuid.uuid4().hex[:8]}.apk"
aligned_apk = f"temp_aligned_{uuid.uuid4().hex[:8]}.apk"
signed_apk = f"temp_signed_{uuid.uuid4().hex[:8]}.apk"
try:
# 4. 反编译APK(静默模式,减少输出)
if not run_command(f"apktool d \"{APK_INPUT_PATH}\" -o \"{decode_dir}\" -f -q", "反编译APK"):
return False
# 5. 修改Manifest(包名、版本号)
old_package = modify_manifest(decode_dir, new_package_name, new_version_code, new_version_name)
if not old_package:
return False
# 6. 修改应用名称
modify_app_name(decode_dir, new_app_name)
# 7. 替换Smali中的包名引用
replace_package_in_smali(decode_dir, old_package, new_package_name)
# 8. 回编译APK(生成未签名包)
if not run_command(f"apktool b \"{decode_dir}\" -o \"{unsigned_apk}\" -f -q", "回编译APK"):
return False
# 9. 第一步:zipalign优化(AS流程:先对齐再签名)
if not run_command(f"zipalign -v -p 4 \"{unsigned_apk}\" \"{aligned_apk}\"", "zipalign优化APK"):
return False
# 10. 第二步:签名(使用apksigner,支持v2/v3签名方案)
# 检查apksigner是否存在
try:
subprocess.run(["apksigner"], capture_output=True, check=True)
use_apksigner = True
except (FileNotFoundError, subprocess.CalledProcessError):
use_apksigner = False
print("⚠️ apksigner未找到,使用jarsigner签名(可能不支持v2签名)")
if use_apksigner:
# 使用apksigner签名(支持v2/v3签名方案)
sign_cmd = (
f'apksigner sign '
f'--ks \"{temp_keystore}\" '
f'--ks-pass pass:{AS_KEYSTORE_PASS} '
f'--key-pass pass:{AS_KEY_PASS} '
f'--ks-key-alias {AS_KEY_ALIAS} '
f'--out \"{signed_apk}\" '
f'\"{aligned_apk}\"'
)
if not run_command(sign_cmd, "使用apksigner签名APK(支持v2/v3)"):
return False
# 验证签名
run_command(f"apksigner verify --verbose '{signed_apk}'", "验证APK签名")
else:
# 回退到jarsigner签名
sign_base_cmd = (
f'jarsigner -verbose '
f'-sigalg SHA256withRSA ' # AS Release默认算法
f'-keystore \"{temp_keystore}\" '
f'-storepass {AS_KEYSTORE_PASS} '
f'-keypass {AS_KEY_PASS} '
f'-signedjar \"{signed_apk}\" '
f'\"{aligned_apk}\" {AS_KEY_ALIAS}'
)
# JDK8需要加-digestalg,JDK11+不需要
if jdk_version == 8:
sign_cmd = sign_base_cmd.replace('-sigalg', '-digestalg SHA-256 -sigalg')
else:
sign_cmd = sign_base_cmd
if not run_command(sign_cmd, "使用jarsigner签名APK"):
return False
# 验证签名
run_command(f"jarsigner -verify -verbose '{signed_apk}'", "验证APK签名")
# 12. 重命名为最终输出文件
if os.path.exists(output_apk_name):
os.remove(output_apk_name)
shutil.move(signed_apk, output_apk_name)
# 输出结果
print("\n🎉 全部操作完成!")
print(f"📤 最终Release APK路径:{os.path.abspath(output_apk_name)}")
print("\n💡 安装说明:")
print(" 1. 该APK使用和Android Studio完全一致的Debug签名,可直接安装")
print(" 2. 若提示未知来源,仅需在手机端开启「允许未知来源安装」即可")
print(" 3. 无需卸载AS打包的同包名应用(签名一致,可覆盖安装)")
return True
finally:
# 清理临时文件(避免残留)
print("\n🧹 清理临时文件...")
# 清理反编译目录
if os.path.exists(decode_dir):
shutil.rmtree(decode_dir, ignore_errors=True)
# 临时签名文件
if os.path.exists(temp_keystore):
os.remove(temp_keystore)
# 临时APK文件
for temp_file in [unsigned_apk, aligned_apk, signed_apk]:
if os.path.exists(temp_file):
os.remove(temp_file)
# 清理对应的.idsig文件
idsig_file = temp_file + ".idsig"
if os.path.exists(idsig_file):
os.remove(idsig_file)
print("✅ 临时文件清理完成")
def main():
"""主函数,处理所有APK配置"""
# 确保输出目录存在
if not os.path.exists(OUTPUT_DIR):
os.makedirs(OUTPUT_DIR)
# 从配置文件加载数据
apk_configs = load_configs()
if not apk_configs:
print("❌ 未在配置文件中读取到任何APK配置数据")
exit(1)
print(f"共配置 {len(apk_configs)} 个APK")
for i, config in enumerate(apk_configs, 1):
# 支持 JSON 数组格式直接解包
new_package_name, new_app_name, new_version_code, new_version_name = config
print(f"\n🚀 开始处理第 {i} 个APK:")
print(f" 包名:{new_package_name}")
print(f" 应用名称:{new_app_name}")
print(f" 版本Code:{new_version_code}")
print(f" 版本号:{new_version_name}")
if process_apk_config(config):
print(f"✅ 第 {i} 个APK处理成功")
else:
print(f"❌ 第 {i} 个APK处理失败")
print("\n🎊 所有APK处理完成!")
if __name__ == "__main__":
# 检查输入APK是否存在
if not os.path.exists(APK_INPUT_PATH):
print(f"❌ 未找到输入APK文件:{APK_INPUT_PATH}")
exit(1)
print("=====================================")
print(" APK 自动修改工具(Release版)")
print("=====================================")
main()