#!/bin/sh

EMAIL=
CF_API_KEY=
CF_ZONE_ID=
CF_DNS_ID=

# 添加多个域名解析
CF_DNS_ID_WWW=54fc33a3dc443d38887b9ec0606c5e09
DNS_RECORD_WWW=www.域名

# ipv4
DNS_RECORD=域名
RECORD_TYPE=A    # ipv6 则为 AAAA

ROUTER_NETWORK_DEVICE=你的设备拨号的网卡,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 -e
# 每小时检查 IPv4 地址是否变化,然后更新解析记录,并输出日志到文件。
*/60 * * * * /root/CloudFlareDDNS.sh >> /root/ddns.log

PS:APIKey 和 ZoneID 可在官网登录后的 Overview 页面获得,而 DNSID 获取较为复杂,具体命令如下(需要安装 curl):

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

PS:hanwckf 固件测试 OK

Last modification:March 1st, 2020 at 10:50 am
如果觉得我的文章对你有用,请随意赞赏