Handling tcpdump output in python

Im trying to handle tcpdump output in python.

I need to run tcpdump (which captures packets and gives me information), and read the output and process it.

The problem is that tcpdump works all the time, and I need to read the package information as soon as it exits and continues to do so.

I tried to learn the python subprocess and tried calling tcpdump using popen and piping stdout, but it does not seem to work.

Any directions on how to do 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() 
+7
python subprocess popen tcpdump
source share
2 answers

You can do tcpdump with line buffering with "-l". You can then use the subprocess to capture the output as it exits.

 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 
+14
source share

By default, channels are buffered in blocks, and interactive output is buffered. It looks like you need a buffered string coming from tcpdump in a subprocess.

In the old days, we recommended Dan Bernstein's "pty" program for this kind of thing. Today, it seems that pty has not been updated for a long time, but there is a new program called "emtpy" which is more or less the same idea: http://empty.sourceforge.net/

You can try running tcpdump under an empty one in your subprocess to make the tcpdump line buffered even if it is written to the channel.

+1
source share

All Articles