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