Skip to content

Instantly share code, notes, and snippets.

@djerfy
Created April 23, 2017 07:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djerfy/64b62d3b3af2431673d4ca3656fd231f to your computer and use it in GitHub Desktop.
Save djerfy/64b62d3b3af2431673d4ca3656fd231f to your computer and use it in GitHub Desktop.
Python | Memory Dump Process (with PID on argument)
#!/usr/bin/env python
import ctypes, re, sys
c_ptrace = ctypes.CDLL("libc.so.6").ptrace
c_pid_t = ctypes.c_int32
c_ptrace.argtypes = [ctypes.c_int, c_pid_t, ctypes.c_void_p, ctypes.c_void_p]
def ptrace(attach, pid):
op = ctypes.c_int(16 if attach else 17)
c_pid = c_pid_t(pid)
null = ctypes.c_void_p()
err = c_ptrace(op, c_pid, null, null)
if err != 0: raise Exception, 'ptrace', err
if (len(sys.argv) < 2):
print "%s <pid>" % sys.argv[0]
sys.exit(-1)
pid = sys.argv[1]
ptrace(True, int(pid))
dump_file = open("./%s.dump" % pid, 'w')
maps_file = open("/proc/%s/maps" % pid, 'r')
mem_file = open("/proc/%s/mem" % pid, 'r', 0)
for line in maps_file.readlines():
m = re.match(r'([0-9A-Fa-f]+)-([0-9A-Fa-f]+) ([-r])', line)
if m.group(3) == 'r':
try:
start = int(m.group(1), 16)
end = int(m.group(2), 16)
mem_file.seek(start)
chunk = mem_file.read(end - start)
dump_file.write(chunk)
except:
pass
maps_file.close()
mem_file.close()
dump_file.close()
ptrace(False, int(pid))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment