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

固定内网v4 + ip.0cloud.cc/ip + DNSPod DDNS 更新(带缓存)适用于 RouterOS 7.x

# 固定内网 + ip.0cloud.cc/ip + DNSPod DDNS 更新(带缓存)
# 适用于 RouterOS 7.x

# DNSPod API Token(格式:ID,Key)
:local token "***,******************"

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

# 缓存文件,用于保存上次 IP
:local cachefile "lastip.txt"

# 临时文件,用于保存当前公网 IP
:local tmpfile "ip.txt"

/file remove $tmpfile
:delay 1

# ? 获取公网 IP(改为你自己的网站)
/tool fetch url="http://ip.0cloud.cc/ip/" mode=http dst-path=$tmpfile
:local ipaddr [/file get $tmpfile contents]
/file remove $tmpfile

# 去掉换行符
:set ipaddr [:pick $ipaddr 0 [:len $ipaddr]]

# 验证 IP 格式
:if ([:len $ipaddr] < 7 || [:find $ipaddr "."] = nil) do={
    :log warning ("[".$dname."] 获取公网IP失败:" . $ipaddr)
    :error "公网 IP 获取失败"
}

# 读取上次 IP(如果存在)
:local lastip ""
:if ([:len [/file find name=$cachefile]] > 0) do={
    :set lastip [/file get $cachefile contents]
    :set lastip [:pick $lastip 0 [:len $lastip]]
}

# 判断是否与上次相同
:if ($ipaddr = $lastip) do={
    :log info ("[".$dname."] 公网IP未变化,无需更新 (" . $ipaddr . ")")
    :return
}

# 获取 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=A" \
    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"]]

# 判断是否需要更新
:if ($recordip != $ipaddr) do={
    :log info ("[".$dname."] 检测到 IP 变化,旧:" . $recordip . " → 新:" . $ipaddr)
    /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&value=$ipaddr" \
        output=none
    :log info ("[".$dname."] 域名 IP 已更新为 " . $ipaddr)
    /file remove $cachefile
    /file print file=$cachefile
    /file set $cachefile contents=$ipaddr
} else={
    :log info ("[".$dname."] DNSPod 记录已是最新,无需更新")
    /file remove $cachefile
    /file print file=$cachefile
    /file set $cachefile contents=$ipaddr
}

更新时间 2025-10-12