The Basics of lsof
The command name "lsof" is an acronym for "list open files".
usage: [-?abhlnNoOPRstUvV] [+|-c c] [+|-d s] [+D D] [+|-f[cgG]] [-F [f]] [-g [s]] [-i [i]] [+|-L [l]] [+|-M] [-o [o]] [-p s] [+|-r [t] [-S [t]] [-T [t]] [-u s] [+|-w] [-x [fl]] [--] [names]
lsof has a truly staggering number of options. You can use it to get information about devices on your system, what a given user is touching at any given point, or even what files or network connectivity a process is using.
The lsof command outputs the following information
Command: The command name
PID: Process ID of the process
User: Owner of the process
FD: File Descriptor definition
Type: Type of the file descriptor
Device: Device number
Size/Off: Dimension of the file or the offset (suffix
0t
is the offset)Node: Node description of the local file; this could be the number of local file, TCP, UDP, STR(Stream)
Name: Name of the mount point where file resides
Although on first glance it may not seem to be the best of the tools, when one remembers that everything in linux is a file, the commands worth starts increasing exponentially.
When used without any args, it returns a long list of all the open files, which is seldom helpful. Thus it is usually used with the plethora of flags and arguments it supports, majorly in troubleshooting tasks for linux.
[!NOTE] Letter after FD
- There may be a letter after the file descriptor which represents how the file is locked. For example 'u' represents that the file is read and write locked, whereas 'R' represents read lock.
[!warning] Use SUDO
- The lsof command when not given the correct permissions like sudo doesn't return an error but just an empty buffer. So, during troubleshooting it is advisable to run the command with the superuser or elevated permissions.
Some useful flags and arguments
For Objects in the file system
One can search to check if a certain file is open or not using
lsof <filename>
To check all the open files in a directory
lsof +d <path_to_directory>
To also search the child directories
lsof +D <path_to_directory>
To show all the files opened by a user
lsof -u <user>
To get things a process has open using processID
lsof -p <processID>
To get things a command has open
lsof -c <command>
To combine two lsof commands (-a adds two searches)
lsof +d . -a -c <command>
For Networking
See open connections
lsof -i
To search with port number
lsof -i :<port_number>
To search with port number but without default name and instead of port number showing in the output
lsof -Pi :<port_number>
To show ip address instead of domain name in the output
lsof -ni
To search by an individual IP
lsof -i @<ip_address>