lsof is an increadibly powerful command-line utility for unix systems. It lists open files, displaying information about them. And since most everything is a file on unix systems, lsof can give sysadmins a ton of useful diagnostic data.
What are some of the most common and useful ways of using lsof, and which command-line switches are used for that?
Will display recursively all the files opened in a directory. +d for just the top-level.
This is useful when you have high wait% for IO, correlated to use on a particular FS and want to see which processes are chewing up your io.
lsof -i
will provide a list of open network sockets. The-n
option will prevent DNS lookups, which is useful when your network connection is slow or unreliable.See what files a running application or daemon has open:
Where pid is the process ID of the application or daemon.
lists the processes using files on the mount mounted at /mountpoint. Particularly useful for finding which process(es) are using a mounted USB stick or CD/DVD.
To show all networking related to a given
port
:To show connections to a specific host, use
@host
Show connections based on the host and the port using
@host:port
lsof -i@192.168.1.5:22grep
ping forLISTEN
shows what ports your system is waiting for connections on:Show what a given user has open using
-u
:See what files and network connections a command is using with
-c
The
-p
switch lets you see what a given process ID has open, which is good for learning more about unknown processes:The
-t
option returns just aPID
Using the
-t
and-c
options together you canHUP
processesYou can also use the
-t
with-u
to kill everything a user has openwill tell you what programs are listening on a specific port.