Saturday, December 1, 2012

Determine port number used by a Process or vise versa


-->
Problem- A tool which can determine port number used by a Process or vise versa
Solution- it consists of below two scripts. Please run port_process_map.sh for desired output.

Below is the code of the scripts.

source code of port_process_map.sh
 
#!/bin/bash
SCRIPT_DIR=`dirname $0`
. ${SCRIPT_DIR}/function.sh
if [ $# -lt 2 ]
then
echo -e "You have not provided enough arguments.Please refer below use syntax.\n"
use_syntax
elif [ ! `echo $#|grep "^-"|wc -l` ]
then
echo -e "OPTIONS are mendatory.Please refer below use syntax.\n"
use_syntax
fi
case `uname -s` in
SunOS ) OS_TYPE=SunOS;;
Linux ) OS_TYPE=Linux;;
* ) echo "this script may not work for you. You may or maynot change somewhere in the script";;
esac
while getopts :P:p: opt
do
case "${opt}" in
P ) PID="${OPTARG}";
        echo $PID|grep "^-">>/dev/null
        if [ $? -eq 0 ]
        then
        use_syntax
        fi
        if [ "$OS_TYPE" == "Linux" ]
            then
                #echo "i m here PID"
                linux_process_to_port_map $PID
        else
                solaris_process_to_port_map $PID
        fi;;
p ) PORT="${OPTARG}";
        echo $PORT|grep "^-">>/dev/null
        if [ $? -eq 0 ]
        then
        use_syntax
        fi
        if [ "$OS_TYPE" == "Linux" ]
             then
        #       echo "i m here PORT"
                linux_port_to_process_map $PORT
        else
                solaris_port_to_process_map $PORT
        fi;;
* ) echo "you have mentioned wrong argument";
    use_syntax;;
esac
done


source code of function.sh

linux_port_to_process_map()
{
echo -e "\n\nPort to Process mapping for PORT -  $1"
PID=`lsof -t -i:$1`
COMMAND=`ps -ef | awk -v PID=$PID '{ if($2==PID) print substr($0,index($0,$8))}'`
echo -e "PID\tPROCESS_OR_COMMAND"
echo -e "$PID\t$COMMAND"
}

solaris_port_to_process_map()
{
echo -e "\n\nPort to Process mapping for PORT -  $1"
echo -e "PID\tPROCESS_OR_COMMAND"
echo "------------------------------------------"
for PID in `ptree -a | awk '/ptree/ {next} {print $1};'`
do
pfiles $PID 2> /dev/null| egrep "port: ${1}$">>/dev/null
if [ $? -eq 0 ]
then
COMMAND=`ps -fo comm= -p $PID`
echo -e "$PID\t$COMMAND"
fi
done
}

linux_process_to_port_map()
{
echo -e "\n\nProcess to Port mapping for PID  - $1"
echo PORTS
lsof|grep "LISTEN"|awk -v PID=$1 '{if($2==PID) print $8}'|awk -F":" '{print $2}'
}

solaris_process_to_port_map()
{
echo -e "\n\nProcess to Port mapping for PID  - $1"
echo PORTS
pfiles $PID 2>/dev/null|egrep port:|awk '{print $5}'
}

use_syntax()
{
echo "usage: $0 [-p PORT] [-P PID] (Wildcard permitted)"
exit;
}