lsof Command on Linux

0
202

Linux is one of the most powerful platforms that offer the utmost control over your system. It comes up with a number of pre-installed tools that can be of tremendous power. “lsof” is such a command that’s available on almost all the UNIX/Linux systems.

“lsof” stands for “list open files”. Using this tool, you can identify what files are being used by which process/program. In the UNIX/Linux environment, every single thing is a file (pipes, directories, devices, sockets etc.). So, having a good knowledge of “lsof” can provide you with useful info in lots of scenarios.

Let’s check out some of the use cases of “lsof”.

“lsof” usage

The basic usage is listing all the open files that belong to all the active processes –

The purpose of using “sudo” is to list ALL the files that are actively being used. Otherwise, it may not properly identify all the files.

You can also check if a specific file is being used.

 

Suppose, you need to identify what processes are accessing the file(s) of a certain directory.

Here, “+D” indicates to include the subdirectories within the directory. If you don’t want to include them, then use “+d”.

Need to find out the file(s) a certain process is accessing? Then use the “-c” flag. The command structure will be –

“lsof” is capable of handling multiple “-c” flags.

You can also list the processes that are using a certain mount point. For this purpose, the following structure must be followed –

Not all the processes in your system run under a certain user. For example, “root”, “<account_username>” etc. You can also tell “lsof” to show the files that are being used as a certain user permission.

From the above example, need to exclude a certain user? Then you have to use “^” flag.

It’s also possible to list all the files a certain process is accessing. Use the “-p” flag in this case. Note that as the value for the flag “-p”, you need to provide the PID of that process

 

List all the network connections –

Another interesting ability of “lsof” is listing all the processes that are listening to a specific port. For example, you want to find out what processes are using the 25 port.

Need to scan a range of port, say, 1-25? Then the command structure will be the following one –

You can also filter your result by IPv4 and IPv6.

Need to find out all the available options of “lsof”? You can get the help of the man page.

You can also export the man page for future usage. Learn how to export Linux command output to a text file.

Enjoy!

Spread the love
  • 6
    Shares

PS. If you like this post please share it with your friends on the social networks using the buttons above.Thanks.

LEAVE A REPLY

Please enter your comment!
Please enter your name here