It’s been a while since I offered a shell trick, so here’s one I’ve
found useful lately. It’s a way to quickly check what’s listening on a specific port.
There are times when I run into a conflict running local services,
saying the port is already in use, but I don’t know by what. So I use the following.
This snippet relies on having your root password stored in your login keychain. See this post for instructions on setting this up. Once it’s in place, you’ll have a secure way to run sudo commands from scripts which only ask for a password when your keychain is locked.
Here’s the snippet, ready to use in a function or alias:
#!/bin/bash
PASS=$(security find-generic-password -l "root password" -a root -w|tr -d '\n')
echo $PASS | sudo -S lsof -nP -iTCP:$1 -sTCP:LISTEN
# │ │ └──────────────────┘
# │ │ └ list only files with TCP LISTEN on port $1
# │ │└ no conversion of port numbers to port names
# │ └ no conversion of network numbers to host names
# └ Accept password on STDIN
The snippet uses lsof to show the process listening on whichever port you provide as the argument to the script.
Store this in a function or script called whatsonport
(or whatever
you like). Replace "root password"
with whatever you named your password entry in Keychain Access. Now you can call it like whatsonport 2020
.
I use this in Fish as a function in ~/.config/fish/functions/whatsonport.fish
:
function whatsonport --description 'find out what PID is running on a port (requires password)'
set -l pass (security find-generic-password -l "root password" -a root -w|tr -d '\n')
echo $pass | sudo -S lsof -nP -iTCP:$argv -sTCP:LISTEN
end
Hope that’s useful!