In this brief article I'd like to share a short script I recently wrote to check for port status for different ports in Linux. This script may prove useful as a pre-check or post-check after a maintenance activity or you can also put the script in cron if you need to monitor the port number corresponding to a service at regular intervals and relying on conventional monitoring tools is not an option.
Here is the script:
[root@still ~]# cat port_check.bash
#!/bin/bash
##Add a file containing a list of port numbers to chek##
PORT_LIST="/root/plist"
while read PNUM
do
netstat -tulpn | grep -w ":${PNUM}" > /dev/null
if [ $? -eq 0 ]
then
echo "port number ${PNUM} is listening on `hostname`"
else
echo "port number ${PNUM} is not listening on `hostname`"
fi
done < ${PORT_LIST}
Here is the script:
[root@still ~]# cat port_check.bash
#!/bin/bash
##Add a file containing a list of port numbers to chek##
PORT_LIST="/root/plist"
while read PNUM
do
netstat -tulpn | grep -w ":${PNUM}" > /dev/null
if [ $? -eq 0 ]
then
echo "port number ${PNUM} is listening on `hostname`"
else
echo "port number ${PNUM} is not listening on `hostname`"
fi
done < ${PORT_LIST}
To test it I've created a file ptest with some port numbers to test the script.
[root@still ~]# cat /root/plist
80
22
30
Let's run the script:
[root@still ~]# ./port_check.bash
port number 80 is listening on still
port number 22 is listening on still
port number 30 is not listening on still
This is more of an arbritrary setup. You can add logic to send an email to you if any of the ports are not found to be in listening state
No comments:
Post a Comment