简体   繁体   English

如何在linux中读取python中进程的内存?

[英]How can I read the memory of a process in python in linux?

I'm trying to use python and python ptrace to read the memory of an external process. 我正在尝试使用python和python ptrace来读取外部进程的内存。 I need to work entirely in python, and I've been trying to read and print out the memory of a process in linux. 我需要完全在python中工作,并且我一直在尝试读取并打印出linux中进程的内存。

So for example I've tried the following code, which keeps giving me IO errors: 所以例如我尝试了以下代码,它一直给我IO错误:

proc_mem = open("/proc/%i/mem" % process.pid, "r")
print proc_mem.read()
proc_mem.close()

Mostly I just want to repeatedly dump the memory of a process and look for changes over time. 大多数情况下,我只想反复转储进程的内存并查找随时间的变化。 If this is the correct way to do this, then what is my problem? 如果这是正确的方法,那么我的问题是什么? OR is there a more appropriate way to do this? 或者有更合适的方法吗?

Call a shell command from python - subprocess module 从python - subprocess模块​​调用shell命令

import subprocess

# ps -ux | grep 1842 (Assuming 1842 is the process id. replace with process id you get)

p1 = subprocess.Popen(["ps", "-ux"], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["grep", "1842"], stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]
print output

and parse through output to see its memory utilization 并解析输出以查看其内存利用率

Mostly I just want to repeatedly dump the memory of a process and look for changes over time. 大多数情况下,我只想反复转储进程的内存并查找随时间的变化。 If this is the correct way to do this, then what is my problem? 如果这是正确的方法,那么我的问题是什么? OR is there a more appropriate way to do this? 或者有更合适的方法吗?

You may be interested in gdb's reverse debugging , which records all changes to process memory. 您可能对gdb的反向调试感兴趣,它会记录对进程内存的所有更改。 Here is the tutorial ( google cache ). 这是教程谷歌缓存 )。

There is also Robert O'Callahan 's Chronicle / Chronomancer work , if you want to play with the raw recording tools. 还有罗伯特O'Callahan纪事 / Chronomancer 工作 ,如果你想与原记录工具打。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM