Welcome, guest | Sign In | My Account | Store | Cart

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

Python, 27 lines
 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/env 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)
pc.loop(__my_handler)

2 comments

jose nazario 16 years, 5 months ago  # | flag

save time, stash the compiled RE patterns. save the compiled REs, saving time by not recompiling them for every packet and then throwing them away. move this:

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

someplace else. also, you can then have a list of patterns to match against, ie find me all Java files, all MP3s, etc ... by iterating over the list of precompiled REs. (this is basically what flowgrep does ...)

nice simple example, otherwise.

Anand 15 years ago  # | flag

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