lsof is the sysadmin/security über-tool. I use it most for getting network connection related information from a system, but that’s just the beginning for this powerful and too-little-known application. The tool is aptly called lsof because it “lists openfiles“. And remember, in UNIX just about everything (including a network socket) is a file.

Interestingly, lsof is also the Linux/Unix command with the most switches. It has so many it has to use both minuses and pluses.

As you can see, lsof has a truly staggering number of options. You can use it to get information about devices on your system, what a given user is touching at any given point, or even what files or network connectivity a process is using.

For me, lsof replaces both netstat and ps entirely. It has everything I get from those tools and much, much more. So let’s look at some of its primary capabilities:

It’s important to understand a few key things about how lsof works. Most importantly, when you’re passing options to it, the default behavior is to OR the results. So if you are pulling a list of ports with -i and also a process list with -p you’re by default going to get both results.

Here are a few others like that to keep in mind:

default : without options, lsof lists all open files for active processes

grouping : it’s possible to group options, e.g. -abC, but you have to watch for which options take parameters

-a : AND the results (instead of OR)

-l : show the userID instead of the username in the output

-h : get help

-t : get process IDs only

-U : get the UNIX socket address

-F : the output is ready for another command, which can be formatted in various ways, e.g. -F pcfn (for process id, command name, file descriptor, and file name, with a null terminator)

As I said, one of my main usecases for lsof is getting information about how my system is interacting with the network. Here are some staples for getting this info:

Show all connections with -i

Some like to use netstat to get network connections, but I much prefer using lsof for this. The display shows things in a format that’s intuitive to me, and I like knowing that from there I can simply change my syntax and get more information using the same command.

Show me everything daniel is doing connected to 1.1.1.1

Using the -t and -c options together to HUP processes

# kill -HUP `lsof -t -c sshd`

Show open connections with a port range

# lsof -i @fw.google.com:2150=2180

Conclusion

This primer just scratches the surface of lsof‘s functionality. For a full reference, run man lsof or check out the online version. I hope this has been useful to you, and as always, comments and corrections are welcomed.