在python中处理tcpdump输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17904231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Handling tcpdump output in python
提问by ashish g
Im trying to handle tcpdump output in python.
我试图在 python 中处理 tcpdump 输出。
What I need is to run tcpdump (which captures the packets and gives me information) and read the output and process it.
我需要的是运行 tcpdump(它捕获数据包并提供信息)并读取输出并对其进行处理。
The problem is that tcpdump keeps running forever and I need to read the packet info as soon as it outputs and continue doing it.
问题是 tcpdump 一直在运行,我需要在它输出后立即读取数据包信息并继续执行。
I tried looking into subprocess of python and tried calling tcpdump using popen and piping the stdout but it doesnt seem to work.
我尝试查看 python 的子进程并尝试使用 popen 调用 tcpdump 并通过管道传输标准输出,但它似乎不起作用。
Any directions on how to proceed with this.
有关如何进行此操作的任何说明。
import subprocess
def redirect():
tcpdump = subprocess.Popen("sudo tcpdump...", stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
while True:
s = tcpdump.stdout.readline()
# do domething with s
redirect()
采纳答案by swstephe
You can make tcpdump line-buffered with "-l". Then you can use subprocess to capture the output as it comes out.
您可以使用“-l”使 tcpdump 行缓冲。然后您可以使用 subprocess 来捕获输出。
import subprocess as sub
p = sub.Popen(('sudo', 'tcpdump', '-l'), stdout=sub.PIPE)
for row in iter(p.stdout.readline, b''):
print row.rstrip() # process here
回答by dstromberg
By default, pipes are block buffered and interactive output is line buffered. It sounds like you need a line buffered pipe - coming from tcpdump in a subprocess.
默认情况下,管道是块缓冲的,而交互式输出是行缓冲的。听起来您需要一个行缓冲管道 - 来自子进程中的 tcpdump。
In the old days, we'd recommend Dan Bernstein's "pty" program for this kind of thing. Today, it appears that pty hasn't been updated in a long time, but there's a new program called "emtpy" which is more or less the same idea: http://empty.sourceforge.net/
在过去,我们建议使用 Dan Bernstein 的“pty”程序来处理此类事情。今天看来 pty 已经很久没有更新了,但是有一个名为“emtpy”的新程序,它或多或少是相同的想法:http://empty.sourceforge.net/
You might try running tcpdump under empty in your subprocess to make tcpdump line buffered even though it's writing to a pipe.
您可能会尝试在子进程中的 empty 下运行 tcpdump 以使 tcpdump 行缓冲,即使它正在写入管道。