问题描述
我正在尝试在 python 中处理 tcpdump 输出.
Im trying to handle tcpdump output in 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.
我尝试查看 python 的子进程并尝试使用 popen 调用 tcpdump 并通过管道传输标准输出,但它似乎不起作用.
I tried looking into subprocess of python and tried calling tcpdump using popen and piping the stdout but it doesnt seem to work.
有关如何进行此操作的任何说明.
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()
推荐答案
您可以使用-l"使 tcpdump 行缓冲.然后你可以使用 subprocess 来捕获输出.
You can make tcpdump line-buffered with "-l". Then you can use subprocess to capture the output as it comes out.
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
这篇关于在 python 中处理 tcpdump 输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!