Tuesday, February 3, 2009

Script to find PID from a port number - Solaris specific

Here is the script which can be used to find which port is running what PID.

Note: This script is Solaris OS specific (because of pfiles command used in the script. This command is only available with Solaris.)


bash-2.05# cat find_PID_from_port
#!/bin/ksh
#*********************************************************************************************************#
# Purpose is to find the PID on which given port is active.
# Need to be root to check other folk's PID's out
#
# Note: This script gives the PID and process details which is using the port number given in argument
# ./find_PID_from_port 80
#*********************************************************************************************************#

line='-------------------------------------------------------------------------'
pids=$(/usr/bin/ps -ef | sed 1d | awk '{print $2}')

# Prompt users or use 1st cmdline argument
if [ $# -eq 0 ]; then
read ans?"Enter port you like to know pid for: "
else
ans=$1
fi

# Check all pids for this port, then list that process
for f in $pids
do
/usr/proc/bin/pfiles $f 2>/dev/null | /usr/xpg4/bin/grep -q "port: $ans"
if [ $? -eq 0 ] ; then
echo $line
echo "Port: $ans is being used by PID:\c"
/usr/bin/ps -ef -o pid -o args | egrep -v "grep|pfiles" | grep $f
fi
done
exit 0


The example of output is shown below:


# ./find_PID_from_port.ksh 23
-------------------------------------------------------------------------
Port: 23 is being used by PID: 154 /usr/sbin/inetd -s

# ./find_PID_from_port.ksh 22
-------------------------------------------------------------------------
Port: 22 is being used by PID: 219 /usr/sbin/sshd
-------------------------------------------------------------------------
Port: 22 is being used by PID: 3189 /usr/sbin/sshd -R
-------------------------------------------------------------------------
Port: 22 is being used by PID: 3187 /usr/sbin/sshd -R
#

No comments: