By monitoring web shell is normal, then trigger e-mail alerts

Recently on the Internet looking at writing a shell script to monitor via web page is normal, if not normal, the trigger e-mail alerts, there is a notification mail repair after repair; but has not found full, so under their own research, write a docking linux-mail and through the shell to write a script to monitor the page, if interested can refer to, but I am also a novice, badly written, please do not take offense. 

In two major steps:

Step one linux butt-mail:
1. First you need to install mailx
If you are minimizing installation of centos / redhat system, there is no built-mailx, that is no mail command.

 yum -y install mailx

2. Edit the configuration file /etc/mail.rc
vim /etc/mail.rc | tail -10
fwdretain subject date from to
# For Linux and BSD, this should be set.
set bsdcompat
set smtp=smtp.163.com
set smtp-auth-password=123456
set smtp-auth=login
3. Configuration instructions
from: When you receive a message other display to the senders
smtp: appoint a third party's mail smtp server address (such as qq, 163, but also the company's mail server)
set smtp-auth-user: email account username
set smtp-auth-password: e-mail account password, fill in some mailboxes authorization code
smtp-auth: SMTP authentication method, the default is login, you can also change the way PLAIN or CRAM-MD5.
4. Test mailbox is successfully docked
echo "访问OK." | mail -s " 访问已经恢复" [email protected]
步骤二shell编写监控的URL:
vim checkweb.sh
#!/bin/bash
#需要接收告警的邮箱
#网站url地址
URL="http://www.baidu.com"
logsize=`ls -l /data/script/checkweb.log| awk '{print $5}'`
if [ -n $logsize ]
then
>/data/script/checkweb.log
fi
while true
date=$(date -d "today" +"%Y-%m-%d-%H:%M:%S")
do
sleep 60
#获取http响应代码
HTTP_CODE=`curl -o /dev/null -s -w "%{http_code}" "${URL}"`
#服务器能正常响应,应该返回200的代码
if [ $HTTP_CODE = 200 ]
then
if [ -f /tmp/checkwebfault.log ]
then
`rm -rf /tmp/checkwebfault.log`
else
echo "$date $URL 访问OK." >>/data/script/checkweb.log
[ ! -f "/tmp/checkwebsucceed" ] || continue
echo "$date $URL 故障已修复." | mail -s "网站故障已经修复" $mail1 $mail2
`touch /tmp/checkwebsucceed`
fi
elif [ $HTTP_CODE != 200 ] && [ ! -f "/tmp/checkwebfault.log" ]
then
echo "$date $URL 已无法访问,请尽快处理." | mail -s "网站紧急故障告警" $mail1 $mail2
`touch /tmp/checkwebfault.log`
`rm -rf /tmp/checkwebsucceed `
fi
done
脚本思路:
1.通过CURL访问后判断这个URL里面返回的值是否为200;如果是则页面正常,否则不正常;
2.如果正常,检查是否有错误的临时文件,有则删除,如果没有临时错误文件,则会发送一个邮件通知是成已经修复,且会生成一个成功的临时文件,后面通过判断这个文件是否存来判断是否还需要发送邮件,避免无休止发送邮件告警;(continue是跳出此次循环)
3.如果不正常,也会发送一个URL故障的邮件通知,且会生成一个失败的临时文件,后面通过判断这个文件是否存来判断是否还需要发送邮件,避免无休止发送邮件告警,且会把成功的临时文件删除;
总的来说就是开关原理,通过判断临时文件是否存在来判断是否需要发送邮件,避免无休止发送告警。
测试查看执行判断的过程
sh -x checkweb.sh

Guess you like

Origin www.cnblogs.com/--smile/p/11241272.html