Python read Linux memory process error (/proc/$pid/mem) -


i have following code tested on linux distros (debian, linux mint...) , working, under centos error run root:

#!/usr/bin/env python import re maps_file = open("/proc/18396/maps", 'r') mem_file = open("/proc/18396/mem", 'r', 0) line in maps_file.readlines():  # each mapped region     m = re.match(r'([0-9a-fa-f]+)-([0-9a-fa-f]+) ([-r])', line)     if m.group(3) == 'r':  # if readable region         start = int(m.group(1), 16)         end = int(m.group(2), 16)         mem_file.seek(start)  # seek region start         chunk = mem_file.read(end - start)  # read region contents         print chunk,  # dump contents standard output maps_file.close() mem_file.close() 

the script reads process' memory , dumps readable region. under centos 5.4 x64 following error:

traceback (most recent call last):   file "./mem.py", line 11, in ?     chunk = mem_file.read(end - start)  # read region contents ioerror: [errno 3] no such process 

the process alive , readable:

[root@localhost ~]# ps xa|grep 18396 18396 ?        s      0:00 /usr/sbin/httpd [root@localhost ~]# ls -al /proc/18396/maps && ls -al /proc/18396/mem -r--r--r-- 1 root root 0 jan 31 17:26 /proc/18396/maps -rw------- 1 root root 0 jan 31 17:26 /proc/18396/mem 

any idea? tried under python 2.4 , python 2.7 works on debian-like distros not under centos.

found answer myself after digging:

#!/usr/bin/env python import ctypes, re, sys  ## partial interface ptrace(2), ptrace_attach , ptrace_detach. c_ptrace = ctypes.cdll("libc.so.6").ptrace c_pid_t = ctypes.c_int32 # assumes pid_t int32_t 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) #ptrace_attach or ptrace_detach     c_pid = c_pid_t(pid)     null = ctypes.c_void_p()     err = c_ptrace(op, c_pid, null, null)     if err != 0: raise syserror, 'ptrace', err  pid = "18396"  ptrace(true, int(pid)) maps_file = open("/proc/"+pid+"/maps", 'r') mem_file = open("/proc/"+pid+"/mem", 'r', 0) line in maps_file.readlines():  # each mapped region     m = re.match(r'([0-9a-fa-f]+)-([0-9a-fa-f]+) ([-r])', line)     if m.group(3) == 'r':  # if readable region         start = int(m.group(1), 16)         end = int(m.group(2), 16)         mem_file.seek(start)  # seek region start         chunk = mem_file.read(end - start)  # read region contents         print chunk,  # dump contents standard output maps_file.close() mem_file.close() ptrace(false, int(pid)) 

Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -