Long long ago, I wrote this piece of code, with Python and pcapy, for my project. Today I put it on my blog, partly for recording, and partly for memento.
This program read the data in libpcap file format, filter some useless records, and write the filtered records to a new file. Majorly, the work was done with pcapy, a wrapper for libpcap packet capture library.
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | #!/usr/bin/python # Copyright (c) 2007 # # Pcap dump file filter. # # This tools filter some packets in pcap capture files # here is the packet send by our robot # # Authors:HonetNet Project # import sys import string from exceptions import Exception import pcapy from pcapy import * def Drop(data): """Check if this packet should be drop """ #Hide some project related code return False def filefilter(filename): """filter a single file """ # Open file try: processor = open_offline(filename) except pcapy.PcapError, e: print "Can't open file: "+filename print "t",e return 1 #check if it's the Ether packet if pcapy.DLT_EN10MB != processor.datalink(): print "Not a Ethernet packet..." return 2 #Open the file store the data after filter if sys.platform == 'win32': pos = filename.rfind('') elif sys.platform == 'linux2': pos = filename.rfind('/') else: print "Running on a unexpect OS" sys.exit(1) if pos == -1: newfile = "filtered-"+filename else: newfile = filename[:pos+1] + 'filtered-' + filename[pos+1:] print newfile try: global dumper dumper = processor.dump_open(newfile) except pcapy.PcapError, e: print "Can't write packet to:", newfile print "t",e return 3 processor.loop(0, packetHandler) def packetHandler(hdr, data): """process with single packet """ if not Drop(data): global dumper dumper.dump(hdr, data) # Process command-line arguments. if __name__ == '__main__': if len(sys.argv) <= 1: print "Usage: %s <filename>" % sys.argv[0] sys.exit(1) filefilter(sys.argv[1]) |
This code is somehow bad, abuse of “import *”, import never-used library, insufficient comments, and so on. But I want to post the original copy, except one comment line. The bad of the post code could be a good teacher of future good ones.
Nowadays, the team is already the thing of the past. But I could never forget it, my first team to involve and lead.