and report how many network packets have come from each IP address. Now, we should be deciding on the scripting language.
Using a shell script is definitely going to be cumbersome. Instead, we can use Python here. There is a simple and nice data structure in Python called ‘Dictionary.’ That would help us a lot.
Now, our job looks much simpler now. Using Python, we will open the output file, read each line from the file, and insert the IP addresses in the dictionary. And if an IP address comes multiple times, we will simply increase the count.
The script
We can use the following shell script first, which would invoke the Python code :
#!/bin/bash
while :
do
sudo tshark -i eth1 -T fields -e ip.src -a duration:15 > ipfile
python ip.py
done
This is really a short and simple one. It just uses the utility tshark, redirects its output to ipfile and calls the python program ip.py.
The Python code ip.py is given below :
#!/usr/bin/python
with open("ipfile", "r") as f:
dict = {}
for line in f:
line = line.rstrip();
dict[line] = dict.get(line, 0) + 1;
for x in dict:
print 'IP : ', x, '\tcount : ', dict[x];
The Python code opens the file ipfile, reads each line, strips the newline character at the end of each line, and gets the IP address. Then, it inserts the IP address in the dictionary and increases the count for multiple entries.
Running the script
If we run the code above, it will report network traffic coming from each IP address.
Here is a sample output:
# ./ip_analyzer.s Capturing on eth1 91 packets captured IP : 74.100.250.179 count : 5 IP : 200.84.22.26 count : 3 IP : 192.168.1.10 count : 42 IP : 91.179.89.25 count : 29 IP : 198.100.200.25 count : 2 IP : 192.68.1.1 count : 1 IP : 201.63.23.83 count : 1 IP : 72.100.188.135 count : 3
The script will throw outputs in each 15-second interval and report how much traffic is coming from each IP address. You can also make further improvements in the script to filter traffic in a better way.








































0 Comments