这篇文章上次修改于 586 天前,可能其部分内容已经发生变化,如有疑问可询问作者。
脚本功能
定时检查域名的连通性,
如果不通,则从ip列表中遍历检查连通性
ip通则与域名绑定到 hosts 文件中
#!/bin/bash
DOMAIN=api.weixin.qq.com
IP_LIST='192.168.1.1 192.168.1.2 192.168.1.3 43.129.2.204 192.168.1.4'
HOSTS=/etc/hosts
BACKUP_DIR=backup
while true; do
echo "=======$(date +"%Y%m%d %H:%M:%S")======"
echo "checking connection of domain: ${DOMAIN}"
if ! ping -c 1 ${DOMAIN} &> /dev/null
then
echo "domain connection is down"
for ip in $IP_LIST
do
echo "checking connection of ip: ${ip}"
if ping -c 1 $ip &> /dev/null
then
# backup hosts 当前时间
# Get current date and time
CURRENT_TIME=$(date +"%Y%m%d_%H%M%S")
# Create backup directory if it doesn't exist
mkdir -p ${BACKUP_DIR}
# Backup hosts file with current date and time appended to the filename
cp ${HOSTS} ${BACKUP_DIR}/hosts_${CURRENT_TIME}
echo "connection is ok, write ${ip} to the file of: ${HOSTS}"
# Check if the domain does not exist in the hosts file
if ! grep -q "${DOMAIN}" ${HOSTS}; then
# If it does not exist, append the IP and domain to the hosts file
echo "${ip} ${DOMAIN}" >> ${HOSTS}
else
sed -i -e "/^[^#]/s/.* ${DOMAIN}/${ip} ${DOMAIN}/" $HOSTS
fi
break
fi
done
else
echo "domain connection is ok"
fi
echo "sleeping for 10s"
sleep 10
done
没有评论