Wednesday, October 7, 2009

Finding the port number of a process (useful when lsof doesn't help).

Hi Folks,

 

I've been away for many months due to work/vacation but now I'm back (I'll try to post new things on a regular basis :)

 

Sometime ago I had a request from a WEBLOGIC guy to kill a process that was using a specific port, but the real issue was: *he didn't know the PID # and LSOF was not working*

 

So, I started g00gling around and found a small script that does the job. The script uses one of the proc tools "PFILES" to grep for the port # given in the command line:

 

# ./portfind.sh 161

Greping for your port, please be patient (CTRL+C breaks)

        sockname: AF_INET 10.13.204.20  port: 8161

Is owned by pid 1438

..

        sockname: AF_INET 0.0.0.0  port: 161

Is owned by pid 2474

..

 

 

# ps -ef | egrep '1438|2474'

    root  1438     1  0   Sep 28 ?        0:03 ./snmpmagt /opt/patrol/PATROL/Solaris28-sun4/lib/snmpmagt.cfg NOV

    root  2474     1  0   Sep 28 ?        0:00 /usr/lib/snmp/snmpdx -f 0 -y -c /etc/snmp/conf

    root  2490  2474  0   Sep 28 ?       11:36 mibiisa -r -p 32855

 

 

Here is the script code:

 

 

#!/bin/bash

# is the port we are looking for

 

if [ $# -lt 1 ]

then

echo "Please provide a port number parameter for this script"

echo "e.g. %content 1521"

exit

fi

 

echo "Greping for your port, please be patient (CTRL+C breaks)"

 

for i in `ls /proc`

do

pfiles $i | grep AF_INET | grep $1

if [ $? -eq 0 ]

then

echo Is owned by pid $i

echo ——

fi

done

 

Enjoy

2 comments:

  1. Replies
    1. This solution was designed on a Solaris environment ... I'm not sure if it works on HPUX systems

      Delete