lsof – handy linux command tool with examples

lsof command lists all open files

lsof can save you a lot of time and hassle if you are just checking on the status of your host, but more importantly can give you valuable information and point you in the right direction when
troubleshooting what exactly your host is up to.

Linux treats mostly everything as a file. Sockets, devices, directories can all be viewed as files. When a process or application interacts with these files it has to “open” them.
Using lsof command you can deep dive into and see what your system is up to. Checking out the man pages on lsof is a great start to know about this command and the options it provides.

Some examples are included to show you the wealth of information that can be leveraged from this handy tool.

>List all open files of active processes :

#lsof (it will show long listing of open files along with columns like Command, PID, USER, FD, TYPE etc.)

>List all network connections ‘LISTENING & ESTABLISHED’:

#lsof -i (this will show all tcp and udp connections in listen & established state)

>List specific network connections types (TCP/UDP):

#lsof -i tcp (this will list tcp connections)
#lsof -i udp (this will list udp connections)

>List TCP connections that are in listening state:

#lsof -i -s tcp:listen

>Find the process running on specific port/service:

#lsof -i :80 (this will show what process is running on port 80)
#lsof -i :http (same as above, here we are just mentioning the service name)

This image has an empty alt attribute; its file name is image-7.png

We can even filter for tcp/udp port by using

#lsof -i tcp:<port>
#lsof -i udp:<port>

This image has an empty alt attribute; its file name is image-9.png

You can even club multiple ports or services

#lsof -i :80,22
#lsof -i :http,ssh

>Find open files by user:

#lsof -u apache
#lsof -u apache,puppet ( multiple users can be clubbed )

>Display recursively all the files opened in a directory:

#lsof +D <directory> (this will show all open files in a directory recursively)

For Non-recursive i.e., for top level of directory use below option.

#lsof +d <directory>

This image has an empty alt attribute; its file name is image-12-1024x230.png

Have a look at the man page of command lsof (#man lsof) which would give a lot more options to use based on requirements.

Leave a Reply

Your email address will not be published.