shell脚本:监控HTTP服务的状态(测试返回码)

#定义函数check_http: html

#使用curl命令检查http服务器的状态 #-m设置curl无论访问成功或失败,最大消耗的时间为5秒,5秒链接服务为相应则视为没法链接bash

#-s设置静默链接,不显示链接时的链接速度、时间消耗等信息 服务器

#-o将curl下载的页面内容导出到/dev/null(默认会在屏幕显示页面内容) curl

#-w设置curl命令须要显示的内容%{http_code},指定curl返回服务器的状态码ide


#!/bin/bash
#Author:丁丁历险(Jacob)
#设置变量,url为你须要检测的目标网站的网址(IP或域名)
url=http://192.168.4.5/index.html
 
#定义函数check_http:
#使用curl命令检查http服务器的状态
#-m设置curl无论访问成功或失败,最大消耗的时间为5秒,5秒链接服务为相应则视为没法链接
#-s设置静默链接,不显示链接时的链接速度、时间消耗等信息
#-o将curl下载的页面内容导出到/dev/null(默认会在屏幕显示页面内容)
#-w设置curl命令须要显示的内容%{http_code},指定curl返回服务器的状态码
check_http(){
status_code=$(curl -m 5 -s-o /dev/null -w %{http_code} $url)
}
 
while :
do
       check_http
       date=$(date +%Y%m%d-%H:%M:%S) 
#生成报警邮件的内容
       echo "当前时间为:$date
       $url服务器异常,状态码为${status_code}.
       请尽快排查异常." > /tmp/http$$.pid
       
#指定测试服务器状态的函数,并根据返回码决定是发送邮件报警仍是将正常信息写入日志
       if [ $status_code -ne 200 ];then
              mail -s Warning root < /tmp/http$$.pid
       else
              echo "$url链接正常" >> /var/log/http.log
       fi
       sleep 5
done
相关文章
相关标签/搜索