Linux lsof Command: Complete Guide and Reference

Master the Linux lsof command with this comprehensive guide covering installation, syntax, practical examples, and advanced usage for system administration.

Linux lsof Command: Complete Guide and Reference

Table of Contents

1. [Introduction](#introduction) 2. [Installation](#installation) 3. [Basic Syntax](#basic-syntax) 4. [Command Options](#command-options) 5. [Output Format](#output-format) 6. [Practical Examples](#practical-examples) 7. [Advanced Usage](#advanced-usage) 8. [Network Monitoring](#network-monitoring) 9. [Process Management](#process-management) 10. [File System Analysis](#file-system-analysis) 11. [Security Applications](#security-applications) 12. [Performance Considerations](#performance-considerations) 13. [Common Use Cases](#common-use-cases) 14. [Troubleshooting](#troubleshooting)

Introduction

The lsof command, which stands for "List Open Files," is a powerful diagnostic tool available on Unix-like systems including Linux. It displays information about files that are currently opened by processes running on the system. In Unix-like systems, everything is treated as a file, including regular files, directories, network sockets, pipes, devices, and more. This makes lsof an incredibly versatile tool for system administration, debugging, and security analysis.

The command provides detailed information about which processes have opened which files, network connections, and other system resources. This capability makes it invaluable for troubleshooting issues related to file access, network connections, and resource usage.

Installation

Ubuntu/Debian Systems

`bash sudo apt update sudo apt install lsof `

CentOS/RHEL/Fedora Systems

`bash

For CentOS/RHEL 7 and earlier

sudo yum install lsof

For CentOS/RHEL 8+ and Fedora

sudo dnf install lsof `

Arch Linux

`bash sudo pacman -S lsof `

macOS

`bash

Usually pre-installed, but can be installed via Homebrew

brew install lsof `

Basic Syntax

`bash lsof [options] [names] `

The basic syntax allows for various combinations of options and file/process names to filter the output according to specific requirements.

Command Options

Primary Options Table

| Option | Description | Example Usage | |--------|-------------|---------------| | -a | AND logic for multiple conditions | lsof -a -u user -c process | | -c | List files opened by processes with specified name | lsof -c apache | | -d | List files with specified file descriptor | lsof -d 1 | | -f | Inhibit the listing of kernel file structure info | lsof -f -- /path/file | | -g | List files opened by processes with specified PGID | lsof -g 1234 | | -i | List network connections | lsof -i :80 | | -n | Don't resolve network numbers to names | lsof -n -i | | -o | Display file offset | lsof -o | | -p | List files opened by specified PID | lsof -p 1234 | | -P | Don't resolve port numbers to names | lsof -P -i | | -r | Repeat mode with specified delay | lsof -r 5 | | -s | Display file size or protocol info | lsof -s | | -t | Terse output (PID only) | lsof -t -i :22 | | -u | List files opened by specified user | lsof -u username | | -v | Verbose mode | lsof -v | | +D | Recursively search directory | lsof +D /var/log | | +d | Search directory (non-recursive) | lsof +d /tmp |

Network-Specific Options

| Option | Description | Example | |--------|-------------|---------| | -i4 | IPv4 connections only | lsof -i4 | | -i6 | IPv6 connections only | lsof -i6 | | -iTCP | TCP connections only | lsof -iTCP | | -iUDP | UDP connections only | lsof -iUDP | | -i:port | Connections on specific port | lsof -i:22 | | -i@host | Connections to/from specific host | lsof -i@192.168.1.1 |

Output Format

The standard lsof output contains the following columns:

Output Columns Table

| Column | Description | Example Value | |--------|-------------|---------------| | COMMAND | Process name (truncated to 9 characters) | apache2 | | PID | Process ID | 1234 | | TID | Task ID (thread ID) | 5678 | | USER | Username of process owner | www-data | | FD | File descriptor | 3u, cwd, txt | | TYPE | File type | REG, DIR, CHR, IPv4 | | DEVICE | Device numbers | 8,1 | | SIZE/OFF | File size or offset | 1024 | | NODE | Inode number | 123456 | | NAME | File name or connection details | /var/log/apache2/access.log |

File Descriptor (FD) Values

| FD Value | Meaning | |----------|---------| | cwd | Current working directory | | txt | Program text (executable code) | | mem | Memory-mapped file | | mmap | Memory-mapped device | | pd | Parent directory | | rtd | Root directory | | 0r | File descriptor 0 opened for reading | | 1w | File descriptor 1 opened for writing | | 2u | File descriptor 2 opened for read/write |

File Type Values

| Type | Description | |------|-------------| | REG | Regular file | | DIR | Directory | | CHR | Character device | | BLK | Block device | | FIFO | Named pipe | | LINK | Symbolic link | | IPv4 | IPv4 network connection | | IPv6 | IPv6 network connection | | unix | Unix domain socket |

Practical Examples

Basic File Listing

`bash

List all open files (warning: produces extensive output)

lsof

List files opened by a specific process

lsof -c firefox

List files opened by multiple processes

lsof -c firefox -c chrome

List files opened by a specific PID

lsof -p 1234

List files opened by multiple PIDs

lsof -p 1234,5678 `

User-Based Queries

`bash

List files opened by a specific user

lsof -u john

List files opened by multiple users

lsof -u john,mary

List files NOT opened by a specific user

lsof -u ^john

Combine user and process filters (AND logic)

lsof -a -u john -c firefox `

Directory and File Queries

`bash

List processes using files in a directory (non-recursive)

lsof +d /var/log

List processes using files in a directory (recursive)

lsof +D /home/user

List processes using a specific file

lsof /var/log/syslog

List processes using files matching a pattern

lsof /var/log/*.log `

Network Connection Analysis

`bash

List all network connections

lsof -i

List connections on a specific port

lsof -i :22 lsof -i :80

List TCP connections only

lsof -iTCP

List UDP connections only

lsof -iUDP

List connections to a specific host

lsof -i@192.168.1.100

List listening ports

lsof -i -sTCP:LISTEN

List established connections

lsof -i -sTCP:ESTABLISHED `

Advanced Usage

Combining Options with Logic

`bash

AND logic: files opened by user 'apache' AND process 'httpd'

lsof -a -u apache -c httpd

OR logic (default): files opened by user 'apache' OR process 'httpd'

lsof -u apache -c httpd

Complex combination: TCP connections by specific user

lsof -a -u john -iTCP

Files in /tmp opened by root user

lsof -a -u root +d /tmp `

Output Formatting and Control

`bash

Terse output (PIDs only)

lsof -t -i :22

No header line

lsof -h

Suppress kernel warnings

lsof -w

Don't resolve hostnames

lsof -n -i

Don't resolve port numbers

lsof -P -i

Both numeric (no name resolution)

lsof -nP -i `

Repeat Mode for Monitoring

`bash

Monitor network connections every 5 seconds

lsof -r 5 -i

Monitor file access in directory every 2 seconds

lsof -r 2 +d /var/log

Monitor with incremental output (only changes)

lsof -r 1 -i :80 `

Network Monitoring

Port Analysis

`bash

Find what's listening on port 80

lsof -i :80

Find all listening services

lsof -i -sTCP:LISTEN

Find established SSH connections

lsof -i :22 -sTCP:ESTABLISHED

Monitor network activity

lsof -i -r 2 `

Connection State Monitoring

`bash

List all TCP connection states

lsof -iTCP -s

Specific connection states

lsof -iTCP:LISTEN lsof -iTCP:ESTABLISHED lsof -iTCP:CLOSE_WAIT `

Network Security Analysis

`bash

Find processes with network connections

lsof -i -n -P

Identify suspicious connections

lsof -i -n -P | grep -E "(ESTABLISHED|LISTEN)"

Monitor for new connections

lsof -r 1 -i -n -P `

Process Management

Process Analysis

`bash

Find all files opened by a process

lsof -p $(pgrep firefox)

Find processes using deleted files

lsof | grep "(deleted)"

Find processes with many open files

lsof | awk '{print $2}' | sort | uniq -c | sort -nr | head -10

Kill processes using a specific file

kill $(lsof -t /path/to/file) `

Resource Usage Analysis

`bash

Count open files per process

lsof -n | awk '{print $1}' | sort | uniq -c | sort -nr

Find processes with most network connections

lsof -i -n | awk '{print $1}' | sort | uniq -c | sort -nr

Memory-mapped files

lsof | grep mem `

File System Analysis

Disk Usage and File Access

`bash

Find processes preventing umount

lsof +D /mount/point

Find deleted but still open files

lsof +L1

Large files currently open

lsof -s | sort -k7 -nr | head -10

Find processes writing to log files

lsof +d /var/log | grep -w w `

Device and Special File Analysis

`bash

Processes using character devices

lsof | grep CHR

Processes using block devices

lsof | grep BLK

Processes using pipes

lsof | grep FIFO

Unix domain sockets

lsof -U `

Security Applications

Security Monitoring

`bash

Monitor for unauthorized network access

lsof -i -n -P | grep -v "127.0.0.1\|::1"

Find processes with unusual network activity

lsof -i -n -P | awk '$8 ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+:/ {print $1, $2, $8}'

Identify processes accessing sensitive files

lsof /etc/passwd /etc/shadow /etc/sudoers

Monitor for privilege escalation

lsof -u root | grep -E "(tmp|home)" `

Forensic Analysis

`bash

Capture current state for analysis

lsof -n -P > system_state_$(date +%Y%m%d_%H%M%S).txt

Find processes with network connections to external hosts

lsof -i -n -P | grep -vE "(127\.0\.0\.1|::1|0\.0\.0\.0)"

Identify processes using configuration files

lsof | grep -E "\.(conf|cfg|ini)$" `

Performance Considerations

Optimization Techniques

The lsof command can be resource-intensive on systems with many open files. Here are optimization strategies:

`bash

Limit scope to reduce execution time

lsof -u specific_user

Use specific filters instead of broad searches

lsof -i :80 # Instead of lsof -i

Avoid recursive directory searches on large filesystems

lsof +d /specific/dir # Instead of lsof +D /

Use numeric output to avoid DNS lookups

lsof -n -P -i `

Performance Monitoring

`bash

Time lsof execution

time lsof > /dev/null

Monitor lsof resource usage

/usr/bin/time -v lsof > /dev/null

Limit output for performance

lsof | head -1000 `

Common Use Cases

System Administration Tasks

`bash

Find why a filesystem won't unmount

sudo lsof +D /mount/point

Identify processes using excessive file descriptors

for pid in $(ps -eo pid --no-headers); do count=$(lsof -p $pid 2>/dev/null | wc -l) if [ $count -gt 100 ]; then echo "PID $pid: $count open files" fi done

Find processes with deleted executables (potential security issue)

lsof | grep "(deleted)" | grep txt

Monitor log file access

lsof +d /var/log | grep -E "(w|u)" `

Development and Debugging

`bash

Debug application file access

lsof -p $(pgrep myapp) -r 1

Find shared libraries used by a process

lsof -p $(pgrep myapp) | grep "\.so"

Monitor database connections

lsof -i :3306 # MySQL lsof -i :5432 # PostgreSQL

Find memory leaks (processes with many deleted files)

lsof | grep "(deleted)" | awk '{print $2}' | sort | uniq -c | sort -nr `

Network Troubleshooting

`bash

Find what's using a port

lsof -i :port_number

Identify connection bottlenecks

lsof -i | grep ESTABLISHED | wc -l

Find processes with TIME_WAIT connections

lsof -i -sTCP:TIME_WAIT

Monitor connection establishment

lsof -i -sTCP:SYN_SENT -r 1 `

Troubleshooting

Common Issues and Solutions

#### Permission Denied Errors `bash

Run with sudo for full system visibility

sudo lsof

Some files may not be accessible even with sudo

lsof -w # Suppress warnings `

#### Performance Issues `bash

Use more specific filters

lsof -u username # Instead of lsof

Avoid deep directory recursion

lsof +d /specific/path # Instead of lsof +D / `

#### Output Too Large `bash

Limit output

lsof | head -100

Filter specific information

lsof -i | grep :80

Use terse output

lsof -t -i :22 `

Error Messages and Solutions

| Error Message | Cause | Solution | |---------------|-------|----------| | lsof: WARNING: can't stat() file | File permissions or missing file | Use -w to suppress warnings | | lsof: no pwd entry for UID | User doesn't exist in /etc/passwd | Normal for system processes | | lsof: avoiding stat() for path | Performance optimization | Use -s to force stat() |

Best Practices

1. Use Specific Filters: Always use the most specific filters possible to reduce execution time and output volume.

2. Combine with Other Tools: Use lsof output with tools like grep, awk, and sort for better analysis.

3. Regular Monitoring: Set up regular lsof checks for security and performance monitoring.

4. Documentation: Document your lsof commands and their purposes for future reference.

5. Script Integration: Integrate lsof into monitoring scripts for automated system analysis.

Example monitoring script: `bash #!/bin/bash

System monitoring script using lsof

Check for processes with too many open files

echo "Processes with >1000 open files:" for pid in $(ps -eo pid --no-headers); do count=$(lsof -p $pid 2>/dev/null | wc -l) if [ $count -gt 1000 ]; then cmd=$(ps -p $pid -o comm --no-headers) echo "PID $pid ($cmd): $count files" fi done

Check for unusual network connections

echo "External network connections:" lsof -i -n -P | grep -vE "(127\.0\.0\.1|::1|0\.0\.0\.0)" | head -10

Check for deleted but open files

echo "Deleted files still open:" lsof +L1 | head -5 `

The lsof command is an essential tool for system administrators, developers, and security professionals. Its ability to provide detailed information about file and network usage makes it invaluable for troubleshooting, monitoring, and security analysis. By mastering its various options and understanding its output format, users can effectively diagnose and resolve a wide range of system issues.

Tags

  • System Monitoring
  • file management
  • linux-commands
  • lsof
  • network-analysis

Related Articles

Popular Technical Articles & Tutorials

Explore our comprehensive collection of technical articles, programming tutorials, and IT guides written by industry experts:

Browse all 8+ technical articles | Read our IT blog

Linux lsof Command: Complete Guide and Reference