lsof is the Linux/Unix Super tool. I use it most for getting network connection related information from a system, but that’s just the beginning for this amazing and little-known application. The tool is aptly called lsof because it “lists open files”. And remember, in Unix just about everything (including a network socket) is a file.
Synopsis:
$ lsof [ -?abChlnNOPRstUvVX ] [ -A A ] [ -c c ] [ +|-d d ] [ +|-D D ] [ +|-f [cfgGn] ] [ -F [f] ] [ -g [s] ] [ -i [i] ] [ -k k ] [ +|-L [l] ] [ -m m ] [ +|-M ] [ -o [o] ] [ -p s ] [ +|-r [t] ] [ -S [t] ] [ -T [t] ] [ -u s ] [ +|-w ] [ -- ] [names]
lsof in action:
1) Show all connections with -i:
$ lsof -i
Show only TCP (works the same for UDP)
$ lsof -iTCP
Port shows all networking related to ssh
$ lsof -i :22
To show connections to a specific host
$ lsof -i@192.168.1.1
Show connections based on the host and the port using
$ lsof -i@192.168.1.1:22
Grep for “LISTEN” shows what ports your system is waiting for connections
$ lsof -i| grep LISTEN
Grep for “ESTABLISHED” shows current active connections
$ lsof -i| grep ESTABLISHED
2) Working with Users, Processes, and Files
Show what a given user has open using -u
$ lsof -u jonboy60
See what files and network connections a command is using with -c
$ lsof -c httpd
Pointing to a file shows what’s interacting with that file
$ lsof /var/log/messages
The -p switch lets you see what a given process ID has open,good for learning more about unknown processes
$ lsof -p 10075
The -t option returns just a PID
$ lsof -t -c Mail
$ ps aux | grep Mail
3) Advanced Usage
Using-a allows you to combine search terms, so the query below says, “show me everything running on my localhost”
$ lsof -a -u jonboy60 -i @192.168.1.1
Using the -t and -c options together you can HUP processes
$ kill -HUP `lsof -t -c sshd`
You can also use the -t with -u to kill everything a user has open
$ kill -9 `lsof -t -u jonboy60`
Certain applications listen on many different ports, such as the Berkeley Internet Name Daemon (BIND) named daemon.
$ lsof -i -nP | grep ^named
Conclusion:
Using lsof to troubleshoot serious system problems, without wasting time going through /proc and trying to find relevant system information, when it’s all there, hidden under just one mighty command.
~

