Getting stdout from tcpdump subprocess after it is completed

I execute tcpdump in a subprocess as follows:

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

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

Then I will go to the website using urllib.open() . After that, I would like to kill tcpdump and put everything that it printed into a line. I tried the following:

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

But (if I am not doing something wrong), this does not work; I killed the process, now there is nothing left to read. If I use read() or communicate() before exiting, my script will just sit and read and continue, waiting for tcpdump finish (which will not happen).

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

+7
source share
1 answer

Instead of using tcpdump, it is often recommended to use PCAP directly or Scapy .

If this is not an option, just call communicate after terminate - killing a process does not kill the data in the pipes. However, be sure to separate the arguments when creating the subprocess ( [,'-w', '-'] instead of [... , '-w -', ..] ):

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

All Articles