这个是老毛子路由器上用的脚本,由于碳云的nat服务器公网IP不断的变,因此只好通过ddns来稳定连接nat服务器了。


顺便水一篇文章,大家新年快乐。

使用前需要将域名添加到 DNSPod 中,并添加一条A记录,使用之后将自动更新ip.(非必要,这个脚本也会自动添加解析)
dnspod账户·密码 和 DNSPod Token 选填一组,推荐使用DNSPod Token,可以保护账户安全
【dnspod.cn 】 中国版 点 这里 查看官方说明以及如何获取DNSPod Token
【dnspod.com】国际版 点 这里 查看官方说明以及如何获取DNSPod Token
【注意】不要开启D-Token,会影响API使用。

基于 DNSPod 用户 API 实现的纯 Shell 动态域名客户端,优先适配网卡地址,无法获得合法外网地址则使用外部接口获取 IP 地址

准备环境

apt -y install curl wget git

获取API

这个脚本只支持DNSPod API(2.0),由这里进行获取:
apt-token

配置

git clone https://github.com/rehiy/dnspod-shell.git

编辑ddnspod.sh,分别修改/your_real_path/ardnspod、arToken和arDdnsCheck为真实信息.
比如我只解析ipv4,那就如下所示:

#!/bin/sh
# 

# Import ardnspod functions
. /root/dnspod-shell/ardnspod

# Combine your token ID and token together as follows
arToken="22312325,c6b13213884dbd4423123231236"

# Place each domain you want to check as follows
# you can have multiple arDdnsCheck blocks

# IPv4:
arDdnsCheck  "baidu.com" "sh"

修改下ardnspod,以解析公网IP而非内网IP
如下所示:

vim ardnspod

case $(uname) in
    'Linux')
       # hostIp=$(ip -o -4 addr list | grep -Ev '\s(docker|lo)' | awk '{print $4}' | cut -d/ -f1 | grep -Ev "$lanIps")
       hostIp=$(curl -s https://v4.myip.la)
        ;;
    Darwin|FreeBSD)
        hostIp=$(ifconfig | grep "inet " | grep -v 127.0.0.1 | awk '{print $2}' | grep -Ev "$lanIps")
    ;;
esac

运行ddnspod.sh,开启循环更新任务;建议将此脚本支持添加到计划任务;

成功运行后,结果如下所示:

root@coal-299r2bvb:~/dnspod-shell# ./ddnspod.sh 
Fetching Host Ip
> Host Ip: 139.226.50.77
> Record Type: A
Fetching Ids of sh.baidu.com
> Domain Ids: 76015004 1050820226
Checking Record for sh.baidu.com
> Last Ip: 1.1.1.1
Updating Record for sh.cve.pub
> arDdnsUpdate - success

如果是相同的IP,就不会提交请求,解决了dnspod api如果有相同IP请求过多导致一段时间不能请求的问题。

定时更新

一般人用cron,但Systemd也可以创建,并且使用Systemd可以记录下日志
1.首先我们使用一个脚本叫做/root/dnspod-shell/ddnspod.sh,脚本内容就是更新ddns任务:
2.然后需要创建一个 Service单元 ddns

vim /usr/lib/systemd/system/ddns.service 

[Unit]
Description=ddns
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/root/dnspod-shell/
ExecStart=/root/dnspod-shell/ddnspod.sh

[Install]
WantedBy=multi-user.target

然后把 ddns 作为系统服务。

systemctl start ddns

3.创建 Timer 单元

由于碳云的更新IP后很影响用户,因此可以设置每分钟检测一次。

可以写成

vim /usr/lib/systemd/system/ddns.timer

[Unit]
Description=Run ddns  every 1m

[Timer]
OnBootSec=5min
OnUnitActiveSec=1min
Unit=ddns.service

[Install]
WantedBy=timers.target

启动定时任务

systemctl  daemon-reload  #重新加载配置
systemctl  start  ddns.timer # 启动定时任务
systemctl  enable  ddns.timer # 启动定时任务

使用systemctl list-timers检查是否定时执行


参考:
rehiy/dnspod-shell
Systemd 定时器教程

最后修改:2022 年 04 月 07 日
如果觉得我的文章对你有用,请随意赞赏