您的位置:首页 > 运维架构 > Shell

shell脚本监控网站是否正常

2019-06-11 17:32 1566 查看
#!/bin/bash
#20190611 url.txt文件直接填写需要监控的网址 第三版
#QQ450433231
time=`date +"%Y/%m/%d %H:%M.%S"`
[ ! -f /root/url.txt ] && echo "url.txt文件不存在" && exit 1

while read url
do
nslookup $url >/dev/null 2>&1
if [ $? -ne 0 ] ;then
echo "$time $url 网页无法解析" >> checkfail.log
continue
else
for((i=1;i<4;i++))
do
connect=`curl -i -s $url|grep "200 OK"|wc -l`
if [ $connect -eq 1 ];then
echo "$time 第$i次检查$url网页访问成功" >> check.log
break
elif [ $i = 3 ];then
echo "$time $url 网页第$i次无法访问"|mail -s "网页不可达告警" 450433231@qq.com
echo "$time 第$i次检查$url网页访问失败" >> checkfail.log
else
echo "$time 第$i次检查$url网页访问失败" >> checkfail.log
fi
done
fi
done < /root/url.txt

-------------------------------------------------------

1. 发送邮件 配置/etc/mail.rc就可以实现 百度教程一堆
2. 如何使用
/root目录下创建脚本 
vi check.sh
授权可执行权限
chmod +x check.sh
每3分钟执行一次脚本 调用crontab
crontab –e
*/3 * * * * sh /root/check.sh

监控网站可达性,当网站出现3次访问不可达的情况发出邮件告警。每3分钟扫描网页,扫描频率可修改;

--------------------------------------
以下是前面写的2个版本 后来想想还是优化下
#!/bin/bash
#20190611 第二版本
check(){
connect=`curl -i -s $url|grep "200 OK"|wc -l`
}
time=`date +"%Y/%m/%d %H:%M.%S"`
[ ! -f /root/url.txt ] && echo "url.txt文件不存在" && exit 1

while read url
do
nslookup $url >/dev/null 2>&1
if [ $? -ne 0 ] ;then
echo "$time $url 网页无法解析" >> $0.faillog
    continue
else
echo "" >> $0.log
fi
check
if [ $connect -eq 1 ];then
echo "$time 第1次检查$url网页访问成功" >> $0.log
else
echo "$time 第1次检查$url网页访问失败" >> $0.faillog
check
if [ $connect -eq 1 ];then
echo "$time 第2次检查$url网页访问成功" >> $0.log
else
echo "$time 第2次检查$url网页访问失败" >> $0.faillog
check
if [ $connect -eq 1 ];then
echo "$time 第3次检查$url网页访问成功" >> $0.log
else
    echo "$time $url 网页3次无法访问"|mail -s "网页不可达告警" 450433231@qq.com
                echo "$time $url 网页3次无法访问" >> $0.faillog
fi
   fi
fi
done < /root/url.txt

#!/bin/bash
#第一版 
while read url
do
connect1=`curl -i -s $url|grep "200 OK"|wc -l`
if [ $connect1 -eq 1 ];then   
  echo `date +"%Y/%m/%d %H:%M.%S"` check $url first success >>/root/connect.log 
else
      connect2=`curl -i -s $url|grep "200 OK"|wc -l`
      echo `date +"%Y/%m/%d %H:%M.%S"` check $url first fail >>/root/fail.log
if [ $connect2 -eq 1 ];then
    echo `date +"%Y/%m/%d %H:%M.%S"` check $url second success >>/root/connect.log
else
    connect3=`curl -i -s $url|grep "200 OK"|wc -l`
echo `date +"%Y/%m/%d %H:%M.%S"` check $url second fail >>/root/fail.log
if [ $connect3 -eq 1 ];then
    echo `date +"%Y/%m/%d %H:%M.%S"` check $url success >>/root/connect.log
else
    echo `date +"%Y/%m/%d %H:%M.%S"` Check $url for three failed visits|mail -s "网页不可达告警" 450433231@qq.com
                echo `date +"%Y/%m/%d %H:%M.%S"` check $url Third fail >>/root/fail.log
fi
fi
fi
done < /root/url.txt


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: