Packet capture in python

    I'm home sick with a cold today and got bored. I wanted to play with packet capture in python, and the documentation for pcapy is a little sparse. I therefore wrote this simple little sample script:

      #!/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)
      


    Which outputs something like this:

      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
      


    Next step, decode me some headers!

    Tags for this post: python pcapy example
    Related posts: Dear lazy web: writing to the win32 event log in Python; Implementing SCP with paramiko; mbot: new hotness in Google Talk bots; Calculating a SSH host key with paramiko; Twisted conch; Example 2.1 from Dive Into Python

posted at: 10:22 | path: /python/pcapy | permanent link to this entry