Skip to content

Instantly share code, notes, and snippets.

@nuxlli
Created November 19, 2020 23:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nuxlli/5174db4369b7381d972b18a005bba159 to your computer and use it in GitHub Desktop.
Save nuxlli/5174db4369b7381d972b18a005bba159 to your computer and use it in GitHub Desktop.
List port by process on macOS
#!/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 %-20s\n" "Port" "Command" "PID" "User" "Listen"
printf "%-6s %-10s %-6s %-8s %-20s\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
LISTEN=$9
printf "%-6d %-10s %-6d %-8s %-20s\n" "$PORT" "$COMMAND" "$PID" "$LSOF_USER" "$LISTEN"
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment