Monday, May 13, 2013

Bash One Liner to Get a Frequency Count for IP Connections with Netstat

So you want to see how many connections a given IP has open with netstat? Here's a quick Bash one-liner to get a frequency count for each IP. Note, this is for the external IP / foreign address, and it ignores what port they're connecting on, so 8.8.8.8:443 and 8.8.8.8:80 will be treated as two connections from 8.8.8.8.

So we run netstat with the -pan flags (word-ish sounding and easy to remember, shows the Program that's using the connection, All connections, Numeric version (instead of hostnames / URLs) ) and then we pipe it to awk, and print the 5th field (Foreign Address), then to cut where we discard the port numbers by telling it to print the first field before a colon (which separates the IP from the port). Then we pipe it to sort to organize it, pipe it to unique with the -c flag to get a count of how many times each IP shows up and then to sort again with the -n (sort numeric, very important) and -r flags so the highest count is at the op. And we're done!



netstat -pan | awk '{print $5}' | cut -d ":" -f 1 | sort | uniq -c | sort -nr 


You'll get something like this (IPs changed to protect the guilty): 



[root@example ~]# netstat -pan | awk '{print $5}' | cut -d ":" -f 1 | sort | uniq -c | sort -nr 
    483 127.0.0.1
    119 8.8.8.8
    104 8.8.8.9
     84 8.8.8.10
     70 8.8.8.11
...
[root@example ~]#

You can see the connection count on the left, 483 current connections from 8.8.8.8, 119 from 8.8.8.9 and so on.

No comments:

Post a Comment