Skip to content

Instantly share code, notes, and snippets.

@siddolo
Last active May 14, 2025 18:16
Show Gist options
  • Save siddolo/59a8ce248cb0afe705989715cf62090f to your computer and use it in GitHub Desktop.
Save siddolo/59a8ce248cb0afe705989715cf62090f to your computer and use it in GitHub Desktop.
Dump all memory-loaded modules with accessible bytecode (.pyc)
# pip install uncompyle6
# cd /tmp/python_memory_dump
find ./ -name '*.pyc' -print0 | xargs -0 -n1 -I{} sh -c 'uncompyle6 "{}" > "$(dirname "{}")/$(basename "{}" .pyc).py"'
import sys
import os
import marshal
import imp
OUTPUT_DIR = '/tmp/python_memory_dump'
MAGIC = b'\x03\xf3\x0d\x0a' # Python 2.7 magic number
TIMESTAMP = b'\x00\x00\x00\x00' # placeholder timestamp
def dump_module(modname, module):
if not hasattr(module, '__file__'):
return
if not hasattr(module, '__loader__'):
return
loader = module.__loader__
if loader is None:
return
if not hasattr(loader, 'get_code'):
return
code = loader.get_code(modname)
if code is None:
return
relpath = modname.replace('.', '/') + '.pyc'
outpath = os.path.join(OUTPUT_DIR, relpath)
outdir = os.path.dirname(outpath)
if not os.path.exists(outdir):
os.makedirs(outdir)
f = open(outpath, 'wb')
f.write(MAGIC)
f.write(TIMESTAMP)
marshal.dump(code, f)
f.close()
print("Wrote:", outpath)
print("Dumping all memory-loaded modules with accessible bytecode...")
for modname in sys.modules:
module = sys.modules[modname]
if module is not None:
dump_module(modname, module)
print("Done.")
@siddolo
Copy link
Author

siddolo commented May 14, 2025

Dump single module

import xxx #target module

import marshal
import imp

code = None
for suffix, loader, type_ in imp.get_suffixes():
    if loader == imp.PY_COMPILED:
        break

if hasattr(xxx, '__file__'):
    # Accedi al loader e al codice oggetto
    loader = xxx.__loader__
    if hasattr(loader, 'get_code'):
        code = loader.get_code('xxx')

if code:
    with open('/tmp/xxx.pyc', 'wb') as f:
        f.write(b'\x03\xf3\x0d\x0a')  # magic number Python 2.7
        f.write(b'\x00' * 4)          # timestamp placeholder
        marshal.dump(code, f)
        print("Dumped to /tmp/xxx.pyc")
else:
    print("Unable to get code object.")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment