|
Tested to work on CentOS. But probably will also run on any Linux distro.
Description: This script will ping it's Internet gateway and it will alert the administrator via SMS message and email.
Prerequisites :
Kannel
Perl
Perl Net::SMTP module
SMTP server
Create the monitoring script:
# vi /usr/sbin/netmonitor
#!/bin/bash
# Created by: Christian Foronda
# Ref: http://onlamp.com/pub/a/onlamp/2003/04/03/linuxhacks.html
PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/sbin:/home/chr1x2/bin
GW="215.46.234.1"
PAUSE=3
MISSED=0
while true; do
if ! ping -c 1 -w 1 $GW > /dev/null; then
((MISSED++))
else
if [ $MISSED -gt 2 ]; then
netmonitor-email-alert && sendsms 01234567890+12345678900 "Automated Alert: Internet seems now UP. Now I can ping the gateway."
fi
MISSED=0
fi;
if [ $MISSED -eq 2 ]; then
netmonitor-email-alert && sendsms 01234567890+12345678900 "Automated Alert: Internet seems DOWN. I cannot ping the gateway. Please check."
fi
sleep $PAUSE;
done
Create the init script that will let netmonitor to run as daemon:
# vi /etc/init.d/netmonitor
#! /bin/sh
# created by: Christian Foronda
#
# netmonitor netmonitor
#
#
# chkconfig: 2345 11 02
# description: netmonitor daemon
# processname: netmonitor
# pidfile: /var/run/netmonitor.pid
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
NETMONITOR="/usr/sbin/netmonitor &"
[ -f /usr/sbin/netmonitor ] || exit 0
RETVAL=0
# See how we were called.
case "$1" in
start)
echo -n "Starting Internet connection monitor: "
daemon $NICELEVEL $NETMONITOR
RETVAL=$?
echo
[ $RETVAL = 0 ] && touch /var/lock/subsys/netmonitor
;;
stop)
echo -n "Stopping Internet connection monitor: "
killproc netmonitor
RETVAL=$?
echo
[ $RETVAL = 0 ] && rm -f /var/lock/subsys/netmonitor
;;
restart)
$0 stop
$0 start
RETVAL=$?
;;
status)
status netmonitor
RETVAL=$?
;;
*)
echo "Usage: $0 {start|stop|restart|status}"
exit 1
esac
exit $RETVAL
# chmod +x /usr/sbin/netmonitor /etc/init.d/netmonitor
Create the email script:
# vi /usr/sbin/netmonitor-email-alert
#!/usr/bin/perl
use Net::SMTP;
my $message = 'Automated Alert: Internet connection seems down. I cannot ping my gateway. Please check.';
my $date = `date +%m/%d/%Y`;
@emails = ("administrator\@mydomain.com","webmaster\@mydomain.com");
$smtp = Net::SMTP->new("ipofsmtpserver");
$smtp->mail("administrator\@mydomain.com");
$smtp->to(@emails);
$smtp->data();
$smtp->datasend("From: SERVER ALERT\n");
$smtp->datasend("Subject: SERVER Internet Connection ALERT: $date \n");
$smtp->datasend("Internet Connection ALERT! $date\n","$message\n","~" x 40,"~" x 40,"\n","THIS IS AUTO-GENERATED. DO NOT REPLY.");
$smtp->dataend();
$smtp->quit();
# chmod +x /usr/sbin/netmonitor-email-alert
To create the sendsms script. You may follow the guide here.
Add to start on boot:
# chkconfig --add netmonitor
Start the daemon:
# /etc/init.d/netmonitor start
|