my recent reads..

Atomic Accidents: A History of Nuclear Meltdowns and Disasters; From the Ozark Mountains to Fukushima
Power Sources and Supplies: World Class Designs
Red Storm Rising
Locked On
Analog Circuits Cookbook
The Teeth Of The Tiger
Sharpe's Gold
Without Remorse
Practical Oscillator Handbook
Red Rabbit

Sunday, March 25, 2007

Who's bound to that port?

Recently wanted to track down the details of the process that had a specific port open. I checked out the O'Reilly Linux Server Hacks book, and hack #56 was pretty much what I wanted. I scriptified it somewhat as follows. Note that this only looks at tcp:
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%/*}

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:


Gavin said...

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.


$ sh ./ 1521
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...



Paul said...

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.