Fun with lsof

Posted on Wed 14 November 2012 in misc

lsof (list open files) is a tool I have used recently for discovering which service is using a certain port.  We also had a issue recently where our /var partition was showing 0 bytes free, but du -csh /var was showing over 1.5GB free.  Using lsof | grep deleted we were able to determine that processes were still holding files open that had since been (erroneously) deleted.  Here are some more examples of lsof that I like.

sudo lsof -i:22 - List all open internet sockets using port 22 (who is using port 22)

sudo lsof -i4 -sTCP:LISTEN - List all IPv4 internet sockets (-i4) in state Listen (-sTCP:LISTEN) This is should list all listening services (not working on centos 5)

sudo lsof -i4 -sTCP:LISTEN -P - As above but don't lookup service names

sudo lsof -u icecast - List all open files used by user icecast (-u icecast)

sudo lsof -u icecast -a -i List all open files used by user icecast and (-a) only internet sockets (-i)

sudo lsof -p 3893 - List all open files of pid 3893

sudo lsof -P -c ushare -a -i - List open files for processes executing a command beginning with "ushare" (-c) and (-a) internet sockets.  Don't lookup the service in /etc/services(-P)

sudo lsof -P -c ushare -a -i -sTCP:LISTEN As above but only the the listening ports for TCP

sudo lsof -i4 -sTCP:LISTEN -a -p 3792 -P - Show listening IP4 TCP ports for process 3792