Monday, July 25, 2011

How to find active TCP in Linux server ?

Situation:  You want to find all the Active TCP connections to a Linux machine for a given Port No. or a Port range. This you might want to do, to find any unauthorized access, to find the server utilization or for trouble-shooting purpose.

Solution:  Use 'lsof' or 'netstat' with appropriate switches. Here I illustrated about using 'lsof' as it will give more legible output when compare to 'netstat' command.

# lsof -i @[Server IP]:[Port no or Port-no range] -R | grep TCP | sort -k7 -u

For demonstration purpose, I logged-in to a Linux FTP server and connected it from 3 remote servers via FTP protocol (port: 21).

Command to find how many FTP connections the server has now:
[root@ftpserver~]# lsof -i @ -R | grep TCP | sort -k7 -u
vsftpd  12355 12353 adevaraju    0u  IPv4 58945888       TCP ftpserver:ftp-> (ESTABLISHED)
vsftpd  12605 12602 adevaraju    0u  IPv4 58946864       TCP ftpserver:ftp-> (ESTABLISHED)
vsftpd  13191 13189 adevaraju    0u  IPv4 58947254       TCP ftpserver:ftp-> (ESTABLISHED)
[root@ftpserver ~]#

Command to find how many connections the server has in port range 20 - 80:
# lsof -i @ -R | grep TCP | sort -k7 -u
[Output not shown]

PS: I have already written a post on using 'lsof' and 'netstat'. Please refer it as well:

1 comment:

  1. Awesome solution...way to go. thanks a ton !!!!