ActiveState Code

Recipe 576678: Packet monitoring with dpkt


This recipe shows how to use pypcap and dpkt to monitor network traffic and grep with regular expression. Python 2.3 required pypcap: http://code.google.com/p/pypcap/ dpkt: http://code.google.com/p/dpkt/

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/usr/bin/python
# this is a simple example to sniff on port 80 for magic CAFEBABE. 
# it has to run either sudo root on any Unix or with windows admin right. 
# author email: pythonrocks@gmail.com. 
import dpkt, pcap
import re
import sys

pattern=re.compile('.*CAFEBABE.*')

def __my_handler(ts,pkt,d):


    tcpPkt=dpkt.tcp.TCP(pkt)
    data=tcpPkt.data

    # let's find any java class pass 
    searched=pattern.search(data)

    if searched:
      d['hits']+=1
      print 'counters=',d['hits']

pc = pcap.pcap()
pc.setfilter('tcp and dst port 80')

print 'listening on %s: %s' % (pc.name, pc.filter)

Comments

  1. 1. At 3:51 a.m. on 23 mar 2009, Anand Balachandran Pillai said:

    Perhaps you will be interested in my recipe #576690 which uses pypcap and dpkt for port scan detection.

Sign in to comment