LiSt Open Files is a useful and powerful tool that will show you opened files. In Unix everything is a file: pipes are files, IP sockets are files, unix sockets are files, directories are files, devices are files, inodes are files…
So in this tangle of files lsof listst files opened by processes running on your system.
Now let’s start our quick tour and you’ll see the power of this tool.
Before starting, log in as root and then type…
lsof | nl
When lsof is called without parameters, it will show all the files opened by any processes. You should see something like this:
1 COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
2 init 1 root cwd DIR 3,1 432 2 /
3 init 1 root rtd DIR 3,1 432 2 /
4 init 1 root txt REG 3,1 32248 199 /sbin/init
5 init 1 root mem REG 3,1 89699 8031 /lib/ld-2.3.2.so
6 init 1 root mem REG 3,1 1466302 8034 /lib/libc-2.3.2.so
……..
3524 courier-i 30928 karkoma 1u unix 0xe1dcf500 2130235 socket
3525 courier-i 30928 karkoma 2w FIFO 0,6 3000 pipe
As you can see this is very verbose output, so let’s make more precise questions to lsof.
Let me know who is using the apache executable file, /etc/passwd, what files are opened on device /dev/hda6 or who’s accessing /dev/cdrom:
lsof `which apache2`
lsof /etc/passwd
lsof /dev/hda6
lsof /dev/cdrom
Now show me what process IDs are using the apache binary, and only the PID:
lsof -t `which apache2`
Show me what files are opened by processes whose names starts by “k” (klogd, kswapd…) and bash. Show me what files are opened by init:
lsof -c k
lsof -c bash
lsof -c init
Show me what files are opened by processes whose names starts by “courier”, but exclude those whose owner is the user “karkoma”:
lsof -c courier -u ^karkoma
Show me the processes opened by user apache and user johndoe:
lsof -u apache,johndoe
Show me what files are using the process whose PID is 30297:
lsof +p 30297
Search for all opened instances of directory /tmp and all the files and directories it contains:
lsof +D /tmp
List all opened internet sockets and sockets related to port 80:
lsof -i
lsof -i :80
List all opened Internet and UNIX domain files:
lsof -i -U
Show me what process(es) has an UDP connection opened to or from the host karkomaonline.com at port 123 (ntp):
lsof -iUDP@www.karkomaonline.com:123
lsof provides many more options and could be an unvaluable foresinc tool if your system get compromised or as daily basis check tool.
References: