views:

2118

answers:

3

Hi all,

What is the best way to sniff network packets using Python?

I've heard from several places that the best module for this is a module called Scapy, unfortunately, it makes python.exe crash on my system. I would assume that it's just a problem with how I installed it, except that many other people have told me that it doesn't work particularly well on Windows. (If anyone is interested, I'm running Windows Vista, which might affect things).

Does anyone know of a better solution?

Thanks

EDITED TO ADD:

Thanks for the answers.

After reading the answer telling me to install PyPcap, I messed around with it a bit and found out that Scapy, which I had tried using, was telling me to install PyPcap as well, except that it's a modified version for it's use. It was this modified PyPcap that was causing the problem, apparently, since the example in the answer also caused a hang.

I installed the original version of PyPcap (from Google's site), and Scapy started working fine (I didn't try many things, but at least it didn't crash as soon as I started sniffing). I sent a new defect ticket to the Scapy developers: http://trac.secdev.org/scapy/ticket/166, hope they can do something with it.

Anyways, just thought I'd let y'all know.

+5  A: 

Use python-libpcap.

import pcap

p = pcap.pcapObject()
dev = pcap.lookupdev()
p.open_live(dev, 1600, 0, 100)
#p.setnonblock(1)
try:
    for pktlen, data, timestamp in p:
        print "[%s] Got data: %s" % (time.strftime('%H:%M', 
                                                   time.localtime(timestamp)),
                                     data)
except KeyboardInterrupt:
    print '%s' % sys.exc_type
    print 'shutting down'
    print ('%d packets received, %d packets dropped'
           ' %d packets dropped by interface') % p.stats()
nosklo
+1  A: 

Another option is pypcap.

To parse the results, Construct is very slick.

orip
is construct dead? it doesn't look like there have been any new releases in over a year...
chills42
A: 

Using pypcap:

import dpkt, pcap
pc = pcap.pcap()
pc.setfilter('icmp')
for timestamp, packet in pc:
    print dpkt.ethernet.Ethernet(pkt)

output sample:

Ethernet(src='\x00\x03G\xb2M\xe4', dst='\x00\x03G\x06h\x18', data=IP(src='\n\x00\x01\x1c',
dst='\n\x00\x01\x10', sum=39799, len=60, p=1, ttl=128, id=35102, data=ICMP(sum=24667,
type=8, data=Echo(id=512, seq=60160, data='abcdefghijklmnopqrstuvwabcdefghi'))))

Ethernet(src='\x00\x03G\x06h\x18', dst='\x00\x03G\xb2M\xe4', data=IP(src='\n\x00\x01\x10',
dst='\n\x00\x01\x1c', sum=43697, len=60, p=1, ttl=255, id=64227, data=ICMP(sum=26715,
data=Echo(id=512, seq=60160, data='abcdefghijklmnopqrstuvwabcdefghi'))))
nosklo