1.2 PySilk Example

The following is an example using the PySiLK bindings. The code is meant to show some standard PySiLK techniques, but is not otherwise meant to be useful. Explanations for the code can be found inline in the comments.

#!/usr/bin/python2.4

# Import the pysilk bindings
from silk import *

# Import sys for the command line arguments.
import sys

# Main function
def main():

    if len(sys.argv) != 3:
        print ("Usage: %s infile outset" % sys.argv[0])

    # Open an silk file for reading
    infile = SilkFile(sys.argv[1], READ)

    # Create an empty IPset
    destset = IPSet()

    # Loop over the records in the file
    for rec in infile:

      # Do comparisons based on rwrec field value
      if (rec.protocol == 6 and rec.sport in [80, 8080] and
          rec.packets > 3 and rec.bytes > 120):

          # Add the dest IP of the record to the IPset
          destset.add(rec.dip)


    # Save the IPset for future use
    destset.save(sys.argv[2])


    # count the items in the set
    count = 0
    for addr in destset:
        count = count + 1

    print "%d addresses" % count

    # Another way to do the same
    print "%d addresses" % len(destset)


    # Print the ip blocks in the set
    for base_prefix in destset.cidr_iter():
        print "%s/%d" % base_prefix

# Call the main() function when this program is started
if __name__ == '__main__':
    main()