我已经在某些Linux发行版(Debian,Linux Mint …)上测试了以下代码,并且可以正常工作,但是在CentOS下,即使我以root身份运行,也会出现错误:#!/usr/bin/env pythonimport remaps_file = open(/proc/18396/maps, r...

我已经在某些Linux发行版(Debian,Linux Mint …)上测试了以下代码,并且可以正常工作,但是在CentOS下,即使我以root身份运行,也会出现错误:
#!/usr/bin/env python
import re
maps_file = open("/proc/18396/maps", 'r')
mem_file = open("/proc/18396/mem", 'r', 0)
for line in maps_file.readlines(): # for each mapped region
m = re.match(r'([0-9A-Fa-f]+)-([0-9A-Fa-f]+) ([-r])', line)
if m.group(3) == 'r': # if this is a readable region
start = int(m.group(1), 16)
end = int(m.group(2), 16)
mem_file.seek(start) # seek to region start
chunk = mem_file.read(end - start) # read region contents
print chunk, # dump contents to standard output
maps_file.close()
mem_file.close()
该脚本读取进程的内存并转储可读区域.在CentOS 5.4 x64下,出现以下错误:
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
该过程是活跃且可读的:
[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
任何想法?我在Python 2.4下尝试过,而Python 2.7在类似Debian的发行版上工作,但在CentOS下却没有.
解决方法:
经过一些挖掘,我自己找到了答案:
#!/usr/bin/env python
import ctypes, re, sys
## Partial interface to ptrace(2), only for PTRACE_ATTACH and PTRACE_DETACH.
c_ptrace = ctypes.CDLL("libc.so.6").ptrace
c_pid_t = ctypes.c_int32 # This assumes pid_t is 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)
for line in maps_file.readlines(): # for each mapped region
m = re.match(r'([0-9A-Fa-f]+)-([0-9A-Fa-f]+) ([-r])', line)
if m.group(3) == 'r': # if this is a readable region
start = int(m.group(1), 16)
end = int(m.group(2), 16)
mem_file.seek(start) # seek to region start
chunk = mem_file.read(end - start) # read region contents
print chunk, # dump contents to standard output
maps_file.close()
mem_file.close()
ptrace(False, int(pid))
沃梦达教程
本文标题为:Python读取Linux内存进程错误(/ proc / $pid / mem)


基础教程推荐
猜你喜欢
- CentOS 7.5 安装 Python3.7 2023-09-03
- Python随机采样及概率分布(二) 2023-08-11
- Python 对象序列化与反序列化之pickle json详细解析 2023-08-09
- 四步教你学会打包一个新的Python模块 2022-10-20
- python总结之闭包和装饰器 2023-08-11
- Linux软件:Anaconda安装python和自带Python 2023-09-03
- python-“陈旧文件句柄”错误,当进程尝试读取文件时,该其他进程已被删除 2023-11-11
- pandas中df.rename()的具体使用 2022-08-30
- Python—进程、线程、协程 2023-09-03
- python验证多组数据之间有无显著差异 2023-08-08