shell脚本定时任务实现接口监测(响应时长、响应码)告警

脚本基于curl实现,用于检测接口或页面请求响应码和响应时长。尝试三次异常则触发告警,不会重复触发告警。告警恢复时提示。检测频率由crontab定时任务配置。

#!/bin/bash
# 默认参数 api接口
check_api=${1:-http://xxxx/api}
# 默认参数 超时时间5s
timeout=${2:-5}
#告警状态文件
shell_path=/xxx/xxx/shell/check_api_state
#告警短信接口
msg_api=http://xxx/sendSmsApiecho "-----------------------check api start-----------------------"
echo `date "+%Y-%m-%d %H:%M:%S"`i=1
error_times=0
#第一次正常则返回,有异常则进行三次检测
while [ $i -le 3 ];do#调用接口计时start_time=`date "+%Y-%m-%d %H:%M:%S"`#curl $check_api 进行接口测试response_code=`curl -I -s -m 10 $check_api |grep HTTP|awk '{print $2}'`end_time=`date "+%Y-%m-%d %H:%M:%S"`#计算响应时间st=`date -d  "$start_time" +%s`et=`date -d  "$end_time" +%s`sumTime=$(($et-$st))echo "接口:$check_api,第$i次接口检查"echo "开始时间:$start_time,结束时间:$end_time。请求用时:$sumTime s,响应码:$response_code。"((i++))# 判断接口响应时长、响应码是否正常if [ $sumTime -ge $timeout -o $response_code -ne '200' ];then((error_times++))#接口异常(可能是网络波动)等待3s 进行下一次检测sleep 3elseecho "检查正常!"breakfi
donewarn_time=`echo ${start_time// /#}`
warn_msg="【xxx告警】接口$check_api异常,请求耗时$sumTime(s),响应码为$response_code,告警时间:$warn_time。" 
ok_msg="【xxx告警】接口$check_api已恢复,请求耗时$sumTime(s),响应码为$response_code,恢复时间:$warn_time。"api_md5=`echo -n $check_api|md5sum|cut -d ' ' -f1`
is_create_file=0
if [ -f "$shell_path/$api_md5.state" ]
thenecho "state file is already exists"
elsetouch "$shell_path/$api_md5.state"echo 0 > $shell_path/$api_md5.stateis_create_file=1
fi
state=`cat $shell_path/$api_md5.state`
#echo "$check_api state_code $state"echo "异常次数 $error_times,告警状态 $state [0未告警,1已告警]"#三次检测全部异常 进行短信告警
if [ $error_times -eq 3 ] && [ $state -eq 0 ]
thenecho 1 > $shell_path/$api_md5.stateecho "发送短信 $warn_msg"#curl 调用接口发送告警短信curl -H "Content-Type: application/json" -X POST -d '{"phoneNo": "131xxxxxxxx","sms": "'$warn_msg'"}' $msg_api
fiif [ $is_create_file -eq 0 ] && [ $state -eq 1 ] && [ $sumTime -le $timeout ] && [ $response_code -eq '200' ]
thenecho 0 > $shell_path/$api_md5.stateecho "发送短信 $ok_msg"curl -H "Content-Type: application/json" -X POST -d '{"phoneNo": "131xxxxxxxx","sms": "'$ok_msg'"}' $msg_api
fiecho `date "+%Y-%m-%d %H:%M:%S"`
echo "-----------------------check api end-----------------------"


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部