12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- #!/bin/bash
- # 获取当前时间
- current_time=$(date "+%Y%m%d%H%M")
- # 备份/etc/hosts文件
- backup_file="/opt/host/hosts.$current_time"
- cp /etc/hosts "$backup_file"
- # 下载远程文件
- curl -s -o hosts_product.txt http://172.20.45.131:11082/BaseService/jyhosts/raw/master/hosts_product.txt
- # 检查文件是否成功下载
- if [ $? -ne 0 ]; then
- echo "无法下载远程文件"
- exit 1
- fi
- # 对比文件内容并替换
- add_count=0
- while IFS= read -r line || [[ -n "$line" ]]; do
- domain=$(echo "$line" | awk '{print $2}')
- ip=$(echo "$line" | awk '{print $1}')
-
- # 检查是否存在域名
- grep -q "$domain" /etc/hosts
-
- if [ $? -eq 0 ]; then
- # 域名存在,检查IP是否一致
- existing_ip=$(grep "$domain" /etc/hosts | awk '{print $1}')
- if [ "$existing_ip" != "$ip" ]; then
- # IP不一致,进行替换
- add_count=$((add_count+1))
- sed -i "s/^$existing_ip[[:space:]]*$domain/$ip $domain/" /etc/hosts
- fi
- else
- # 域名不存在,新增
- add_count=$((add_count+1))
- echo "$ip $domain" >> /etc/hosts
- fi
- done < hosts_product.txt
- echo "replace success: ${add_count}"
|