Pages by Andreas B. M. Hofmeier
An-H
email Impressum/Note Privacy
http[s]://www.abmh.de/en/papers/ls/Endless_Loop_to_Monitor_a_Server.html

Like to be free? ... then: Fight for Freedom

About: Endless Loop to Monitor a Server

From Linux Solutions

Jump to: navigation, search

The following script sends every five minutes five pings to the server www.isis.or.ug. If one of these five pings are replayed, an SMS is send and the scripts ends itself.

     1  #!/bin/bash
       
       
     2  while true; do
     3    if ping -c 5 www.isis.or.ug 2> /dev/null > /dev/null; then
     4      echo www.isis.or.ug back online | mail 0712726609@sms.ugandatelecom.com
     5      echo www.isis.or.ug back online | mail 0774360452@mtnconnect.co.ug
     6      break;
     7    fi;
     8    sleep 5m;
     9  done
       
    10  sleep 5m
    11  sudo sendmail -qf

Line 2: Endless loop

Examle:

while true; do echo Hello; done

Note: Be very careful with endless loops. There can consume a lot of CPU power and make the computer very slow. Because of this put always a sleep into your loop.


Line 3:

ping -c 5 www.isis.or.ug send five pings to www.isis.or.ug

ping -c 5 www.isis.or.ug 2> /dev/null > /dev/null ... and suppress any output of ping.

if a; then
  b;
  c;
fi

Executes command a. If this command succeeds (returns 0), execute command b and c. Ping returns 0 if at least one ping is received.

if ! a; then b; c; fi

The same as above but b and c are executed if command a fails (Retunes Error Code greater than zero)


Line 4: Send the email with the body "www.isis.or.ug back online" and no subject to 0712726609@sms.ugandatelecom.com. In this case, the email is forwarded as SMS to the mobilephone 0712726609 by sms.ugandatelecom.com.

Normally emails should have a expressive subject!

cat <<EOF | mail -s "This is a subject" user@maildomain.co.ug
Hallo,

this email was sens by a script
EOF

Line 6: Leave the loop.


Line 8: Wait 5 minutes before executing to loop again (from line 3)


Line 10: Wait 5 minutes after the loop finished.

Line 11: Force all email in the local email queue to be sent.


Replace Line 3 with

if ! ping -c 5 www.isis.or.ug 2> /dev/null > /dev/null; then

if you want the SMS to be sent if the server is down and not answering the pings.

Remove Line 6 if you wand the script not to be finished after the SMS was sent. Warning: If the server is down longer, it will send a SMS every five minutes. May include a very long sleep, e.g. sleep 1d (sleep one day).


Andreas B.M. Hofmeier.


Pages by Andreas B. M. Hofmeier
An-H
email Impressum/Note Privacy
http[s]://www.abmh.de/en/papers/ls/Endless_Loop_to_Monitor_a_Server.html
Creative Commons License
(c) Andreas B. M. Hofmeier
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Germany License