Innovate | Connect | Transform
ContactService statusUSD $

GICT knowledge base

How to Use the lsof Command to List Open Files and Ports in Linux

Published

LinuxLinux and CommandsSystem Administration

On Linux, almost everything is treated as a file—regular documents, directories, devices, and even network sockets. When you want to know which files a process is using, who is holding a file open, or which program is listening on a specific network port, the lsof (List Open Files) command is the go-to tool for administrators, developers, and support teams. lsof gives you a live, detailed view into how your system’s resources are being used and by whom.

In this article, you will learn exactly what lsof is, how it works, how to install it, and how to use its many options for effective file and network management. You will see practical, real-world examples, learn how to combine lsof with other powerful Linux commands, and understand best practices for troubleshooting and securing your system.

Prerequisites

  • Access to a Linux terminal
  • Sudo privileges (for system-wide inspection)
  • Basic command-line experience

What Is lsof and Why Use It?

lsof stands for “List Open Files.” In Linux, open files include not only text files and programs but also directories, device files, pipes, and network sockets. Each running process can have one or more of these “files” open at a time.

Why is this important?

  • Troubleshooting: Find out which process is holding a file or device “busy” so you can safely unmount or remove it.
  • Security: Discover unfamiliar or suspicious network connections and see which process is responsible.
  • Resource Management: Track file handles and open ports to avoid exhaustion of system resources.
  • Auditing: Understand which users are accessing sensitive files.

Installing lsof

Most distributions include lsof by default. To check if it’s installed:

$ lsof -v

If you see version information, you are ready to use the tool. If you see “command not found,” install it as follows:

On Ubuntu/Debian

$ sudo apt update
$ sudo apt install lsof

On CentOS/RHEL

$ sudo yum install lsof

On Fedora

$ sudo dnf install lsof

Understanding lsof Output

A typical lsof output includes the following columns:

Column Description
COMMAND Name of the command/process
PID Process ID
USER Owner of the process
FD File descriptor (e.g., cwd, txt, mem, 0u for stdin, 1w for stdout, etc.)
TYPE Type of file (REG for regular file, DIR for directory, CHR for character device, etc.)
DEVICE Device identifier
SIZE/OFF Size or offset of file
NODE Inode number (file system node)
NAME Name of the file or resource

When you run lsof with no arguments, you get a massive snapshot of all open files and resources—a lot to process! Use filtering and search options to focus on what matters.

Basic Usage Examples

Step 1: List All Open Files

$ lsof
$ lsof | less

Step 2: List Open Files for a Specific User

$ lsof -u username
$ lsof -u alice

Lists all files and network sockets opened by Alice.

Step 3: List Open Files by a Specific Process

First, find the PID:

$ ps aux | grep processname

Then:

$ lsof -p PID

Replace PID with the actual process ID.

Step 4: List Open Files in a Specific Directory

$ lsof +D /path/to/directory

Useful when unmounting a USB drive, NFS share, or deleting directories.

Step 5: Investigate File Locks and “Busy” Files

$ lsof /mnt/myusb
$ lsof +D /mnt/myusb

Kill the process or close the application holding the file open, then try unmounting or deleting again.

Monitoring Network Activity with lsof

Step 6: Show All Active Network Connections

$ lsof -i

Step 7: Show Only TCP or UDP

$ lsof -i tcp
$ lsof -i udp

Step 8: Show Only Listening Ports

$ lsof -i -sTCP:LISTEN

Step 9: Find Which Process Is Using a Specific Port

$ lsof -i :8080
$ lsof -i :443

Step 10: See Connections to a Specific Host

$ lsof -i @192.168.1.100

Filtering lsof Output

Step 11: Filter by Command Name

$ lsof -c ssh

Step 12: Multiple Users or Exclusions

$ lsof -u alice,bob
$ lsof -u ^root

Step 13: Restrict to IPv4 or IPv6

$ lsof -i 4
$ lsof -i 6

Step 14: Filter by File Type

