Search code examples
pythondjangotcpdump

How to check transporting some data to the port?


I use Django 1.6 and Python 2.7

It is my tcpdump command.

sudo /usr/sbin/tcpdump -n -X port 3331

And I kick the command from python because I'd like to use it in Django.

import subprocess as sub

def tcpdump(request, port):    
    result = 'nothing'

    count = 0
    proc = sub.Popen(['sudo', 'tcpdump', '-n', '-X', 'port', str(port)], stdout=sub.PIPE)    

    try:
        for row in proc.stdout:
            print row.rstrip()   # process here
            result = str(row.rstrip())
            count += 1
            if count > 10:
                break
    except:
        print 'tcpdump error'
        proc.terminate()

    return HttpResponse(result)

I wrote in the views.py.

urls.py

url(r'^tcpdump(?P<port>\d+)/$', tcpdump),

I will just access to http://some.url/tcpdump3331

This row.rstrip() get multiple lines string, and I'd like to do timeout.

Could you tell me better practice?


Solution

  • You do not need to run tcpdump from your app. The point is that it sniffs the network traffic, and logs network packets regardless of the applications generating the traffic. You do not even have to run it on the same computer, where your server is running, just run in on the same subnet.

    You can also use GUI tools like wireshark which is easier to configure.