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/sendSmsApi

echo "-----------------------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 3
  else
    echo "检查正常!"
    break
  fi
done


warn_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" ]
then
  echo "state file is already exists"
else
  touch "$shell_path/$api_md5.state"
  echo 0 > $shell_path/$api_md5.state
  is_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 ]
then
  echo 1 > $shell_path/$api_md5.state
  echo "发送短信 $warn_msg"
  #curl 调用接口发送告警短信
  curl -H "Content-Type: application/json" -X POST -d '{"phoneNo": "131xxxxxxxx","sms": "'$warn_msg'"}' $msg_api
fi


if [ $is_create_file -eq 0 ] && [ $state -eq 1 ] && [ $sumTime -le $timeout ] && [ $response_code -eq '200' ]
then
  echo 0 > $shell_path/$api_md5.state
  echo "发送短信 $ok_msg"
  curl -H "Content-Type: application/json" -X POST -d '{"phoneNo": "131xxxxxxxx","sms": "'$ok_msg'"}' $msg_api
fi

echo `date "+%Y-%m-%d %H:%M:%S"`
echo "-----------------------check api end-----------------------"

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值