$ lsof -d cwd
$ lsof -a -d REG

Combining lsof with Other Tools

Step 15: Filter Further with grep

$ lsof -i | grep firefox
$ lsof | grep "/var/log"

Step 16: Count Open Files

$ lsof | wc -l

Step 17: Find Deleted but Open Files

$ lsof | grep deleted

Restart the holding process to release the file and reclaim space.

Advanced Techniques

Step 18: Output in Machine-Readable Format

$ lsof -F

Step 19: List Files Opened by All Instances of a Program

$ lsof -c nginx

Step 20: List Files Opened by a Group of PIDs

$ lsof -p 1234,5678,9012

Step 21: View Only Files with a Specific Extension

$ lsof | grep '\.log$'

Step 22: Audit All Open Files in /tmp

$ lsof +D /tmp

Step 23: Monitor File Usage Over Time

$ watch -n 2 'lsof -i :80'

Step 24: Script to Close Files Before Unmounting

#!/bin/bash
lsof +D /mnt/backup
echo "Closing all processes using /mnt/backup..."
for pid in $(lsof -t +D /mnt/backup); do
    kill "$pid"
done
umount /mnt/backup

Real-World Troubleshooting Scenarios

Step 25: Device or Directory Refuses to Unmount

$ umount /mnt/myusb
umount: /mnt/myusb: target is busy.
$ lsof +D /mnt/myusb

Step 26: Which Process Is Blocking a Port?

$ lsof -i :3306

Step 27: File System Is Full but Files Seem Deleted

$ lsof | grep deleted

Step 28: Unexpected Network Connections

$ lsof -i | grep ESTABLISHED

Performance and Security Considerations

Performance Tips

  • Avoid Recursive Directory Searches on Very Large Trees: lsof +D can be slow on deeply nested directories.
  • Use Filters to Limit Output: The more specific your options, the faster and more readable your results.

Security and Privacy

  • lsof shows information about all users’ processes if run as root.
  • Restrict access to lsof if you have untrusted users on your system.
  • Regularly audit with lsof to detect suspicious files or unexplained network activity.

lsof vs. Other Linux Tools

Tool Typical Use Example
lsof List all open files and ports lsof -i :80
netstat Show network connections and routing netstat -tulnp
ss Modern network socket stats and analysis ss -tulnp
fuser Identify process using a file or socket fuser -v /mnt/usb
ps List running processes ps aux

Best Practices Checklist

  • Always filter your output (-u, -p, -i, etc.) for relevance and speed.
  • Run sudo lsof for full visibility when troubleshooting system-wide issues.
  • Chain with grep, awk, or column for easy parsing and reporting.
  • Combine with watch for real-time monitoring.
  • Integrate lsof into scripts for automated diagnostics or cleanup.
  • Regularly audit your system’s open files and ports to detect anomalies.

Summary Table: Essential lsof Options

Option Description Example
-u user Files opened by user lsof -u alice
-p PID Files opened by process ID lsof -p 1234
+D dir Files opened under a directory (recursive) lsof +D /var/log
-i All open network files lsof -i
-i :PORT Processes using a specific port lsof -i :22
-c command Processes with command name prefix lsof -c ssh
-F Script-friendly, machine-readable output lsof -F
-d FD Filter by file descriptor lsof -d txt
-t Output only process IDs (PIDs) lsof -t +D /mnt/usb
-sTCP:LISTEN Only show listening TCP sockets lsof -i -sTCP:LISTEN

Conclusion

The lsof command is a critical tool for managing, troubleshooting, and securing Linux machines. Its ability to reveal which processes are using which files and ports provides transparency and control, helping you resolve common issues like locked files, busy devices, or occupied network ports. By learning to combine its powerful options with other Linux utilities, you can automate problem-solving, improve system security, and maintain a healthy Linux environment.

Regularly use lsof as part of your administrative routine, and it will become an indispensable ally in keeping your system running smoothly and securely.

Related guides

Account services are unavailable until the production backend is configured.