#! /bin/bash
#检测网络连接
#设置检测的IP
initIp(){
#echo $1
if [ -n "$1" ];then
ip=$1
else
ip=10.1.2.1
fi
echo 初始化ip=$ip
}
#循环检查
pingCheck(){
retry=0
alarm=false
while true
do
pingAct
if [ $? -eq 0 ];then
retry=0
if $alarm ;then
#通知钉钉恢复了
sendMsg "小妹:网络已恢复"
fi
alarm=false
else
retry=$((retry + 1))
if [ $retry -gt 3 ];then
echo 是否已通知 $alarm
if ! $alarm ;then
sendMsg "小妹:深圳到重庆网络断了"
#钉钉机器人
alarm=true
fi
else
echo 连续检测$retry次报错了
fi
fi
sleep 1s
done
}
#ping
pingAct(){
echo 检测IP=$ip
ping -c 1 $ip > /dev/null 2>&1
}
#发送钉钉机器人通知
sendMsg(){
curl --location --request POST 'https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxxxxx' \
--header 'User-Agent: Apifox/1.0.0 (https://apifox.com)' \
--header 'Content-Type: application/json' \
--header 'Accept: */*' \
--header 'Host: oapi.dingtalk.com' \
--header 'Connection: keep-alive' \
--data-raw "{'at':{'atUserIds':[],'isAtAll':false},'text':{'content':'$1'},'msgtype':'text'}"
}
main(){
initIp $1
pingCheck
}
#开始执行
main $1
用法:nohup bash networkcheck.sh [ip] > log 2>&1 &