shell端口监听异常邮箱告警
阅读原文时间:2023年07月08日阅读:1

  业务场景:应用发布监听服务是否正常启动,因为服务器资源不够上不了prometheus、grafana,所以写的shell脚本监听。此脚本适用于初创公司及小微企业使用。

准备工作

除了shell脚本这里还使用到了expect脚本,expect类似有telnet你的服务端口返回相应的值判断应用端口是否正常开启。

yum install -y expect
vim script.exp

#!/usr/bin/expect
set timeout 2
set host [lindex $argv 0]
set port [lindex $argv 1]
spawn telnet $host $port
expect "*Escape character*"
send "\1D\r quit\r"

然后是主体脚本main.sh

#!/bin/bash
ip=$1 #从参数中获取目的IP
port=$2 #从参数中获取目的端口
AppName=$3 #从参数中获取服务名称
Fail=0 #失败标记
FailCount=0 #连续失败次数
Dmail=xxxxxxxxxx@qq.com #通知邮箱

while true
do
date=`date`
expect -f script.exp $ip $port | grep "Escape character" > $ip-$port.log
#截取script.exp脚本中返回的包含Escape character的行,重定向到日志文件中,如果telnet失败,则文件为空。注意第一次启动该脚本会自动创建日志文件,邮件也会异常提醒,重新运行后会就正常。
if [[ -s $ip-$port.log ]]
then
#若文件存在且不为空,则端口连通
if [[ $Fail -eq 1 ]]
#若端口连通且上一次为失败状态,则执行
then
echo -e "$ip $port $AppName 已恢复正常\n$date" >> success.txt | mailx -s "【xxxx环境】$AppName已恢复正常!" $Dmail < success.txt #发送邮件到XXXX@qq.com Fail=0 #重置失败标记 FailCount=0 #重置失败次数 cat /dev/null > success.txt
#邮件发送后清空日志文件,防止日志堆积发送。
fi
else
FailCount=$(( $FailCount+1 ))
#记录连续失败次数
if [[ $Fail -eq 0 ]]
then
#若端口不通且上一次为连通状态,则执行
echo -e "$ip $port $AppName 监听端口异常\n$date" >> fail.txt | mailx -s "【XXXX环境】$AppName异常请查看检查服务!!!" $Dmail < fail.txt Fail=1 #点亮失败标记 cat /dev/null > fail.txt
fi

    if \[\[ $FailCount -eq 180 \]\]  
    then  
        #若连续失败次数大于180次,重置失败标记及最大连续失败次数,若仍失败则再次发送邮件提醒。  
        FailCount=0  
        Fail=0  
    fi  
fi  
sleep 2  

done

邮箱通知设置

#邮箱配置教程:https://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
yum -y install mailx
vim /etc/mail.rc

set from=xxxxxxxxx@qq.com

这里必须和set smtp-auth-user的邮箱一样

set smtp=smtps://smtp.qq.com:465
set smtp-auth-user=xxxxxxxxx@qq.com
set smtp-auth-password=邮箱授权码
set smtp-auth=login
set ssl-verify=ignore
set nss-config-dir=/root/.certs

邮箱证书配置,避免不必要的异常。

mkdir -p /root/.certs/

echo -n | openssl s_client -connect smtp.qq.com:465 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ~/.certs/qq.crt
certutil -A -n "GeoTrust SSL CA" -t "C,," -d ~/.certs -i ~/.certs/qq.crt
certutil -A -n "GeoTrust Global CA" -t "C,," -d ~/.certs -i ~/.certs/qq.crt
certutil -L -d /root/.certs

cd /root/.certs
certutil -A -n "GeoTrust SSL CA - G3" -t "Pu,Pu,Pu" -d ./ -i qq.crt

#返回如下提示即可:
Notice: Trust flag u is set automatically if the private key is
present.

测试

#测试
mailx -s “邮箱测试” xxxx@qq.com < "hello world"

最后批量监控服务shell

#创建日志文件
touch fail.txt
touch success.txt

vim start.sh

#!/bin/bash
#目的ip 端口 服务名称
./main.sh ip prot XXXX &
./main.sh ip prot XXXX &
./main.sh ip prot XXXX &
./main.sh ip prot XXXX &

转载请备注原文链接!