Use this command to get rid of All the hosts using web server.

#netstat -natp | grep :80 | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -n | tail

You can use this command on any other port that you want to search.
Let us break this command and explain the things to make it more understandable.

First of all – how many connections are there to the web server:

#netstat -natp | grep :80 | wc -l

In this case, the flags being used state the following:
-n” Numerical representation of the hosts rather than attempt to resolve to addresses
-a” All traffic (listening and non-listening sockets)
-t” TCP traffic only (UDP is a whole other ballgame)
-p” The PID of the process using the port – Just a course of habit for me – since I usually want to know
who is listening and taking up a port.
grep :80
Since this example deals with a web server, so we take port 80.
wc -l  # Count total number of lines.

A typical output for netstat -natp | grep :80 ::
tcp        0      0          TIME_WAIT   –                  
tcp        0      0          TIME_WAIT   –                  
tcp        0      0          TIME_WAIT   –                  
tcp        0   2885        ESTABLISHED 10439/nginx: worker
tcp        0      0          TIME_WAIT   –                  
tcp        0      0          TIME_WAIT   –                  
tcp        0      0             TIME_WAIT   –

Next in Command we have make the use of  “awk, sort, cut and uniq”  to get a
nice representation of the top port 80 tcp offenders.

awk ‘{print $5}’
Will give us the fifth column:

awk -F “:” ‘{print $1}’
cut -d: -f1

These two will basically do the same thing: in awk, the “-F” flag states the field delimiter (in this case the colon “:”) and print the first column.
With cut, the “-d” flag states the delimiter (in this case the colon), and “-f1” tells it to use the first field.
Now we finally have a simple clean list of lots of IPs.
All that is left is to sort them, count how many unique IPs there are and sort the output of that test.

sort | uniq -c | sort -n

First we must sort, otherwise uniq doesn’t work.
-c” tells uniq to count the occurrences of each unique object.
In sort, “-n” tells it to do a proper numerical sorting rather than alphabetical, otherwise “10″ will come before “2″.

Posted in: Linux.
Last Modified: November 19, 2013

Leave a reply