#!/bin/bash
port=$1
procinfo=$(netstat --numeric-ports -nlp 2> /dev/null | grep ^tcp | grep -w ${port} | tail -n 1 | awk '{print $7}')
case "${procinfo}" in
"")
echo "No process listening on port ${port}"
;;
"-")
echo "Process is running on ${port}, but current user does not have rights to see process information."
;;
*)
echo "${procinfo} is running on port ${port}"
ps -uwep ${procinfo%/*}
;;
esac
As you can see, this works by getting a little bit of process info from netstat, then using ps to get the full details. Download the script here: whosOnPort.sh
2 comments:
Hey Paul,
Nice script, except I tested it, and (probably due to Murphy...) came up with a bug.
testing for port 1521 on a RAC database, comes back with 1 process listening on the same port, but two addresses (actual and VIP address) which causes the ps -uwep ${procinfo%/*} to break as it's getting two parameters.
ie
$ sh ./whosonport.sh 1521
29020/tnslsnr
29020/tnslsnr is running on port 1521
ps -uwep 29020/tnslsnr 29020
but it's not that often that you'd be asking a simple question like who owns the listener port on a RAC database server... like I said, Murphy's Law must have kicked in...
:-)
Gavin
Hi Gavin, good catch. I hadn't tried it with multiple IPs in use and its obviously a problem.
Straight-forward fix would be to tail -n 1 the netstat output to make sure only line returned.
More interesting fix is to change the procinfo variable substitution to ps -uwep ${procinfo%%/*}.
This makes it a greedy match, so you only get the first pid.
Post a Comment