前言

由于自己用了多WAN,一直没找到合适的ddns插件,所以用cloudflare api[1]实现了一个ddns功能

代码

#!/bin/sh
[ $ACTION = "ifup" -a $INTERFACE = "WAN" ]
ip=`ubus call network.interface.WAN status | grep \"address\" | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'`
curl -X PUT "https://api.cloudflare.com/client/v4/zones/xxxxxxxxx/dns_records/xxxxxxxx" -H "Authorization: Bearer XXXXXXXXXXX"  -H "Content-Type: application/json" --data '{"type":"A","name":"domian.test","content":"'$ip'","ttl":120,"priority":10,"proxied":false}' > /dev/null                                               

将以上文件保存为30-cloudflare 放置在/etc/hotplug.d/iface目录下

非拨号设备

如果不是在路由器上拨号,可定时获取公网IP

#!/bin/sh
ip=`curl -s http://ns1.dnspod.net:6666 | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'`
wanip=`cat wanip.txt`
if [ "$wanip" != "$ip" ];then
    res=`curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/xxxxxxxxx/dns_records/xxxxxxxxx" \
    -H "Authorization: Bearer xxxxxxxxx" \
    -H "Content-Type:application/json" \
    --data '{"type":"A","name":"domian.test","content":"'$ip'","ttl":120,"priority":10,"proxied":false}'| \
    python3 -c "import sys, json; print(json.load(sys.stdin)['success'])"`
                                      
    if [ "$res" = "True" ];then
        echo "$ip" > wanip.txt
    fi

fi

注:xxx替换为自己的设置,token长期有效[2],可以固定写死.


  1. Cloudflare Update DNS Record Wiki ↩︎

  2. Cloudflare API Tokens page ↩︎