Python EXE反编译原理:从archive到pyc的提取过程
使用 pyinstxtractor.py 提取 .exe 中的 archive ,再用 uncompyle6 或 decompyle3 还原 .pyc 源码。

提取 archive 结构
pyinstaller 打包的 .exe 本质是包含 Python 解释器和压缩数据的自解压包。运行 python pyinstxtractor.py target.exe 可解析头部并导出 target.bin 和 shared.lib。

该工具会扫描文件末尾的标记,定位 archive 起始位置。提取出的 bin 文件通常经过 zlib 压缩,需进一步处理才能获取内部的 .pyc 模块列表。
反编译 pyc 模块
将上一步生成的 bin 文件解压缩后,会得到多个 .pyc 文件。安装 uncompyle6 后,对每个 .pyc 执行反编译命令即可恢复源代码。

import sys
import os
import struct
import zlib
def extract_archive(exe_path, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
with open(exe_path, 'rb') as f:
data = f.read()
# 查找 PYZ 标记
idx = data.find(b'PYZ-00')
if idx == -1:
print("No PYZ archive found.")
return
# 读取 archive 大小
arch_size = struct.unpack('>I', data[idx+4:idx+8])[0]
archive_data = data[idx+8:idx+8+arch_size]
# 解压 archive
try:
decompressed = zlib.decompress(archive_data)
except zlib.error:
print("Decompression failed.")
return
# 解析模块列表
pos = 0
while pos < len(decompressed):
name_len = struct.unpack('>I', decompressed[pos:pos+4])[0]
pos += 4
name = decompressed[pos:pos+name_len].decode('utf-8')
pos += name_len
size = struct.unpack('>I', decompressed[pos:pos+4])[0]
pos += 4
code = decompressed[pos:pos+size]
pos += size
filename = os.path.join(output_dir, f"{name}.pyc")
with open(filename, 'wb') as out:
out.write(code)
print(f"Extracted: {name}")
if __name__ == '__main__':
if len(sys.argv) != 3:
print("Usage: python extractor.py <exe_path> <output_dir>")
sys.exit(1)
extract_archive(sys.argv[1], sys.argv[2])
运行脚本后,会在指定目录生成若干 .pyc 文件。这些文件可直接用于后续的反编译步骤。若输出目录为空,说明目标文件非标准 PyInstaller 打包产物。
不同版本的 Python 生成的 .pyc 格式略有差异。Python 3.8+ 引入了新的魔术数字,可能需要更新反编译工具版本以支持最新格式。若遇到解密失败,通常是因为 PEP 569 引入的加密头,需手动剥离或使用支持新标准的工具。
处理加密与混淆
部分打包工具会对字节码进行简单加密或混淆,导致直接反编译失败。此时需先通过脚本剥离加密头,或寻找对应的解密算法。
对于强混淆的代码,反编译结果可能难以阅读。建议结合静态分析工具查看控制流图,辅助理解逻辑。注意,反编译仅适用于未加壳或弱保护的 EXE,强保护方案通常包含完整性校验,修改会导致程序崩溃。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









