108

lsof is an increadibly powerful command-line utility for unix systems. It lists open files, displaying information about them. And since most everything is a file on unix systems, lsof can give sysadmins a ton of useful diagnostic data.

What are some of the most common and useful ways of using lsof, and which command-line switches are used for that?

Jeremy
  • 1
  • 85
  • 340
  • 366
Hans Sjunnesson
  • 21,745
  • 17
  • 54
  • 63

6 Answers6

123

To show all networking related to a given port:

lsof -iTCP -i :port
lsof -i :22

To show connections to a specific host, use @host

lsof -i@192.168.1.5

Show connections based on the host and the port using @host:port lsof -i@192.168.1.5:22

grepping for LISTEN shows what ports your system is waiting for connections on:

lsof -i| grep LISTEN

Show what a given user has open using -u:

lsof -u daniel

See what files and network connections a command is using with -c

lsof -c syslog-ng

The -p switch lets you see what a given process ID has open, which is good for learning more about unknown processes:

lsof -p 10075

The -t option returns just a PID

lsof -t -c Mail

Using the -t and -c options together you can HUP processes

kill -HUP $(lsof -t -c sshd)

You can also use the -t with -u to kill everything a user has open

kill -9 $(lsof -t -u daniel)
Kevin
  • 4,618
  • 3
  • 38
  • 61
27
lsof -i :port 

will tell you what programs are listening on a specific port.

Rob Kielty
  • 7,958
  • 8
  • 39
  • 51
dvorak
  • 31,281
  • 4
  • 27
  • 29
  • 1
    It's not limited to "listening", so if you specify `lsof -i :8080` and you have a bunch of processes connecting to a proxy on port 8080 you'll get those too. – Matt Byrne Oct 01 '14 at 01:57
14

lsof -i will provide a list of open network sockets. The -n option will prevent DNS lookups, which is useful when your network connection is slow or unreliable.

John Millikin
  • 197,344
  • 39
  • 212
  • 226
  • 6
    `lsof -i` will *only* show you sockets that you have access to in your namespace (and which are regarded as "internet" sockets through introspection, not just any kind of network socket). Otherwise handles of type 'sock' will not show up in the list. – Nick Bastin Aug 06 '13 at 21:17
14
lsof +D /some/directory

Will display recursively all the files opened in a directory. +d for just the top-level.

This is useful when you have high wait% for IO, correlated to use on a particular FS and want to see which processes are chewing up your io.

siesta
  • 1,365
  • 2
  • 16
  • 21
13

See what files a running application or daemon has open:

lsof -p pid

Where pid is the process ID of the application or daemon.

Rob Kielty
  • 7,958
  • 8
  • 39
  • 51
Chris
  • 4,852
  • 1
  • 22
  • 17
10
lsof +f -- /mountpoint

lists the processes using files on the mount mounted at /mountpoint. Particularly useful for finding which process(es) are using a mounted USB stick or CD/DVD.

mas
  • 1,107
  • 1
  • 11
  • 18