813471a80804e6816abf25c574e7eeabd53d0b32
[pingpong.git] / parse_packet_frequency.py
1 #!/usr/bin/python
2
3 """
4 Script that takes a file (output by wireshark/tshark, in JSON format) and analyze
5 the traffic frequency of a certain device at a certain time.
6 """
7
8 import sys
9 import json
10 from collections import defaultdict
11 from dateutil import parser
12
13 JSON_KEY_SOURCE = "_source"
14 JSON_KEY_LAYERS = "layers"
15
16 JSON_KEY_ETH = "eth"
17 JSON_KEY_ETH_DST = "eth.dst"
18 JSON_KEY_ETH_SRC = "eth.src"
19 JSON_KEY_FRAME = "frame"
20 JSON_KEY_FRAME_TIME = "frame.time"
21
22
23 def save_to_file(tbl_header, dictionary, filename_out):
24     """ Show summary of statistics of PCAP file
25         Args:
26             tbl_header: header for the saved table
27             dictionary: dictionary to be saved
28             filename_out: file name to save
29     """
30     # Appending, not overwriting!
31     f = open(filename_out, 'a')
32     # Write the table header
33     f.write("\n\n" + str(tbl_header) + "\n");
34     # Iterate over dictionary and write (key, value) pairs
35     #for key, value in dictionary.iteritems():
36     for key in sorted(dictionary):
37         f.write(str(key) + ", " + str(dictionary[key]) + "\n")
38
39     f.close()
40     print "Writing output to file: ", filename_out
41
42
43 def main():
44     """ Main function
45     """
46         if len(sys.argv) < 5:
47                 print "Usage: python", sys.argv[0], "<input_file> <output_file> <device_name> <mac_address>"
48                 return
49         # Parse the file for the specified MAC address
50         time_freq = parse_json(sys.argv[1], sys.argv[4])
51         # Write statistics into file
52         save_to_file(sys.argv[3], time_freq, sys.argv[2])
53         print "====================================================================="
54         for time in time_freq.keys():
55                 print time, " => ", time_freq[time]
56         print "====================================================================="
57
58
59 # Convert JSON file containing DNS traffic to a map in which a hostname points to its set of associated IPs.
60 def parse_json(file_path, mac_address):
61     """ Show summary of statistics of PCAP file
62         Args:
63             file_path: path of the read file
64             mac_address: MAC address of a device to analyze
65     """
66         # Maps timestamps to frequencies of packets
67         time_freq = dict()
68         with open(file_path) as jf:
69                 # Read JSON.
70         # data becomes reference to root JSON object (or in our case json array)
71                 data = json.load(jf)
72                 # Loop through json objects in data
73                 # Each entry is a pcap entry (request/response (packet) and associated metadata)
74                 for p in data:
75                         # p is a JSON object, not an index
76                         layers = p[JSON_KEY_SOURCE][JSON_KEY_LAYERS]
77                         # Get timestamp
78                         frame = layers.get(JSON_KEY_FRAME, None)
79                         date_time = frame.get(JSON_KEY_FRAME_TIME, None)
80                 # Get into the Ethernet address part
81                         eth = layers.get(JSON_KEY_ETH, None)
82                         # Skip any non DNS traffic
83                         if eth is None:
84                                 print "[ WARNING: Packet has no ethernet address! ]"
85                                 continue
86                     # Get source and destination MAC addresses
87                         src = eth.get(JSON_KEY_ETH_SRC, None)
88                         dst = eth.get(JSON_KEY_ETH_DST, None)
89                         # Get just the time part
90                         date_time_obj = parser.parse(date_time)
91                         # Remove the microsecond part
92                         time_str = str(date_time_obj.time())[:8]
93                         print str(time_str) + " - src:" + str(src) + " - dest:" + str(dst)
94                         # Get and count the traffic for the specified MAC address
95                         if src == mac_address or dst == mac_address:
96                             # Check if timestamp already exists in the map
97                             # If yes, then just increment the frequency value...
98                             if time_str in time_freq:
99                                 time_freq[time_str] = time_freq[time_str] + 1
100                             else: # If not, then put the value one there
101                                 time_freq[time_str] = 1
102         return time_freq
103
104 if __name__ == '__main__':
105         main()
106