synchosts.sh 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/bin/bash
  2. # 获取当前时间
  3. current_time=$(date "+%Y%m%d%H%M")
  4. # 备份/etc/hosts文件
  5. backup_file="/opt/host/hosts.$current_time"
  6. cp /etc/hosts "$backup_file"
  7. # 下载远程文件
  8. curl -s -o hosts_product.txt http://172.20.45.131:11082/BaseService/jyhosts/raw/master/hosts_product.txt
  9. # 检查文件是否成功下载
  10. if [ $? -ne 0 ]; then
  11. echo "无法下载远程文件"
  12. exit 1
  13. fi
  14. # 对比文件内容并替换
  15. add_count=0
  16. while IFS= read -r line || [[ -n "$line" ]]; do
  17. domain=$(echo "$line" | awk '{print $2}')
  18. ip=$(echo "$line" | awk '{print $1}')
  19. # 检查是否存在域名
  20. grep -q "$domain" /etc/hosts
  21. if [ $? -eq 0 ]; then
  22. # 域名存在,检查IP是否一致
  23. existing_ip=$(grep "$domain" /etc/hosts | awk '{print $1}')
  24. if [ "$existing_ip" != "$ip" ]; then
  25. # IP不一致,进行替换
  26. add_count=$((add_count+1))
  27. sed -i "s/^$existing_ip[[:space:]]*$domain/$ip $domain/" /etc/hosts
  28. fi
  29. else
  30. # 域名不存在,新增
  31. add_count=$((add_count+1))
  32. echo "$ip $domain" >> /etc/hosts
  33. fi
  34. done < hosts_product.txt
  35. echo "replace success: ${add_count}"