Monday, March 05, 2007

Which process listens to this port (in Solaris)

If you have 'lsof' installed, it is very easy to find out which process is listening at certain port. However, in Solaris, it may not be so obvious. This is the question my friend asked me and I wrote a short script (listen.sh) for him. Basically it runs 'pfile' over all the processes listed in /proc (except process 0, which is the sched)

#! /bin/sh

if [ $# -ne 1 ]; then
  echo "Usage: $0 "
  exit 1
fi
listen=$1


PATH=/usr/bin:/bin
export PATH


#
# skip process 0
#
cd /proc
for i in [1-9][0-9]*
do
  pfiles $i | nawk -v listen=$listen '
    BEGIN {
      found=0
    }
    NR==1 {
      process=$0
    }
    /sockname/ && $NF == listen {
      getline
      if ( ! /peername/ ) {
        found=1
        exit
      }
    }
    END {
      if ( found == 1 ) {
        printf("%s\n",process)
      }
    }'
done

# ./listen.sh 22
29626: /usr/lib/ssh/sshd
#

Labels:

2 Comments:

Blogger Pintilie said...

It was really handy. Thanks

12:26 AM  
Blogger PaulsBlog said...

Hi, this script is great - just what I needed! I adopted it in the following way such that it won't output error messages of processes which the uses who runs this script does not have access to, modify the line
pfiles $i 2> /dev/null | nawk ...

such that strerr will be redirected to /dev/null

7:52 PM  

Post a Comment

<< Home