Advertisement
NoTextForSpeech

Memory Dump Python (Linux)

Apr 16th, 2024 (edited)
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1. # memdump.py
  2. #https://gist.githubusercontent.com/Dbof/b9244cfc607cf2d33438826bee6f5056/raw/aa4b75ddb55a58e2007bf12e17daadb0ebebecba/memdump.py
  3. #! /usr/bin/env python3
  4. import sys
  5. import re
  6.  
  7. if __name__ == "__main__":
  8.  
  9.     if len(sys.argv) != 2:
  10.         print('Usage:', sys.argv[0], '<process PID>', file=sys.stderr)
  11.         exit(1)
  12.  
  13.     pid = sys.argv[1]
  14.  
  15.     # maps contains the mapping of memory of a specific project
  16.     map_file = f"/proc/{pid}/maps"
  17.     mem_file = f"/proc/{pid}/mem"
  18.  
  19.     # output file
  20.     out_file = f'{pid}.dump'
  21.  
  22.     # iterate over regions
  23.     with open(map_file, 'r') as map_f, open(mem_file, 'rb', 0) as mem_f, open(out_file, 'wb') as out_f:
  24.         for line in map_f.readlines():  # for each mapped region
  25.             m = re.match(r'([0-9A-Fa-f]+)-([0-9A-Fa-f]+) ([-r])', line)
  26.             if m.group(3) == 'r':  # readable region
  27.                 start = int(m.group(1), 16)
  28.                 end = int(m.group(2), 16)
  29.                 mem_f.seek(start)  # seek to region start
  30.                 print(hex(start), '-', hex(end))
  31.                 try:
  32.                     chunk = mem_f.read(end - start)  # read region contents
  33.                     out_f.write(chunk)  # dump contents to standard output
  34.                 except OSError:
  35.                     print(hex(start), '-', hex(end), '[error,skipped]', file=sys.stderr)
  36.                     continue
  37.     print(f'Memory dump saved to {out_file}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement