stillhq.com : Mikal, a geek from Canberra living in Silicon Valley http://www.stillhq.com The life, times, travel and software of Michael Still en Copyright (c) Michael Still 2000 - 2006 blosxom simplerss20 v20050208hh 180 http://blogs.law.harvard.edu/tech/rss Packet capture in python /python/pcapy Tue, 25 Nov 2008 10:22:00 PST I'm home sick with a cold today and got bored. I wanted to play with packet capture in python, and the documentation for <a href="http://oss.coresecurity.com/pcapy/doc/pt01.html">pcapy</a> is a little sparse. I therefore wrote this simple little sample script: <br/><br/> <ul><pre> #!/usr/bin/python # A simple example of how to use pcapy. This needs to be run as root. import datetime import gflags import pcapy import sys FLAGS = gflags.FLAGS gflags.DEFINE_string('i', 'eth1', 'The name of the interface to monitor') def main(argv): # Parse flags try: argv = FLAGS(argv) except gflags.FlagsError, e: print FLAGS print 'Opening %s' % FLAGS.i # Arguments here are: # device # snaplen (maximum number of bytes to capture _per_packet_) # promiscious mode (1 for true) # timeout (in milliseconds) cap = pcapy.open_live(FLAGS.i, 100, 1, 0) # Read packets -- header contains information about the data from pcap, # payload is the actual packet as a string (header, payload) = cap.next() while header: print ('%s: captured %d bytes, truncated to %d bytes' %(datetime.datetime.now(), header.getlen(), header.getcaplen())) (header, payload) = cap.next() if __name__ == "__main__": main(sys.argv) </pre></ul> <br/><br/> Which outputs something like this: <br/><br/> <ul><pre> 2008-11-25 10:09:53.308310: captured 98 bytes, truncated to 98 bytes 2008-11-25 10:09:53.308336: captured 66 bytes, truncated to 66 bytes 2008-11-25 10:09:53.315028: captured 66 bytes, truncated to 66 bytes 2008-11-25 10:09:53.316520: captured 130 bytes, truncated to 100 bytes 2008-11-25 10:09:53.317030: captured 450 bytes, truncated to 100 bytes 2008-11-25 10:09:53.324414: captured 124 bytes, truncated to 100 bytes 2008-11-25 10:09:53.327770: captured 114 bytes, truncated to 100 bytes 2008-11-25 10:09:53.328001: captured 210 bytes, truncated to 100 bytes </pre></ul> <br/><br/> Next step, decode me some headers! <br/><br/><i>Tags for this post: python(<a href="http://www.stillhq.com/python"><img src="http://www.stillhq.com/tagicon.cgi?post=/python/pcapy/000001&tag=python&format=.png" border="0" alt="S"></a>) pcapy(<a href="http://www.stillhq.com/pcapy"><img src="http://www.stillhq.com/tagicon.cgi?post=/python/pcapy/000001&tag=pcapy&format=.png" border="0" alt="S"></a>) </i><br/><i>Related posts: <a href="http://www.stillhq.com/python/000003.html">Dear lazy web: writing to the win32 event log in Python</a></i> <a href="http://www.stillhq.com/python/pcapy/000001.commentform.html">Comment</a> http://www.stillhq.com/python/pcapy/000001.html http://www.stillhq.com/python/pcapy/000001.html