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".

Example running lsof -u root

lsof-u root

The command above will show you all "root's user" open files.

 

lsof -a -p "PID".

lsof -a -p 1

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 "/var/log/filename.log".

lsof /var/log/messages

lsof /var/log/messages

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.

[[email protected]:~]#-> 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

Senior Professional Network and Computer Systems Engineer during work hours and father when home.

Andrea strives to deliver outstanding customer service and heaps of love towards his family.

In this Ad-sponsored space, Andrea shares his quest for "ultimate" IT knowledge, meticulously brought to you in an easy to read format.

4 useful lsof commands explained
Rate this post

Ask me anything