Linux Step By Steps

NETWORKING-PORT SCRIPTS

From: Vu Pham

I attach two versions of the script. One ( funet ) uses netstat -l for symbolic ports, the other ( funet2 ) netstat -ln for numerical ports . The later gives result faster


filename="funet"

#!/bin/sh
#thanks to ideas of David A. Bandel and Myles Green
#note: fuser requires root priviledge to collect information

netstat -l |

# keep lines that start with tcp or udp, and keep only protocol & port
sed -e '/^..[^p]/d' -e 's/\*:\*.*//1' -e 's/ .*:/ /1' |
while read line
do
   # line is of format "tcp port-number" or "udp port-number"
   i=`fuser -n $line`
   # i is of format "port-number/protocol: PID1 PID2 ..."
   #save the port/protocol for later use
   port=`echo $i | sed -e 's/:.*/:/g'`
   #get the array of PIDs for a given port/protocol
   j=`echo $i | sed -e 's/^.*://g'`
   for m in $j # loop for all PIDs
   do
      #display program that has predefined PID
      k=`ps -p $m -o comm -h`
      echo "$port $k"
   done
done

filename="funet2"

#!/bin/sh
#thanks to ideas of David A.Bandel and Myles Green
#note : fuser requires root priviledge to collect information
netstat -ln |
#keep line that starts with tcp or udp, and keep only protocol and port
sed -e '/^..[^p]/d' -e 's/0.0.0.0:\*.*//1' -e 's/ .*:/ /1' |
while read line
do
   # line is of format "tcp port-number" or "udp port-number"
   i=`fuser -n $line`
   # i is of format "port-number/protocol: PID1 PID2 ..."
   #save the part port/protocol for later use
   port=`echo $i | sed -e 's/:.*/:/g'`
   #get the array of PIDs for a given port/protocol
   j=`echo $i | sed -e 's/^.*://g'`
   for m in $j # loop for all PIDs
   do
      #display program that has predefined PID
      k=`ps -p $m -o comm -h`
      echo "$port $k"
   done
done