Bash脚本编写

注意事项:

  1. 赋值不能有空格 name=13
  2. 判断语句 【】前后要有空格
  3. ``和$()效果一样
  4. 执行命令会fork 子shell,所以要加上足够长的sleep,确保上一个子shell退出

log(){
lvl=$1
msg=$2
current_date=$(date +"%Y-%m-%d")
current_time=$(date +"%H:%M:%S")
echo $current_date $current_time $lvl $msg
}

fetchIDP(){
local lkey=$2
local ltimeout=$1
$(curl -X POST -s -o ./idp_mon.tmp --max-time ${ltimeout} -k -d ${lkey} https://www.baidu.com) # 发送curl请求并将响应保存到response变量中
exit_code=$?
response=$(cat ./idp_mon.tmp)

ret=0
if [ $exit_code -eq 0 ]; then
# Check if the response contains the expected string
if [[ $response == "ICP" ]]; then
log "INFO: " "Success"
ret=1
else
log "WARN: " "Response does not contain the expected string"
fi
elif [ $exit_code -eq 28 ]; then
log "ERROR: " "Timeout"
else
log "ERROR: " "occurred: $exit_code"
fi
return $ret
}

while true; do
unset http_proxy
unset https_proxy
result0=curl -k -L https://www.baidu.com/profile.jsp
key=echo ${result0}|awk -F '"' '{print $12}'

max_retries=100 # 设置最大重试次数
for ((i=1; i<=max_retries; i++)); do
export https_proxy=http://test1:BNi@10.120.2.169:8080
export http_proxy=http://test1:BNi@10.120.2.169:8080

fetchIDP 30 $key
firstRet=$?
# 重试一次
if [ $firstRet -eq 0 ]; then
sleep 2
fetchIDP 60 $key
secondRet=$?
if [ $secondRet -eq 0 ]; then
log "DEBUG: " "failed"
echo "idp service failed" > /tmp/idp_mon.stat
break
fi
fi
echo 'success' > /tmp/idp_mon.stat
sleep 200 # 间隔1分钟
done
done

posted on 2023-06-29 11:43  IT老友  阅读(47)  评论(0)    收藏  举报

导航