python2解决反编译乱码
文章目录
- 得到.pyc文件
- 调用以下脚本(二进制转明文)
- 得到源码文件
得到.pyc文件
见文章:《python2反编译部分》
- 执行到这一步就能得到.pyc文件:3、 解包.exe文件(以PyInstaller为例)
调用以下脚本(二进制转明文)
#!/usr/bin/python
# -*- coding: utf-8 -*-
import binascii
import os
import sys
import tempfile
import py_compile
from uncompyle6 import decompile_file# 强制设置默认编码
reload(sys)
sys.setdefaultencoding('utf-8')med_data = ""def print_gbk(s):s_gbk = s.encode('gbk','ignore')print(s_gbk.decode('gbk'))def save_as_py(result, original_pyc_path):try:# 获取原始文件名(不带.pyc扩展名)base_name = os.path.splitext(os.path.basename(original_pyc_path))[0]output_py = '%s.py' % base_name# 写入txt文件with open(output_py, 'w') as f:f.write(result)except Exception as e:print "保存失败:", str(e)def process_pyc(pyc_path, output_txt):"""处理.pyc文件,生成十六进制文本"""try:# 读取.pyc文件二进制数据with open(pyc_path, 'rb') as f:data = f.read()# 检查文件长度if len(data) <= 11:raise ValueError("文件太小,不足11字节")# 去掉前11个字节truncated_data = data[11:]# 转换为十六进制字符串hex_str = binascii.hexlify(truncated_data)# 添加空格分隔符formatted_hex = ' '.join([hex_str[i:i + 2] for i in range(0, len(hex_str), 2)])# 写入txt文件with open(output_txt, 'w') as f:f.write(formatted_hex)global med_datamed_data = formatted_hex# print "B处理成功."print_gbk("B处理成功.")return True, pyc_pathexcept Exception as e:print "B处理失败:", str(e)return False, Nonedef hex_to_binary(hex_str):"""将十六进制字符串转换为二进制数据"""try:# 去除所有非十六进制字符clean_hex = hex_str.replace(' ', '').replace('\\x', '').replace('0x', '')# Python 2 专用转换方式return clean_hex.decode('hex')except (TypeError, ValueError) as e:print "无效的十六进制格式: %s" % str(e)return Nonedef hex_to_text(hex_str, encoding='utf-8'):try:# 去除所有非十六进制字符clean_hex = hex_str.replace(' ', '').replace('\\x', '').replace('0x', '')# Python 2 专用转换方式binary_data = clean_hex.decode('hex')return binary_data.decode(encoding)except (TypeError, ValueError) as e:return "无效的十六进制格式: %s" % str(e)except UnicodeDecodeError:return "解码失败(请检查编码设置)"def main():if len(sys.argv) < 2:print "请指定.pyc文件路径"print "用法: python script.py <input.pyc>"returninput_pyc = sys.argv[1]# 步骤1: 处理.pyc文件生成十六进制文本output_txt = "temp_hex.txt"success, pyc_path = process_pyc(input_pyc, output_txt)if not success:print "十六进制转换失败"returnresult = hex_to_text(med_data)save_as_py(result, input_pyc)if __name__ == "__main__":main()
得到源码文件
- 中间文件(十六进制的数据):
- 与pyc文件同名的py源文件:
注意:
- 文件末尾有00编码出来的无用字符要删掉,如图: