我有一个经过混淆的 Python 代码对象,它已使用各种模块(包括 base64、zlib、gzip 和 marshal)进行编码和压缩。
我的目标是对该代码对象进行逆向工程,以提取原始源代码。
这是我用来生成混淆代码对象的过程:
import gzip, zlib, marshal, base64
pycode = "print('Hello world')"
obfuscated_code = base64.b64encode(zlib.compress(gzip.compress(marshal.dumps(compile(pycode, <string>, "exec"))), level=zlib.Z_BEST_COMPRESSION))
然后我做了以下操作来运行混淆的Python代码来运行..
import gzip, zlib, marshal, base64
exec(marshal.loads(gzip.decompress(zlib.decompress(base64.b64decode(obfuscated_code)))))
我尝试将 exec 更改为打印。 然而,我收到的输出不是打印源代码,而是:
bash<code object <module> at 0x15034df59df0, file "Nice Try", line 1>
我的问题是:如何对该代码对象进行逆向工程以成功提取原始源代码?
有没有办法从给定的混淆代码对象中恢复源代码?
谢谢您的帮助!
这里有两种方法可以让您反编译字节码,但您需要原始 .pyc 或 .pyo 文件将其反编译回源代码。
如果您正在使用
uncompyle6
,我建议您使用 python <= 3.6
软件包。
pip install uncompyle6
uncompyle6 path/to/bytecode/file.pyc
import subprocess
def decompile_pyc(pyc_file_path):
try:
command = ["uncompyle6", pyc_file_path]
result = subprocess.run(command, capture_output=True, text=True, check=True)
decompiled_code = result.stdout
return decompiled_code
except subprocess.CalledProcessError as e:
print("Error:", e)
return None
# Provide the path to your .pyc file
pyc_file_path = "__pycache__/test.cpython-38.pyc"
# Call the function to decompile the .pyc file
decompiled_code = decompile_pyc(pyc_file_path)
# Print the decompiled code
if decompiled_code:
print(decompiled_code)
查看 https://github.com/rocky/python-uncompyle6 了解更多
如果您使用
python-3.7
或 python-3.8
,请查看 decompyle3
。用法和以前基本一样:
pip install decompyle6
decompyle6 path/to/bytecode/file.pyc
import subprocess
def decompile_pyc(pyc_file_path):
try:
command = ["decompyle3", pyc_file_path]
result = subprocess.run(command, capture_output=True, text=True, check=True)
decompiled_code = result.stdout
return decompiled_code
except subprocess.CalledProcessError as e:
print("Error:", e)
return None
# Provide the path to your compiled .pyc file
pyc_file_path = "__pycache__/test.cpython-38.pyc"
# Call the function to decompile the .pyc file
decompiled_code = decompile_pyc(pyc_file_path)
# Print the decompiled code
if decompiled_code:
print(decompiled_code)
查看 https://github.com/rocky/python-decompile3 了解更多信息。