Skip to content

Instantly share code, notes, and snippets.

@nuxlli
Created March 12, 2010 14:08
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nuxlli/330338 to your computer and use it in GitHub Desktop.
Save nuxlli/330338 to your computer and use it in GitHub Desktop.
#!/bin/sh
# Map LISTENing TCP ports to their PIDs using lsof
LSOF=/usr/sbin/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 -f inet | grep -i listen | awk '{ print $4 }' | sed -e :a -e 's/.*\.//'`; 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
@tkrajcar
Copy link

Great script, thanks for sharing it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment