更新hosts,将无效地址注释,地址恢复有效后再打开
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#!/bin/bash ###################################### #功能说明:当域名失效时自动注释掉。可用之后自动打开 # #使用说明:请把本脚本放在定时任务中执行。 ##################################### IPS=$(cat /etc/hosts|awk '{print$1}') for IP in $IPS; do if [ "$(echo $IP|awk -F '.' '{print$1}'|sed 's#[0-9]##g')" = "#" ];then EIP=$(echo $IP|sed '/#/ s/#//g') ping $EIP -c1 >>/dev/null if [ $? -eq 0 ];then sed -i "/$EIP/ s/#//g" /etc/hosts fi else ping $IP -c1 >>/dev/null if [ $? -gt 0 ];then sed -i "s/$IP/#$IP/g" /etc/hosts fi fi done
更新hosts中指定域名
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#!/bin/bash url=https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID url_name=qyapi.weixin.qq.com IPS=$(cat /etc/hosts|grep ${url_name}|awk '{print$1}') for IP in $IPS; do echo "当前映射,${url_name} 的公网ip地址:$IP" #resolve需要libcurl版本7.21.3才支持 status_code=$(curl --resolve $url_name:443:$IP -m 5 -s -o /dev/null -w %{http_code} $url) echo "$url服务器,状态码为${status_code}" #指定测试服务器状态的函数,并根据返回码决定是发送邮件报警还是将正常信息写入日志 if [ "$status_code" != "200" ];then #删除/etc/hosts里面的qyapi.weixin.qq.com对应的第一个IP的行 #如果要使用shell变量,就需要使用双引号 sed -i "/$IP/d" /etc/hosts echo "成功删除无效IP映射,IP:$IP" else echo "$url测试正常" fi done
使用ping判断域名是否访问成功
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#!/bin/bash url=https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID url_name=qyapi.weixin.qq.com check_http(){ status_code=$(curl -m 5 -s -o /dev/null -w %{http_code} $url) } url_ip=`ping ${url_name} -c 1 | sed '1{s/[^(]*(//;s/).*//;q}'` echo "${url_name} 的公网ip地址:${url_ip}" echo "$url_ip $url_name" >> /etc/hosts update_host(){ if [ $url_ip != "" ];then #删除/etc/hosts里面的qyapi.weixin.qq.com的行 sed '/$url_name/'d /etc/hosts #新增host echo "$url_ip $url_name" >> /etc/hosts fi } while : do check_http date=$(date +%Y%m%d-%H:%M:%S) echo "当前时间为:$date" echo "$url服务器,状态码为${status_code}" #指定测试服务器状态的函数,并根据返回码决定是发送邮件报警还是将正常信息写入日志 if [ "$status_code" != "200" ];then update_host else echo "$url测试正常" fi sleep 5