菜单
展开边栏 收起边栏

通过脚本监听域名ip并写入hosts中

最近自己的一个小需求,做一个笔记!

1、先创建一个脚本 update_hosts.sh

#!/bin/bash

# 监听 home.jiangfei.net 的 IP 地址
ip=$(dig +short domain.com)

# 检查是否成功获取到 IP
if [[ -n $ip ]]; then
    # 将多个域名指向此 IP 并写入 hosts 文件中
    domains=(domain1.com domain2.com domain3.com)
    
    for domain in "${domains[@]}"; do
        if ! grep -q "$ip" /etc/hosts || ! grep -q "$domain" /etc/hosts; then
            echo "$ip $domain" >> /etc/hosts
        fi
    done
    
    # 重启网络服务以更新 DNS 缓存
    systemctl restart network.service
fi

 

2、将以上代码保存为 update_hosts.sh,然后赋予执行权限:

chmod +x update_hosts.sh

 

3、接下来,您可以设置定时任务来每隔一段时间自动运行此脚本。使用以下命令打开当前用户的 crontab 文件进行编辑:

crontab -e

 

4、在文件末尾添加以下行来每隔 10 分钟运行该脚本:

*/10 * * * * /path/to/update_hosts.sh

注意将 /path/to 替换为脚本的实际路径。

 

5、最后,您可以将此脚本添加到系统启动项来确保在系统启动时自动运行。将以下行添加到 /etc/rc.local 文件的末尾:

/path/to/update_hosts.sh &

注意在行末添加 & 符号以在后台运行该脚本。

 

 

Copyright © 2008-. JiangFei.net all rights reserved 苏ICP备18062911号