此脚本适合openwrt
root目录新建update_hosts.sh

#!/bin/bash

# 域名和对应的hosts条目
declare -A DOMAINS
DOMAINS=(
  ["pixman.io.ystenlive.dnsany.com"]="cache.ott.ystenlive.itv.cmvideo.cn"
  ["pixman.io.bestlive.dnsany.com"]="cache.ott.bestlive.itv.cmvideo.cn"
  ["pixman.io.wasulive.dnsany.com"]="cache.ott.wasulive.itv.cmvideo.cn"
  ["pixman.io.fifalive.dnsany.com"]="cache.ott.fifalive.itv.cmvideo.cn"
  ["pixman.io.hnbblive.dnsany.com"]="cache.ott.hnbblive.itv.cmvideo.cn"
)

# 备份现有的hosts文件
cp /etc/hosts /etc/hosts.bak

# 删除旧的相关条目,只删除定义的域名对应的条目
for ENTRY in "${DOMAINS[@]}"; do
  sed -i "/ $ENTRY$/d" /etc/hosts
done

# 获取最新的IP地址并更新hosts文件
for DOMAIN in "${!DOMAINS[@]}"; do
  NEW_IP=$(ping -c 1 "$DOMAIN" | grep 'PING' | awk -F'[()]' '{print $2}' | awk '{print $1}')
  if [ -n "$NEW_IP" ]; then
    echo "$NEW_IP ${DOMAINS[$DOMAIN]}" >> /etc/hosts
  else
    echo "No IP found for $DOMAIN"
  fi
done

echo "Hosts file updated with latest IP addresses for domains: ${!DOMAINS[@]}"

设置脚本权限:

chmod +x update_hosts.sh

执行脚本:

./update_hosts.sh

可以在openwrt的计划任务里添加

0 */4 * * * /root/update_hosts.sh

每4个小时执行一次

如果是liunx系统脚本如下

#!/bin/bash

# 域名和对应的hosts条目
declare -A DOMAINS
DOMAINS=(
  ["pixman.io.ystenlive.dnsany.com"]="cache.ott.ystenlive.itv.cmvideo.cn"
  ["pixman.io.bestlive.dnsany.com"]="cache.ott.bestlive.itv.cmvideo.cn"
  ["pixman.io.wasulive.dnsany.com"]="cache.ott.wasulive.itv.cmvideo.cn"
  ["pixman.io.fifalive.dnsany.com"]="cache.ott.fifalive.itv.cmvideo.cn"
  ["pixman.io.hnbblive.dnsany.com"]="cache.ott.hnbblive.itv.cmvideo.cn"
)

# 备份现有的hosts文件
cp /etc/hosts /etc/hosts.bak

# 删除旧的相关条目,只删除我们定义的域名对应的条目
for ENTRY in "${DOMAINS[@]}"; do
  sed -i "/ $ENTRY$/d" /etc/hosts
done

# 获取最新的IP地址并更新hosts文件
for DOMAIN in "${!DOMAINS[@]}"; do
  NEW_IP=$(ping -c 1 $DOMAIN | grep 'PING' | awk '{print $3}' | tr -d '()')
  echo "$NEW_IP  ${DOMAINS[$DOMAIN]}" | sudo tee -a /etc/hosts > /dev/null
done

echo "Hosts file updated with latest IP addresses for domains: ${!DOMAINS[@]}"

为脚本添加执行权限:

chmod +x update_hosts.sh

使用crontab定时执行脚本:

crontab -e

然后在crontab文件中添加一行,例如每小时执行一次:

0 * * * * /path/to/update_hosts.sh
Last modification:August 9th, 2024 at 08:26 am