Network sniffing with python

Jorge Machado picture Jorge Machado · Jan 14, 2012 · Viewed 9.3k times · Source

I'm going to build an sniffing software for the university. I have some ideas but want to hear some more. The idea is to use a passive tap on front on the firewall and so get all data...

I know C is faster but i want to do it with python any good ideas like libraries etc?

Refs:

Answer

ThiefMaster picture ThiefMaster · Jan 14, 2012

Use pylibcap. It provides an interface to libpcap which is the de-facto standard for packet sniffing on linux. To parse packets, you might want to use the construct library as it already contains a parser for TCP packets.

Here's a small example program:

import pcap
from construct.protocols.ipstack import ip_stack

def print_packet(pktlen, data, timestamp):
    if not data:
        return

    stack = ip_stack.parse(data)
    payload = stack.next.next.next
    print payload


p = pcap.pcapObject()
p.open_live('eth0', 1600, 0, 100)
p.setfilter('dst port 80', 0, 0)

print 'Press CTRL+C to end capture'
try:
    while True:
        p.dispatch(1, print_packet)
except KeyboardInterrupt:
    print # Empty line where ^C from CTRL+C is displayed
    print '%d packets received, %d packets dropped, %d packets dropped by interface' % p.stats()