Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling tcpdump output in python

Im trying to handle tcpdump output in python.

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

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.

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()
like image 450
ashish g Avatar asked Jul 28 '13 01:07

ashish g


People also ask

How do I check tcpdump output?

Use the "ifconfig" command to list all the interfaces. For example, the following command will capture the packets of "eth0" interface. The "-w" option lets you write the output of tcpdump to a file which you can save for further analysis. The "-r" option lets you read the output of a file.

How do I redirect a tcpdump output to a file?

Use “-w” option in tcpdump command to save the capture TCP/IP packet to a file, so that we can analyze those packets in the future for further analysis.

What is output format of tcpdump?

The tcpdump can also adjust output formats by using -X for hex or -A for ASCII. # tcpdump -i any -c4 -X tcpdump: data link type LINUX_SLL2 dropped privs to tcpdump tcpdump: verbose output suppressed, use -v[v]...


1 Answers

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
like image 171
swstephe Avatar answered Sep 17 '22 15:09

swstephe