Unix/Linux

Unix/Linux – LSOF (List Open Files)

LSOF lists on its standard output file information about files opened by processes, it is a powerful utility that combines capabilities of ps and netstat commands and it is available to sysadmin (root) users only.


Usage:

lsof 4.82
[-?abhlnNoOPRtUvVX] [+|-c c] [+|-d s] [+D D] [+|-f[gG]] [+|-e s]
[-F [f]] [-g [s]] [-i [i]] [+|-L [l]] [+m [m]] [+|-M] [-o [o]] [-p s]
[+|-r [t]] [-s [p:s]] [-S [t]] [-T [t]] [-u s] [+|-w] [-x [fl]] [–] [names]
Use the “-h” option to get more help information.


The ‘^’ is used to exclude certain things from output when -u, -p, -g, -c and -s options are used.

Following usage excludes root user from the output:

lsof -u ^root

-a option can be used for AND operation, following produces listing of only UNIX socket files AND those belong to processes owned by users root and ntp:

lsof -a -U -u root,ntp

List files that belong to users root or ntp and have network connection to address 127.0.0.1:

lsof -a -i @127.0.0.1 -u root,ntp

List processes that starts with letter “a”, “b” and “c”

lsof -ca -cb -cc

Lists NFS files:

lsof -N

Lists process with port id:9650 and inhibits conversion from port numbers to port names (-P) and also inhibits conversion from network addresses to hostnames (-n)

lsof -P -n -i:9650

COMMAND     PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
java       8250 root  115u  IPv4 503039      0t0  TCP 10.1.1.1:57218->10.2.2.2:9650 (ESTABLISHED)

 list only network files with TCP state LISTEN:

lsof -iTCP -sTCP:LISTEN

list network files with all UDP states except Idle:

lsof  -iUDP -sUDP:Idle

Linux – Useful NetStat cmds

  1. Display Kernel IP Routing Table: netstat -rn
  2. Display Interface Rx/Tx Statistics: netstat -i
  3. Display Ethernet Interface Status & Errors: netstat -ie 
  4. Display All Protocol Statistics: netstat -s
  5. Display TCP Ststistics: netstat -st
  6. Display UDP Statistics: netstat -su
  7. Display PID of Service: netstat -tp
  8. Display Connections in Listening State: netstat -l  (-lt for TCP and -lu for UDP)
  9. Display Programs in a Listening State: netstat -ap
  10. Display Processes With PIDs and Usernames: sudo netstat -ltpe  (run as root)