用于通过电子邮件警报进行服务监控并防止重复警报的 bash 脚本

用于通过电子邮件警报进行服务监控并防止重复警报的 bash 脚本

我有一个计划每 5 分钟运行一次的脚本来检查两项服务,如果发现任何服务状态关闭,则会发送电子邮件。其工作正常。

但问题是我希望它在服务上线时也发送 UP 警报。我可以添加行来发送电子邮件,但它会重复向上警报。我如何添加向上警报功能,但它应该只发送一次警报(就像向下警报一样)

#!/bin/bash
if pgrep "mysql" > /dev/null
then
    echo "MYSQL Running"
    rm -f /var/run/.mysql_mail_sent
else
    echo "ALERT: mysqld Stopped."
    if [ ! -f /var/run/.mysql_mail_sent ]; then
echo "Sending MYSQL DOWN Email..."
echo "DOWN ALERT! sending email" > /var/run/.mysql_mail_sent

    fi
fi

if pgrep "radiusd" > /dev/null
then
    echo "radiusd Running"
    rm -f /var/run/.radiusd_mail_sent
else
    echo "ALERT: RADIUSD Stopped"
    if [ ! -f /var/run/.radiusd_mail_sent ]; then
echo "RADIUSD DOWN: Sending Email."
echo "DOWN ALERT! sending email" > /var/run/.radiusd_mail_sent
    fi
fi

答案1

好吧,我终于成功了。 BASH 更快并且不需要任何第三部分工具。 [下午 4:43 更新]

#!/bin/bash
# Scheduled Script to check linux service status after every 5 minutes.
# If found stopped, send sms or email Alerts, but donot repeat it untill next status change.
# Syed Jahanzaib


# Run script with service name like
# ./status.sh mysqld


# Check if no service name is given
if [ "$1" == "" ]; then
echo No service name have been provided.
echo Usage exmaple:
echo
echo -e "./status.sh mysqld"
echo
fi

DATE=`date`
COMPANY="MYISP"


SERVICE1="$1"
SUBJECT="ALERT: $SERVICE1 is Down..."
STATUS_HOLDER="/tmp/$SERVICE1_STATUS_HOLDER.txt"

# KANNEL Gateway Info
KANNELURL="127.0.0.1:13013"
KANNELID="kannel"
KANNELPASS="password"
CELL1="0333xxxxxx"

# SMS Msgs test
MSG_UP="$COMPANY Info: $SERVICE1 is now UP @ $DATE"
MSG_DOWN="$COMPANY Alert: $SERVICE1 is now DOWN @ $DATE"

touch $STATUS_HOLDER

for SRVCHK in $SERVICE1
do
        PID=$(pgrep $SERVICE1)
        if [ "$PID" == "" ]; then
                echo "$SRVCHK is down"
                if  [ $(grep -c "$SRVCHK" "$STATUS_HOLDER") -eq 0 ]; then
                        echo "ALERT: $SERVICE1 is down at $(date) / SENDING SMS ...."
            echo "$MSG_DOWN" > /tmp/$SERVICE1_down.sms
# Sending DOWN SMS via KANNEL
cat /tmp/$SERVICE1_up.sms | curl "http://$KANNELURL/cgi-bin/sendsms?username=$KANNELID&password=$KANNELPASS&to=$CELL1" -G --data-urlencode text@-
                        echo "$SRVCHK" >> $STATUS_HOLDER
                fi
        else
                echo -e "$SRVCHK is alive and its PID are as follows...\n$PID"
                if  [ $(grep -c "$SRVCHK" "$STATUS_HOLDER") -eq 1 ]; then
                        echo "INFO ALERT : $SERVICE1 is UP at $(date) / SENDING SMS ...."
            echo "$MSG_UP" > /tmp/$SERVICE1_up.sms
# Sending UP SMS via KANNEL
cat /tmp/$SERVICE1_up.sms | curl "http://$KANNELURL/cgi-bin/sendsms?username=$KANNELID&password=$KANNELPASS&to=$CELL1" -G --data-urlencode text@-
                        sed -i "/$SRVCHK/d" "$STATUS_HOLDER"
                fi
        fi
done

相关内容