Solved

In python how can I redirect the output from tcpdump to a variable

Posted on 2015-01-18
2
1,566 Views
Last Modified: 2015-01-19
Greetings,

I am looking for a way to make this work in python,

f=os.system("tcpdump -l src 172.16.0.3 and dst 172.16.0.33")
print "Dump is ", f

I will then process 'f' downstream of this

This produces an output of tcpdump to the console but nothing to the 'f' string

Thanks,
Ron
0
Comment
Question by:RonWensley
2 Comments
 
LVL 25

Accepted Solution

by:
clockwatcher earned 500 total points
ID: 40556771
I think you'd be much better served by going with a pcap module (https://code.google.com/p/pypcap/) but you can give this a try:
import StringIO
import sys
import shlex
import subprocess
cmd = "/usr/sbin/tcpdump -l src 172.16.0.3 and dst 172.16.0.33"
args = shlex.split(cmd)
tcpdump = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
print "Press CTRL-C to stop tcpdump"
output = StringIO.StringIO()
running = True
while running:
    try:
        data = tcpdump.stdout.readline()
        if len(data):
            output.write(data)
        else:
            running = False
    except KeyboardInterrupt:
        tcpdump.kill()
        data = tcpdump.stdout.readline()
        if len(data):
            output.write(data)
        running = False

lines = output.getvalue().split("\n")
for i, line in enumerate(lines):
    print "{0} => {1}".format(i, line)

Open in new window

0
 

Author Closing Comment

by:RonWensley
ID: 40558346
Thanks for the quick reply.  This is working out great.  I will have a look at the link you offered and see how that can be used.
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This is an explanation of a simple data model to help parse a JSON feed
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Learn several ways to interact with files and get file information from the bash shell. ls lists the contents of a directory: Using the -a flag displays hidden files: Using the -l flag formats the output in a long list: The file command gives us mor…
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question