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
Output:
     25 195.150.23.130
     25 67.222.164.140
     28 95.34.20.117
     31 72.45.232.204
     34 209.56.4.6

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
459

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 123.231.146.176:80          92.35.20.117:12205          TIME_WAIT   –                  
tcp        0      0 123.231.146.176:80          92.35.20.117:64428          TIME_WAIT   –                  
tcp        0      0 123.231.146.190:80          92.35.20.117:20645          TIME_WAIT   –                  
tcp        0   2885 123.231.146.176:80          92.35.20.117:57267        ESTABLISHED 10439/nginx: worker
tcp        0      0 123.231.146.190:80          92.35.20.117:50365          TIME_WAIT   –                  
tcp        0      0 123.231.146.176:80          92.35.20.117:52670          TIME_WAIT   –                  
tcp        0      0 123.231.146.176:40214       69.4.187.136:80             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:
92.35.20.117:12205
92.35.20.117:64428
92.35.20.117:20645
92.35.20.117:57267

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