Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Adapted from Stackoverflow, a Python script to dump the memory of a process.
#!/usr/bin/env python
# Source:
# Adapted to be python3
import os
import re
import sys
def print_memory_of_pid(pid, only_writable=True):
Run as root, take an integer PID and return the contents of memory to STDOUT
stdout_b = os.fdopen(sys.stdout.fileno(), 'wb')
memory_permissions = 'rw' if only_writable else 'r-'
sys.stderr.write("PID = %d" % pid)
with open("/proc/%d/maps" % pid, 'r') as maps_file:
with open("/proc/%d/mem" % pid, 'rb', 0) as mem_file:
for line in maps_file.readlines(): # for each mapped region
m = re.match(r'([0-9A-Fa-f]+)-([0-9A-Fa-f]+) ([-r][-w])', line)
if == memory_permissions:
sys.stderr.write("\nOK : \n" + line+"\n")
start = int(, 16)
if start > 0xFFFFFFFFFFFF:
end = int(, 16)
sys.stderr.write( "start = " + str(start) + "\n") # seek to region start
chunk = - start) # read region contents
stdout_b.write(chunk) # dump contents to standard output
sys.stderr.write("\nPASS : \n" + line+"\n")
if __name__ == '__main__': # Execute this code when run from the commandline.
assert len(sys.argv) == 2, "Provide exactly 1 PID (process ID)"
pid = int(sys.argv[1])
except (AssertionError, ValueError) as e:
print("Please provide 1 PID as a commandline argument.")
print("You entered: %s" % ' '.join(sys.argv))
raise e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment