Skip to content

Instantly share code, notes, and snippets.

@eddieantonio
Created September 2, 2022 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eddieantonio/b8650e646903262a4a478c4f9ffd6fbe to your computer and use it in GitHub Desktop.
Save eddieantonio/b8650e646903262a4a478c4f9ffd6fbe to your computer and use it in GitHub Desktop.
Terrible script to dump CPython bytecode from a .pyc file
"""
Usage:
python3 -i load_pyc.py path/to/file.pyc
"""
import dis
import importlib.util
import marshal
import struct
import sys
INTERPRETER_MAGIC_NUMBER = importlib.util.MAGIC_NUMBER
def read_u32le(f):
"""Read unsigned 32-bit int (little endian)."""
return struct.unpack("<I", f.read(4))[0]
def decode_u16le(b):
"""Read unsigned 16-bit int (little endian)."""
return struct.unpack("<H", b)[0]
with open(sys.argv[1], "rb") as bytecode_file:
magic_number = bytecode_file.read(4)
header = read_u32le(bytecode_file)
if header == 0:
print("Timestamp .pyc")
time_stamp = read_u32le(bytecode_file)
file_size = read_u32le(bytecode_file)
else:
print("Hash pyc: idk how to deal with this")
print(magic_number, header)
# load the bytecode
bytecode = marshal.load(bytecode_file)
version = decode_u16le(magic_number[:2])
if magic_number == INTERPRETER_MAGIC_NUMBER:
print(f"versions match: {version}")
else:
print("Python version does not match :(")
print(
"Consult: https://github.com/python/cpython/blob/main/Lib/importlib/_bootstrap_external.py"
)
print(f"for a list that matches version: {version}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment