Friday, July 18, 2008

A Script Looking For Processes That Open Specific Ports

Question: In Solaris, how to know which process opens a specific port?

There is an easy answer in Linux: lsof. However, Solaris doesn't deliver a similar command. So I need a workround to resolve it: using ps command to get pid of all processes, and use pfiles to find ports opened by those processes and match them with the given ports.

I wrote the following script to manage it.

Example of usage:

pp 9000
pp 9000 9001
pp 9000-9010 9100 9200-9201


#!/usr/bin/bash

# The script lists the process that opens given ports

# function printing usage message
help_msg () {
echo "Usage: pp ... -..."
}

# initialize argument array
aports=""

# function appending a port to $aports
append_arg () {
if echo " $aports " | grep " $1 " > /dev/null
then
return
fi
aports=`echo $aports $1`
}

# verify arguments
if [ $# -eq 0 ]
then
help_msg
exit 1
fi

# process arguments
for arg in $*
do
if echo $arg | grep "^[0-9]*$" > /dev/null
then
#process single port
append_arg $arg
elif echo $arg | grep "^[0-9]*-[0-9]*" > /dev/null
then
# process port range (-)
n1=`echo $arg | cut -d "-" -f1`
n2=`echo $arg | cut -d "-" -f2`
if [ $n1 -le $n2 ]
then
until [ $n1 -gt $n2 ]
do
append_arg $n1
n1=$((n1 + 1))
done
else
echo "Invalid port:" $arg
fi
else
echo "Invalid port: " $arg
fi
done

# loop arguments
for port in $aports
do
echo "Port: $port"
found=false

# find processes
for pid in `ps -ef -o pid | tail +2`
do
for pport in `/usr/proc/bin/pfiles $pid 2>/dev/null | grep "sockname:" | cut -d: -f 3`
do
if [ $pport -eq $port ]
then
found=true
echo "Process: $pid"
# echo "Command: " `ps -ef -o pid -o args | grep ^\ *$pid | cut -b7-`
echo "Command: " `pargs -l $pid`
#echo $pports
echo
break
fi
done
done

if ! $found
then
echo "Not found"
echo
fi
done

No comments: