Getting stdout from a tcpdump subprocess after terminating it

做~自己de王妃 提交于 2019-12-23 08:05:29

问题


I am running tcpdump in a subprocess like this:

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

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

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.

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)?


回答1:


Instead of using tcpdump, it's often advisable to use PCAP directly, or Scapy.

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)


来源:https://stackoverflow.com/questions/7163877/getting-stdout-from-a-tcpdump-subprocess-after-terminating-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!