Port to PID with lsof

The following is a script that maps LISTENing TCP ports to their associated PID, command name, and process owner. The script was specifically written for Solaris 9, but it may be useful for other UNIX platforms that do not have the --program, or -p,  flag with netstat.

If you are concerned that the system is compromised, it would be a better idea to scan for open ports with a tool like nmap instead of relying on netstat output.

Example output:

Port   Command    PID    User   
----   -------    ---    ----   
21     inetd      196    root   
22     sshd       5097   root   
23     inetd      196    root   
25     sendmail   289    root   
80     httpd      453    prms   
587    sendmail   289    root   
898    smcboot    268    root   
1099   rmiregist  12177  prms   
1583   SimbaMana  11948  prms   
5987   smcboot    268    root   
5988   smcboot    268    root   
6996   swxevd_sr  12217  prms   
7937   nsrexecd   303    root   
7938   nsrexecd   302    root   
8012   java       12244  prms   
8015   java       12244  prms   
9010   htt_serve  298    root   
10000  tvinetd    11949  prms   
10001  tvinetd    11949  prms   
11000  java       12190  prms   
32768  smcboot    270    root   
32769  smcboot    272    root   
56241  java       12224  prms

Script:

# Map LISTENing TCP ports to their PIDs using lsof

LSOF=/usr/local/bin/lsof

# e.g. netstat -an
# 127.0.0.1.25               *.*                0      0 49152      0 LISTEN
#       *.22                 *.*                0      0 49152      0 LISTEN

# e.g. lsof -i
# sshd    5097    root    5u  IPv4 0x30863fb1b58      0t0  TCP *:ssh (LISTEN)

printf "%-6s %-10s %-6s %-8s\n" "Port" "Command" "PID" "User"
printf "%-6s %-10s %-6s %-8s\n" "----" "-------" "---" "----"

for PORT in `netstat -an | grep LISTEN | \
perl -ne 'print "$1\n" if /.*\.(\d+)\s+\*\.\*/' | sort -n | uniq`
do
   $LSOF -i :${PORT} 2>/dev/null | grep LISTEN | tail -1 | while read line
   do
      set $line
      COMMAND=$1
      PID=$2
      LSOF_USER=$3
      printf "%-6d %-10s %-6d %-8s\n" "$PORT" "$COMMAND" "$PID" "$LSOF_USER"
   done
done

Back to brandonhutchinson.com.
Last modified: 2006/07/27