lsof cheat sheet
Basic options
Option | What the option does |
---|---|
-a | Consider all selectors to be ‘AND’ to reduce output |
-c | Match by process name |
-i | Match by internet address, or in other words, network connections |
-i4 | Limit to IPv4 |
-i6 | Limit to IPv6 |
-n | Do not resolve IP addresses to hostnames |
-P | Do not resolve port numbers to service names |
-u | Limit files to a specific user |
Creating a shell script? Then we suggest using the long format option, as this improves the readability. For quick use of on the command-line consider using the short notation of the related option.
Performing specific requests
Open files in a specific directory
Want to see what is opened within a directory, use the +D option.
lsof +D /var/log/journal
By mount point
Sometimes it may be useful to learn what files are open to a specific mount point, like a NAS. Use the +f followed by two dashes, to signal lsof that a specific path is coming.
lsof +f -- /mnt/backup/
NFS
When using NFS, we can query all open files.
lsof -N
Open files by process id (PID)
lsof -p 1234
Open files by process name
lsof -c nginx
Open files by user
On a web server you may want to check what files are opened for the user account that runs the web server.
lsof -u www-data
Deleted files
Sometimes files can be opened, even though they are already deleted. To uncover them, use lsof [more info] with the option +L1. The ‘1’ defines the boundary, so all files with less than 1 link are shown.
lsof +L1
Open network connections
As everything is a file on Linux, the related sockets are also visible as files. To query them, select one or more ports.
lsof -i :80,443
Another way is by protocol.
lsof -i UDP -i TCP
To only show listening TCP services, limit the output. To avoid any lookups (hostname or service name), add -n and -P.
lsof -n -P -i TCP -sTCP:Listen
Open connections for a single IP address can be specified as well, optionally with a port.
lsof -n -P -i @192.168.1.1:22
Combine options
Use the -a option to tell lsof to combine the options (logical AND operator). For example to show only files (regular and directory) that are opened by the nginx process, we can combine it to a command like this.
lsof -a -c nginx -r 3 /
By defining the root path, only normal files are displayed. That is, if they are opened by the process with the name ’nginx’. The -r defines a refresh rate, so that we can see the open files by nginx at a given moment in time.