shell脚本学习
目的
编写shell脚本,定时请求某接口并监听接口请求时间,当请求较慢时发送预警
实现
- 编写脚本文件
#创建文件
vi excute.sh
#文件内容
#!/bin/bash
declare -i end=3
declare -i line_num=1
max_time=1.500
one=
two=
three=
#循环请求三次
for((i=0;i<$end;i++))
do
curl -A "Alipay" -o /tmp/shelltest/curl.txt -s -w '%{time_total}' http://XXXXXX >> /tmp/shelltest/curltime.txt
echo \ >> curltime.txt
done
#读取请求时间
while read line
do
echo $line
if [ $line_num -eq 1 ]; then
one=$line
elif [ $line_num -eq 2 ]; then
two=$line
elif [ $line_num -eq 3 ]; then
three=$line
else
echo 'out range line:'$line_num
fi
line_num=$(($line_num+1))
done < /tmp/shelltest/curltime.txt
#计算平均请求时长并发送报警
avg_time=$(echo "scale=3;($one+$two+$three)/$end"|bc)
echo 'avg_time:'$avg_time
if [ `echo "$avg_time > $max_time"|bc` -eq 1 ] ; then
curl 'https://oapi.dingtalk.com/robot/send?access_token=XXXXXX' \
-H 'Content-Type: application/json' \
-d '{"msgtype":"text","text": {"content":"模糊查询请求耗时:'$avg_time',请查看具体原因"}}'
else
echo "请求正常"
fi
rm -rf curltime.txt
- 脚本文件授权
chmod 755 excute.sh
- 设置定时参数
#编辑定时任务
crontab -e
#添加相应的任务
*/5 * * * * /tmp/shelltest/excute.sh