This short post introduces you 4 useful lsof commands by examples.
Due to their usefulness, I’d like to “remember to use” those commands more often.
lsof -u “username”.
The command above will show you all “root’s user” open files.
lsof -a -p “PID”.
lsof -a -p 1
-a is a simple AND operator. Used this way is the equivalent of “lsof -p 1“.
-p 1 limits the output to PID 1 (usually that is the kernel…). You get PIDs by running the ps command.
When you specify more than 1 lsof -X -Y command switches (ie. “lsof -p 1 -u johndoe“), by default lsof will perform an OR operation (ie. EITHER “PID = 1” OR “User = johndoe“).
IF you type, say, “lsof -p 1 -a -u johndoe“, lsof will filter your output by “PID = 1” AND “User = johndoe“.
lsof with a file parameter will show you who & what daemon is using the file (ie. the “messages“-log file).
On the above screenshot, /var/log/messages is opened by root thru rsyslogd (which has a PID of 1078).
lsof -i :TCP|UDP-PortRange.
[root@host:~]#-> lsof -i :1-100
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
sshd 1216 root 3u IPv4 11823 0t0 TCP *:ssh (LISTEN)
sshd 1216 root 4u IPv6 11827 0t0 TCP *:ssh (LISTEN)
sendmail 1240 root 4u IPv4 11922 0t0 TCP localhost:smtp (LISTEN)
sshd 1446 root 3r IPv4 22798 0t0 TCP 192.168.1.1:22->192.168.1.2:23494 (ESTABLISHED)
lsof -i :1-100
The above command (with a space-char after “-i“), queries your system about “what services are running on the first 100 ports”?
If you want to know only what TCP ports are in use, then type:
lsof -i tcp
That’ll show you all the open TCP ports.
My short examples are only the tip of the iceberg of what lsof can do.
lsof is extremely useful and has an extensive (and sometimes arcane) list of options and switches -- check for yourself at the lsof man page: http://linux.die.net/man/8/lsof