Solved

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

Posted on 2015-01-18
2
1,401 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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

This is an explanation of a simple data model to help parse a JSON feed
This is about my first experience with programming Arduino.
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

743 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now