#!/bin/sh
# Written by hip0.
# Under GPL ver. 2.0 and above.
# Description: Uses array of servers, specified port number
# and nmap to check the port defined in $port_num for "open" state.
# If the checked port has different state from "open"
# We assume our server is down and send notify sms and mail
# to the administrator. Where the mail header that the mail's been sent
# from will have the problematic server's ip in instead of username.


# array with boxes we check for
box[0]="192.168.0.1";
box[1]="192.168.0.2";
box[2]="192.168.0.3";
box[3]="127.0.0.1";
box[4]="192.168.0.4";
box[5]="192.168.0.4";
# Count of the machines in the array counted from zero.
machine_cnt=${#box[@]};
# port number we shall check for
port_num="80";
# nmap scanner location and options
scanner_stuff="/usr/bin/nmap -P0 -p $port_num";
# string for opened port
op="open";
# my gsm number where our mail shall be sent
mynum=359899594691;
# provider to use for sending
myprov="sms.globul.bg";
# mail address for notifaction 
mymail="hipo@design.bg";
# temporary lock file ( should be manually removed )
lock_file=/tmp/server-down;
# qmail-inject binary full path
qmail_inject=/var/qmail/bin/qmail-inject;

if [ -f $lock_file ]; then
exit 1;
fi

for((i=0;i<${machine_cnt};i++)); do
sleep 2;
if [ "`$scanner_stuff ${box[$i]} | grep "$op" | awk '{ print $2 }'`" != "$op" ]; then
sleep 20;
if [ "`$scanner_stuff ${box[$i]} | grep "$op" | awk '{ print $2 }'`" != "$op" ];
then
sleep 40;
if [ "`$scanned_stuff ${box[$i]} | grep "$op" | awk '{ print $2 }'`" != "$op" ]; then
sleep 400;
if [ "`$scanned_stuff ${box[$i]} | grep "$op" | awk '{ print $2 }'`" != "$op" ]; then
sleep 800;
if [ "`$scanned_stuff ${box[$i]} | grep "$op" | awk '{ print $2 }'`" != "$op" ]; then

sedded_box_name=$(echo ${box[$i]} | sed -e "s/\./_/g");
if [ -f $lock_file ]; then
exit 1;
fi
export USER=$sedded_box_name;
echo "To:${mynum}@${myprov}" | $qmail_inject 
echo -e "Our ${box[$i]}'s port $port_num is closed or filtered.\n The box is probably down" | mail ${mymail} -s "Problem with server ${box[$i]}";
touch $lock_file 
echo "Port: $port_num on box: ${box[$i]} closed or filtered" >> $lock_file
echo "Machine is probably down" >> $lock_file
exit 1;
fi
fi
fi
fi
fi
done

