2 # -*- coding: utf-8 -*-
5 from csv import reader, Sniffer
6 from os.path import exists
7 from argparse import ArgumentParser
10 def showinfo(f_in, source_ip, destination_ip):
13 with open(f_in, 'r') as f:
14 csv = reader(f, delimiter=',', quotechar='"')
16 # Make sure that CSV file includes a header.
17 if not Sniffer().has_header(f.read(8192)):
18 sys.stderr.write("ERROR: CSV file has no header!\n")
22 # Parse header of the input file
24 # Find field for source IP
26 source_field = header.index("Source")
28 sys.stderr.write("ERROR: Cannot find column 'Source' " +
30 sys.stderr.write("These are the values that were found: " +
31 "%s\n" % ", ".join(header))
34 # Find field for destination IP
36 dest_field = header.index("Destination")
38 sys.stderr.write("ERROR: Cannot find column 'Destination' " +
40 sys.stderr.write("These are the values that were found: " +
41 "%s\n" % ", ".join(header))
44 # Parse CSV and add values
48 if row[source_field] != source_ip:
51 if row[dest_field] not in ips:
52 ips[row[dest_field]] = 1
54 ips[row[dest_field]] += 1
56 if row[dest_field] != destination_ip:
59 if row[source_field] not in ips:
60 ips[row[source_field]] = 1
62 ips[row[source_field]] += 1
65 print "ERROR: IP address does not occur in CSV file!"
68 print "Number of packets: %d" % pkts
69 print "Number of connecting partners: %d" % len(ips)
72 for i in ips.iterkeys():
76 print "Most connections: %s" % ip
77 print "Number of packets for %s: %d" % (ip, ips[ip])
82 parser = ArgumentParser(description="Show connection information for an " +
84 epilog='Example: %s --input ' % sys.argv[0] +
85 'file.csv --source-ip 192.168.0.1')
86 parser.add_argument("--input", type=str, required=True,
87 help="Input CSV file.")
88 group = parser.add_mutually_exclusive_group(required=True)
89 group.add_argument("--source-ip", type=str, help="Source IP address.")
90 group.add_argument("--destination-ip", type=str,
91 help="Destination IP address.")
93 args = parser.parse_args()
94 if not exists(args.input):
95 sys.stderr.write("ERROR: Input file '%s' " % args.input +
99 showinfo(args.input, args.source_ip, args.destination_ip)
102 if __name__ == '__main__':