List Open Files and Users Accessing Them on Your System | Using lsof for System Administration
Understanding the lsof Command in Linux
Introduction to File Management Issues
- The speaker addresses a common issue faced by Linux administrators: being unable to rename or move a file because it is open and in use.
- Introduces the
lsofcommand (List Open Files), which helps identify which files are currently open on a Linux system.
Basic Usage of lsof
- The basic command
lsofis executed, producing extensive output that includes various details about open files.
- Demonstrates how to limit output using the
headcommand to view only the first 10 lines, making it easier to analyze.
Understanding lsof Output
- The first line of output contains headers such as Command, PID (Process ID), User, etc., crucial for interpreting results.
- Explains that each line corresponds to an open file and emphasizes that everything in Linux is treated as a file.
Key Columns Explained
Command Column
- Describes the "Command" column, indicating which command is associated with each open file.
Process ID (PID)
- Defines PID as a unique identifier assigned to every running process on the system, managed by the init system (often systemd).
User Column
- Highlights the "User" column's importance for identifying which user created the process holding an open file.
Inode Number
- Discusses inode numbers that uniquely identify files without storing actual data but rather metadata like permissions and size.
Filtering Output with lsof
By User
- Shows how to filter results by user using
grep, allowing users to see only their own open files.
Using sudo for Comprehensive Access
- Emphasizes that executing
lsofwithsudoprovides access to all open files across users, revealing more comprehensive information.
Advanced Filtering Techniques
By Process Name
- Demonstrates filtering output based on specific processes using
lsof -c <process_name>, exemplified with Apache 2 installation.
By Process ID
- Illustrates narrowing down results further by specifying a process ID with
lsof -p <PID>for targeted insights into specific processes.
Real-world Application of lsof
Monitoring Active Connections
- Transitioning from local examples to real production systems shows practical applications of monitoring active connections via SSH and checking directory usage.
Identifying Users Listening to Content
- Uses an example where someone listens to a podcast episode; demonstrates how lsof can help decide when it's appropriate to reboot servers based on active connections.
Excluding Specific Users from Results
Using Exceptions in Queries
- Explains how adding a caret symbol before a username allows exclusion from results when searching for open files not owned by root.
Investigating Network Connections
Viewing IP Addresses of Active Users
- Shows how filtering can also be applied for network-related queries using IPv4 or IPv6 options within lsof commands.
Conclusion and Further Learning Opportunities