1

I have 5 hosts which i need to ping if any one down i should be alerted through an email it is possible..? and it will be checked with every 20 minutes. can anyone help me.. Thanks in advance...

i have used this script.. Do i need to make any changes for getting the expected result ?

Please suggest any opinion please.

    #!/bin/bash

    for i in $( cat $HOME/iplist.txt )
    do
    ping -q -c2 $i > /dev/null
    if [ $? -eq 0 ]
    then
    echo $i "Pingable"
    else
    echo $i "Not Pingable"
    fi
    done
Sajinu
  • 21

1 Answers1

0

Your script looks ok. You should add exit 0 / exit 1, for failure / success .. more info below.

and it will be checked with every 20 minutes

If the script should run always, each 20 minutes in the background, you should use cron, which is already available on your system.

Like that all output of your script will be mailed to root, if the script returns 1(FAILURE) .. however per default the root-mail just goes to some folder. You need to install & configure a mail-daemon to forward the root-mail to your personal mail-address. How that can be done is e.g. explained here: https://superuser.com/questions/306163/what-is-the-you-have-new-mail-message-in-linux-unix

Or here: Easy way to forward all email

Edit:

Ok, here some commands to get things done.

1.) First you need a version of your script which exits 1 on failure. Something like this should do:

#!/bin/bash

ALL_HOSTS_AVAILABLE=true
for i in $( cat $HOME/iplist.txt )
do
   ping -q -c2 $i > /dev/null
   if [ $? -eq 0 ]
   then
      echo $i "Pingable"
   else
      echo $i "Not Pingable"
      ALL_HOSTS_AVAILABLE=false
fi
done

if [ "$ALL_HOSTS_AVAILABLE" = false ] ; then
   echo 'Some hosts were not available!'
   exit 1
fi
exit 0

2.) Now make sure you have sudo-permissions set for your user(you dont want to do things directly as root). If not, follow this manual: How do I add a user to the "sudo" group? Maybe you first need to install the package sudo

su root
apt-get install sudo

3.) Copy your script to some folder which is visible to all users and hand it over to root. E.g:

sudo cp myScript /usr/local/bin
sudo chown root /usr/local/bin/myScript
sudo chgrp root /usr/local/bin/myScript

4.) Setup a cronjob which runs your script

# write out current crontab
crontab -l > mycron
# echo new cron into cron file */20 means each 20 minutes
# Check https://de.wikipedia.org/wiki/Cron for format
echo "*/20 * * * * /usr/local/bin/myScript" >> mycron
# install new cron file
sudo crontab mycron
rm mycron

5.) Install some MTA, so you get the email-notification working .. it looks like the most simple one is nullmailer

sudo apt-get install nullmailer

.. I dont know details, just google for help to do the nullmailer setup in the right way.

Alex
  • 385
  • 3
  • 15