Search code examples
bashemailalertpingrhel

Email Alerts when service or server automatically comes up


I am working on a bash script that helps to ping and get the network interface level status of the host machines and services. This script will send a email alerts in case of failure.

#!/bin/bash
HOSTS="192.168.8.200"
COUNT=4
for myHost in $HOSTS
do
  count=$(ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
  if [ $count -eq 0 ]; then
    # 100% failed
    echo -e "HOST:$myHost is down (ping failed) at $(date)" | mailx -A gmail    -s “Mail       subject” anymail@anydomain.com

  fi
done

This works fine. But need help to get a one single email alert when host automatically comes up (ping success).


Solution

  • You need to save the state of the host (up/down) during the calls of your script. if the host is "up" and the former state was "down" then you need to send an email. You can just write the result of the "check command" to a file in /tmp/ if the check returns that the server is up you read the content of the file. if the state is "down" in the file, then send an email an write "up" to the file. on the next check if the server is up, there will be no additional email sent, because the server was also "up" before.

    #!/bin/bash
    HOSTS="192.168.8.200 192.168.8.201 192.168.122.1"
    COUNT=4 
    STATE="/tmp/ping_state.txt"
    
    for myHost in $HOSTS
    do      
      count=$(ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
      if [ $count -eq 0 ]; then 
        # 100% failed
        #echo -e "HOST:$myHost is down (ping failed) at $(date)" | mailx -A gmail    -s “Mail       subject” anymail@anydomain.com
         echo "host $myHost down"
        #delete all previous entries of that ip 
        sed -i "/$myHost/d" $STATE
        #mark host as down 
        echo "$myHost - down" >> $STATE
      else    
        CHECK=`grep "$myHost" $STATE | grep -o "down"` 
        if [ "$CHECK" = "down" ]; then 
          echo "host $myHost up again"
          #insert email for host up here
        fi      
    
        #delete all previous entries of that ip 
        sed -i "/$myHost/d" $STATE
        echo "$myHost - up" >> $STATE
      fi      
    done
    

    for simple testing I just used an echo statement instead of sending an email.