Script to get the list of services running on system in below format:

Protocol – Port – Program Name

for LIST in `netstat -nalpe | egrep -i ‘^tcp|^udp’ | grep ‘LISTEN’ | awk ‘{ print $1"|"$4"|"$9 }’`; do PROT=`echo ${LIST} | cut -d"|" -f1`; PORT=`echo ${LIST} | cut -d"|" -f2`; PORT=${PORT##*:}; PROG=`echo ${LIST} | cut -d"|" -f3`; PROG=${LIST##*/}; echo "${PROT} – ${PORT} – ${PROG}"; done

Here   ${PORT##*:}  or    ${LIST##*/}    is called Parameter Substitution.
In this ##*/ or ##*:  erases whatever before : & /

To study this script.. Brake the script…

1. See what output you get by this command

netstat -nalpe | egrep -i ‘^tcp|^udp’ | grep ‘LISTEN’ | awk ‘{ print $1"|"$4"|"$9 }’

You will get below output

tcp|0.0.0.0:22|8316/sshd
tcp|127.0.0.1:8118|1310/polipo
tcp|127.0.0.1:631|1187/cupsd

2. Copy first line of above output and put that into variable LIST
LIST="tcp|0.0.0.0:22|8316/sshd"

3. Then try below commands and see the output.

PROT=`echo ${LIST} | cut -d"|" -f1`
echo $PROT

PORT=`echo ${LIST} | cut -d"|" -f2`
echo $PORT

PORT=${PORT##*:}
echo $PORT 

like this see all variables in script PROT, PORT, PROG. So that you will understand the script very easily.

Neelesh Gurjar has written 122 articles

One thought on “

Leave a Reply