Linux One Liner – netstat

Oneliner

One liner is individual Linux commands can be combined in the command line, to accomplish tasks that otherwise would require shell scripts to be written.

The following one liner is commonly required for us to find the IP, which is abusing to the server, means making more connections. Following command will print the list of IP’s with the number of connections in the first column. I will give an explanation of the following one liner, so that you can understand it and can be used for future without copy pasting the command. Also can be alter it for getting required results.

netstat -plan  | grep :80  | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nk1
netstat -plan  | grep :80   ---(1)

It will print all connections which are related to port 80, irrespective of incoming or outgoing. In web servers most of them are incoming only, but if some cases it may vary depending on the server configuration.

netstat -plan  | grep :80  | awk '{print $5}'  ---(2)

Printing the Fifth column ( field ) from the result of the first command. Which is normally the outside ip, which is connecting to the server on port 80. If the server is configured with proxying like nginx, the field will contain the server ip itself. Just compare the results of the commands to find the difference.

netstat -plan  | grep :80  | awk '{print $5}' | cut -d: -f1  ---(3)

Output of command 2 is like ip:port, so we need to cut the ip from it using the delimiter “:” and print the first field (IP).

netstat -plan  | grep :80  | awk '{print $5}' | cut -d: -f1 | sort | uniq -c  ---(4)

Here I’m adding two commands together, sort and uniq. Inorder to get the unique count, the input to “uniq” command should be sorted, so we are adding a sort inbetween the previous command output and “uniq”. The option “-c” will print the count in first column.

netstat -plan  | grep :80  | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nk1  ---(5)

The last and final is again a “sort” command, which will sort the first field based on numeric sort.

-n ----- Numeric sort
-k1  --- Sorting the first field

In addition to the above we can add a tail at the end to print only the last 10 ip’s with more connections only.

About Suhesh KS 24 Articles
Mr. Suhesh KS is Linux System Administrator by profession with 11 Years of work experience in Linux system administration in web hosting, data center and data warehousing industry and have worked with reputed support companies. He has wide range of skills include team management, system administration ( Linux ), programming ( bash, perl, php, java ), web hosting, data center support, seo analysis.