shell script to monitor port and notify by email
!/bin/bash ADMIN_EMAIL="email" PID=$$ POLL_INTERVAL=2 trap traphup HUP sleep 1 i=1 laststate="STARTUP" notify() { #echo "Service State Changed to $1" | mail -s "Service Status Notification" $ADMIN_EMAIL echo "Admin has been notified $1" } while [ $i -lt 2 ] do echo "LastState:$svc" portstat=nmap -p21 localhost -oG - | grep -o open
if [ $portstat ]; then svc="UP" echo "Port is Listening:$portstat" if [[ "$svc" != "$laststate" && "$laststate" != "STARTUP" ]]; then notify $svc fi laststate=$svc else svc="DOWN" echo "Port is Not Listening:Closed" if [[ "$svc" != "$laststate" && "$laststate" != "STARTUP" ]]; then notify $svc fi laststate="DOWN" fi sleep $POLL_INTERVAL done toggle_alert(){ if [ $1 == 1 ]; then let ALERTS=0; else ALERTS=1; fi } traphup(){ $0 "Test" & kill $$ exit 0 }
Advanced version : Sending signal to turn alert on and off
send signal by : kill -HUP nmap -p${MONITOR_PORT} localhost -oG - | grep -o open
if [ $portstat ]; then svc="UP" if [[ "$svc" != "$laststate" && "$laststate" != "STARTUP" ]]; then echo Alert is $ALERT notify $svc $ALERTS fi laststate=$svc else svc="DOWN" if [[ "$svc" != "$laststate" && "$laststate" != "STARTUP" ]]; then notify $svc $ALERTS fi laststate="DOWN" fi sleep $POLL_INTERVAL done