Skip to content

Instantly share code, notes, and snippets.

@akrisiun
Forked from tianchaijz/tips_lsof.sh
Last active January 24, 2023 18:00
Show Gist options
  • Save akrisiun/35aa968a0b1b55284b58a03143100ae9 to your computer and use it in GitHub Desktop.
Save akrisiun/35aa968a0b1b55284b58a03143100ae9 to your computer and use it in GitHub Desktop.
Shell command lsof : see open files and ports; Selection is OR by default, use -a for AND; Tested on OSX
# filter LISTEN - faster variant
lsof -anP -i4 -sTCP:LISTEN
# exclude UDP
lsof -anP -i4 -sTCP:LISTEN | grep TCP
# lsof with ports sort:
lsof -anP -i4 -sTCP:LISTEN | grep -v UDP | awk {'printf("%18s %-12s %8s %s %s %s\n", $9,$1,$2,$4,$3,$10)'} | sort -u
# docker-ps
docker ps -a --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" | grep -v k8s | awk {'printf("%-15s %s %3s %s %-32s %-20s %s %s\n", $1,$2,$3,$4,$5,$6,$7,$8)'}
# non Apple launchctl services + brew services
launchctl list | grep -v apple
echo "brew services list "
brew services list
#list all ports for tcp
sudo lsof -itcp
#find all things listening on ports
lsof -Pnl +M -i4 | grep LISTEN
#all ports for tcp, dont resolve port name from numbers
sudo lsof -itcp -P
#open files and ports of process #$PID
sudo lsof -p $PID
#only ports of tcp for process #$PID, dont resolve port name, dont resolve ip name
sudo lsof -a -p $PID -P -n -itcp
#only ports of tcp for process #$PID, dont resolve port name, dont resolve ip name, refresh every 5 seconds
sudo lsof -a -p $PID -P -n -itcp -r 5
#search by file (can be slow)
sudo lsof /complete/path/to/file
#plenty more options and usage patterns
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment