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.


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


Example:
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 @10.20.64.30:21 -R | grep TCP | sort -k7 -u
vsftpd  12355 12353 adevaraju    0u  IPv4 58945888       TCP ftpserver:ftp->r3aash01-d1.prod.domain:44760 (ESTABLISHED)
vsftpd  12605 12602 adevaraju    0u  IPv4 58946864       TCP ftpserver:ftp->stoash01-t1.prod.domain:25559 (ESTABLISHED)
vsftpd  13191 13189 adevaraju    0u  IPv4 58947254       TCP ftpserver:ftp->gtwash01.prod.domain:50426 (ESTABLISHED)
[root@ftpserver ~]#


Command to find how many connections the server has in port range 20 - 80:
# lsof -i @10.20.64.30:20-80 -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:
http://ashok-linux-tips.blogspot.com/2010/10/how-to-pid-associated-with-port-no.html

1 comment:

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

    ReplyDelete