前提需要一个域名并设置 NS 到 CloudFlare

DNS ID 获取方法:

curl -X GET "https://api.cloudflare.com/client/v4/zones/输入你的ZoneID/dns_records?type=A&name=设置的域名记录值(比如xxx.yourdomain.com)" \
-H "X-Auth-Email:你注册时的邮箱" \
-H "X-Auth-Key:你的APIKEY" \
-H "Content-Type: application/json"

运行该命令后会输出结果,找到"id":"xxx"这个选项,其中的xxx即对应你的DNSID值

Shell 脚本:

#!/bin/sh

EMAIL=你注册时的邮箱
CF_API_KEY=域名管理界面右下角 获取您的 API 令牌
CF_ZONE_ID=同样右下角 区域 ID
CF_DNS_ID=上面获取到的ID

# 添加多个解析记录
CF_DNS_ID_WWW=用上面方法获取
DNS_RECORD_WWW=www.xxx.com

DNS_RECORD=域名
RECORD_TYPE=A(IPv4 为 A;IPv6 为 AAAA)

ROUTER_NETWORK_DEVICE=ppp0(你的设备拨号的网卡,openwrt一般是pppoe,可使用ifconfig命令查看)

# 获取当前 DNS 记录
resolving_ip=$(curl -k -X GET "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/dns_records/${CF_DNS_ID}" -H "X-Auth-Email:${EMAIL}" -H "X-Auth-Key:${CF_API_KEY}" -H "Content-Type: application/json" | awk -F '"' '{print $18}')
resolving_ip=$(curl -k -X GET "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/dns_records/${CF_DNS_ID_WWW}" -H "X-Auth-Email:${EMAIL}" -H "X-Auth-Key:${CF_API_KEY}" -H "Content-Type: application/json" | awk -F '"' '{print $18}')

# 获取本机 ipv4 地址
current_ip=$(ip -o -4 addr list $ROUTER_NETWORK_DEVICE | awk '{print $4}' | cut -d/ -f1 | head -n 1)

# 获取本机 ipv6 地址
#current_ip=$(ip -o -6 addr list $ROUTER_NETWORK_DEVICE | awk '{print $4}' | cut -d/ -f1 | head -n 1)

echo "当前解析 IP: $resolving_ip"
echo "当前本机 IP: $current_ip"

# 没有变化
if [ $resolving_ip = $current_ip ];
    then
    echo "IP 未变化"

# 修改 DNS 记录
else
    echo "更新解析记录"
    curl -k -X PUT "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/dns_records/${CF_DNS_ID}" -H "X-Auth-Email:${EMAIL}" -H "X-Auth-Key:${CF_API_KEY}" -H "Content-Type: application/json" --data '{"type":"'$RECORD_TYPE'","name":"'$DNS_RECORD'","content":"'$current_ip'"}'
    curl -k -X PUT "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/dns_records/${CF_DNS_ID_WWW}" -H "X-Auth-Email:${EMAIL}" -H "X-Auth-Key:${CF_API_KEY}" -H "Content-Type: application/json" --data '{"type":"'$RECORD_TYPE'","name":"'$DNS_RECORD_WWW'","content":"'$current_ip'"}'
fi

echo " "

使用 crontab 定时更新解析记录:0 * * * * /home/cloudflare_ddns.sh >> /home/ddns.log

每小时检查 IPv6 地址是否变化,然后更新解析记录,并输出日志到文件。

Last modification:June 21st, 2020 at 11:21 am
如果觉得我的文章对你有用,请随意赞赏