当前位置:首页 > Mikrotik > 正文

适用于 RouterOS v7.x,IPv6 + DNSPod DDNS 自动更新脚本(带缓存 + 检测)

# ========== IPv6 + DNSPod DDNS 自动更新脚本 ==========
# ? 适用于 RouterOS v7.x,逻辑与你 IPv4 脚本一致(带缓存 + 检测)

# DNSPod API Token
:local token "0000,000000000000000000000000"

# 域名与主机名
:local domain "0cloud.cc"
:local subdomain "000"
:local dname ($subdomain . "." . $domain)

# 缓存文件(保存上次 IPv6)
:local cachefile "lastipv6.txt"

# 接口名称(IPv6 来源)
:local interface "bridge1"

# ========== Step 1: 获取当前接口 IPv6 ==========
:local ipv6 [/ipv6/address get [find interface=$interface && global] address]
:if ($ipv6 = "") do={
    :log warning ("[".$dname."] 未获取到全局IPv6地址,退出")
    :error "No IPv6"
}

# 去掉 /128 或 /64
:set ipv6 [:pick $ipv6 0 [:find $ipv6 "/"]]

# 简单校验 IPv6 格式
:if ([:find $ipv6 ":"] = nil) do={
    :log warning ("[".$dname."] 获取IPv6格式异常:" . $ipv6)
    :error "Invalid IPv6"
}

# ========== Step 2: 读取缓存 ==========
:local lastipv6 ""
:if ([:len [/file find name=$cachefile]] > 0) do={
    :set lastipv6 [/file get $cachefile contents]
    :set lastipv6 [:pick $lastipv6 0 [:len $lastipv6]]
}

# ========== Step 3: 比较是否变化 ==========
:if ($ipv6 = $lastipv6) do={
    :log info ("[".$dname."] IPv6 未变化,无需更新 (" . $ipv6 . ")")
    :return
}

# ========== Step 4: 获取 DNSPod 记录 ==========
:local record [/tool fetch url="https://dnsapi.cn/Record.List" \
    http-data="login_token=$token&format=json&domain=$domain&sub_domain=$subdomain&record_type=AAAA" \
    as-value output=user]

:set record ($record->"data")
:set record [:pick $record [:find $record "\"records\":"] [:len $record]]

:local recordid [:pick $record ([:find $record "\"id\":\""]+6) [:find $record "\",\"ttl"]]
:local recordip [:pick $record ([:find $record "\"value\":\""]+9) [:find $record "\",\"en"]]

# ========== Step 5: 判断是否更新 ==========
:if ($recordip != $ipv6) do={
    :log info ("[".$dname."] 检测到 IPv6 变化,旧:" . $recordip . " → 新:" . $ipv6)
    /tool fetch url="https://dnsapi.cn/Record.Ddns" \
        http-data="login_token=$token&format=json&domain=$domain&sub_domain=$subdomain&record_id=$recordid&record_line_id=0&record_type=AAAA&value=$ipv6" \
        output=none
    :log info ("[".$dname."] IPv6 已更新为 " . $ipv6)
    /file remove $cachefile
    /file print file=$cachefile
    /file set $cachefile contents=$ipv6
} else={
    :log info ("[".$dname."] DNSPod AAAA 记录已是最新,无需更新")
    /file remove $cachefile
    /file print file=$cachefile
    /file set $cachefile contents=$ipv6
}

更新时间 2025-10-12