本文介绍了终止后从 tcpdump 子进程获取标准输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这样的子进程中运行 tcpdump:

I am running tcpdump in a subprocess like this:

pcap_process = subprocess.Popen(['tcpdump', '-s 0', '-w -', 'tcp'],
                                  stdout=subprocess.PIPE, stderr=subprocess.PIPE)

-w - 参数很重要:它告诉 tcpdump 将生成的 .pcap 文件打印到 stdout.

The -w - argument is important: it tells tcpdump to print the resulting .pcap file to stdout.

然后我继续使用 urllib.open() 访问网站.完成后,我想杀死 tcpdump 并将它打印的任何内容放入字符串中.我尝试了以下方法:

I then go on to access a website using urllib.open(). After this is done, I would like to kill tcpdump and put whatever it printed into a string. I have tried the following:

pcap_process.terminate()
result = pcap_process.stdout.read()    # or readline(), etc.

但是(除非我做错了什么),那是行不通的;我杀了这个进程,现在没有什么可读的了.如果我在终止之前使用 read()communicate(),我的脚本将只是坐在那里继续阅读,等待 tcpdump完成(它不会).

But (unless I'm doing something wrong), that doesn't work; I killed the process, now there's nothing left to be read. If I use read() or communicate() before terminating, my script will just sit there and read on and on, waiting for tcpdump to finish (which it won't).

有没有办法做到这一点(最好没有循环)?

Is there a way to do this (preferably without loops)?

推荐答案

通常建议使用 PCAP 直接,或Scapy.

如果这不是一个选项,只需在 terminate 之后调用 communicate - 终止进程不会终止管道中的数据.但是,不要忘记在创建子流程时将参数分开([,'-w', '-'] 而不是 [... , '-w -',..]):

If that isn't an option, simply call communicate after terminate - killing a process does not kill data in the pipes to it. However, don't forget to separate arguments in the creation of the subprocess ([,'-w', '-'] instead of [... , '-w -', ..]):

pcap_process = subprocess.Popen(['tcpdump', '-s', '0', '-w', '-', 'tcp'],
                                  stdout=subprocess.PIPE, stderr=subprocess.PIPE)

这篇关于终止后从 tcpdump 子进程获取标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-30 20:14