Monday, January 2, 2012

Linux - Which process is bound to a particular port

I found this neat script, for you to use whenever in doubt about what process is bound to a particular port.

#!/bin/bash
# See Linux Server Hacks #54
# $Id: whosOnPort.sh,v 1.5 2007/03/28 06:50:09 oracle Exp $
#

port=$1
# get the process info (pid/name). restricted to tcp only
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

Source

https://github.com/tardate/sources/blob/master/whosOnPort.sh


It parses netstat info.

Example:

wwwrun@linux-2561:~> ./whosOnPort.sh  9999
9591/pgpool is running on port 9999
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
wwwrun    9591  0.0  0.1  10000  4128 ?        S    18:55   0:00 /usr/local/bin/pgpool -f /usr/local/etc/pgpool.conf -F /usr/local/e

Mmm, alternatively you can grep the /etc/services file (I own that one to RAF). For instance:

postgres@debian1:~$ cat /etc/services | grep 5432
postgresql      5432/tcp        postgres        # PostgreSQL Database
postgresql      5432/udp        postgres

But I like the script mentioned above better as it gives you more useful info.

No comments:

Post a Comment