如何监视服务并自动通知?

Bash

1 前言

一个问题,一篇文章,一出故事。
最近笔者希望通过脚本实现监视服务并在服务异常是使用两种方式通知管理员,于是创建本章节。

2 最佳实践

2.1 创建脚本

vim ~/scripts/checkService.sh

加入如下配置,

#!/bin/bash

# 配置变量
serverName="rproxy03"  # 替换为要检查的服务器名称
serviceName="nginx php-fpm"  # 替换为要检查的服务名称列表
adminEmail="will@cmdschool.org jeff@cmdschool.org"  # 替换为接收通知的邮箱列表
mailFrom="no_reply_admin@cmdschool.org"
smtpSer="smtp.cmdschool.org"
smtpPort="25"
mailTool="mail" #选项: "s-nail" or "mail"
tigaseAppID="10086"
tigaseAppPassword="*********"
tigaseEmployeeID="will,jeff"
tigaseApiURL="https://tigase.cmdschool.org:8092/tigase/pushText"
logFile="/var/log/serviceCheck.log"

# 函数:检查服务状态
checkServiceStatus() {
    local serviceName=$1
    systemctl is-active --quiet "$serviceName"
    return $?  # 返回服务状态
}

# 函数:发送 Tigase 通知
sendTigaseNotification() {
    local serverName=$1
    local serviceName=$2
    local messageBody="$serverName: $serviceName is down.%0d%0aEvent date:$(date +'%Y.%m.%d')"
    local curlData="appId=$tigaseAppID&password=$tigaseAppPassword&employee_id=$tigaseEmployeeID&body=$messageBody"
    curl -X POST -d "$curlData" "$tigaseApiURL" &> /dev/null
}

# 函数:发送邮件通知
sendEmailNotification() {
    local serverName=$1
    local serviceName=$2
    local subject="Service Alert: $serverName $serviceName is down"
    local message="The service $serviceName is not running. Please check the system."

    for mailTo in $adminEmail; do
        if [ "$mailTool" == "s-nail" ]; then
        	echo "$message" | s-nail -s "$subject" -r "$mailFrom" -S "mta=smtp://$smtpSer:$smtpPort" "$mailTo";
        elif [ "$mailTool" == "mail" ]; then
        	echo "$message" | mail -s "$subject" -r "$mailFrom" -S "smtp=smtp://$smtpSer:$smtpPort" "$mailTo";
        else
                echo "Invalid mail tool specified."
                exit 1
        fi
    done
}

# 函数:记录日志
logMessage() {
    local message="$1"
    echo "$(date +'%Y-%m-%d %H:%M:%S') $message" | tee -a "$logFile"
}

# 主程序
main() {
    for service in $serviceName; do
        if ! checkServiceStatus "$serviceName"; then
            echo "Service $serviceName is down. Sending notifications."
            sendEmailNotification "$serverName" "$serviceName"
            sendTigaseNotification "$serverName" "$serviceName"
            logMessage "$serviceName is down. Notifications sent."
        else
            echo "Service $serviceName is running."
        fi
    done
}

# 执行主程序
main

2.2 测试脚本

bash ~/scripts/checkService.sh

2.3 创建脚本触发

crontab -e

加入如下配置,

*/5 * * * * bash ~/scripts/checkService.sh
Bash
如何在远程主机执行函数?

1 前言 一个问题,一篇文章,一出故事。 笔者今天想在远程机器执行本地脚本定义的函数,于是整理当前章 …

Bash
如何实现监视多台服务器的日志?

1 前言 一个问题,一篇文章,一出故事。 今天遇到需要根据PostFix的特定邮箱地址触发一个电话报 …

Bash
如何用Base Shell推送华为消息?

1 前言 一个问题,一篇文章,一出故事。 今天遇到服务器推送华为消息失败,于是尝试使用curl去测试 …