Cloudflare API更新后,仅支持通过API Tokens进行鉴权,原有email – token鉴权方式失效。
预解析域名
在Cloudflare DNS绑定域名后,新建需要进行DDNS的子域名,根据需要创建A或AAAA记录(对应IPv4和IPv6),随意填写一个记录值即可。
获取API tokens等参数
获取zone DNS token
在Appearance – API Tokens中,创建一个Edit zone DNS,使用预置模板即可,选择对应的作用Zone,最后一步可获得到token,请注意保存,后续无法再显示,遗忘只能重新创建。
此步骤获得的对应下文`API_TOKEN`参数。
注意,API Keys中的Global API Keys无需获取。
获取zone id和record id
在域名Overview下方,可找到对应的Zone id
打开终端,输入:
ZONE_ID=" Your Zone ID"
API_TOKEN="Your API Token"
DDNS = "Your domain to DDNS"
curl -X GET "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records?name=$DDNS" \
-H "Authorization: Bearer $API_TOKEN" \
-H "Content-Type: application/json"
正确请求结果如:
{"result":[{"id":"abcdefg","zone_id":"12345678","zone_name":"a.com","name":"www.a.com","type":"A","content":"127.0.0.1","proxiable":true,"proxied":false,"ttl":1,"locked":false],"success":true,"errors":[],"messages":[],"result_info":{"page":1,"per_page":100,"count":1,"total_count":1,"total_pages":1}}
记录结果中的id,对应下文`RECORD_ID`参数。
利用bash脚本便捷执行
vim ddns.sh
以IPv6为例:
#!/bin/sh
#!/bin/bash
# 参数配置
NEW_IP=`curl -s http://ipv6.icanhazip.com` # DDNS 服务,可自选,http://6.ipw.cn/
CURRENT_IP=`cat $(dirname "$0")/current_ip.txt`
CURRENT_TIME=$(date +"%F %T")
DDNS=""
ZONE_ID=""
API_TOKEN=""
RECORD_ID=""
if [ "$NEW_IP" = "$CURRENT_IP" ]
then
echo "[$CURRENT_TIME] No Change in IP Adddress" >> $(dirname "$0")/crontab_log.txt
echo "Current IP[$CURRENT_IP] has no changes."
exit 0
else
update_dns=$(curl -k -X PUT "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records/$RECORD_ID" \
-H "Authorization: Bearer $API_TOKEN" \
-H "Content-Type: application/json" \
--data '{"type":"AAAA","name":"'"$DDNS"'","content":"'"$NEW_IP"'","ttl":1,"proxied":true}') > /dev/null
# 此处type可自行设置A/AAAA等,proxied变量对应是否使用Cloudflare的代理(小黄云)
fi
if [ "$update_dns" != "${update_dns%\"success\":true*}" ]; then
echo "DNS Update to '$NEW_IP' Successfully."
echo $NEW_IP > $(dirname "$0")/current_ip.txt
echo "[$CURRENT_TIME] IP changed to $NEW_IP" >> $(dirname "$0")/crontab_log.txt
else
echo "Something wrong. Please check the message:"
echo $update_dns
fi
执行Shell脚本并设置定时任务
利用crontab可实现定时循环执行。
# 每30分钟执行一次
*/30 * * * * sh /root/ddns.sh