Nasser Heidari

2012-01-06

lsof: A Unix Utility You Should Know About

Filed under: Linux — Nasser Heidari @ 17:32
Tags:

LSOF lists information about files opened by processes. An open file may be a regular file, a directory, a NFS file, a block special file, a character special file, a shared library, a regular pipe, a named pipe, a symbolic link, a socket stream, an Internet socket, a UNIX domain socket, and many others. Since almost everything in Unix is a file, you can imagine how incredibly useful lsof is!

lsof in action:

– Find who’s using a file:
lsof /path/to/file

– List of Open files Per Process:
lsof -p

– List of open Files Per User:
lsof -u

– List of Open File Descriptors:
lsof -d

– List of Open Internet protocols & ports:
lsof -i

– Directory Search :
lsof +D

– Find all open files by program’s name:
lsof -c

Examples:
# lsof -u admin,nasser
This will list all the files that are open by users admin and nasser.

# lsof -c httpd
It the list open files for processes whose name begins with httpd.

# lsof -a -u nasser -c tcsh
-a means AND
The output will be list of files opened by tcsh, which is run under nasser user privilege.

# lsof -u ^root
The ^ character before root username will negates the match and causes lsof print all open files by all users who are not root.

# lsof -p ^1010
List all open files by all the processes EXCEPT process with PID 1010.

# lsof -i tcp
List all TCP network connections.

# lsof -i udp
List all UDP network connections.

# lsof -i :22
The :22 option to -i makes lsof find processes using TCP or UDP port 25.

# lsof -i tcp:80
Finds who’s using a TCP port 80.

# lsof -a -u nasser -i
Will Find all network activity by user nasser.

# lsof -U
List all Unix domain socket files.

# lsof -g 1234
List all files for processes with a specific group id.

# lsof -r 5 -i tcp:22
The -r option makes lsof repeatedly list files until interrupted.

Have Fun.