那我给大家来段代码,非我原创,针对 cloudfare ddns 。网上我搜的很多结果都过时了,cloudfare ddns 官方 wiki 也没写的明白。
#!/bin/bash
API_TOKEN="content of API_TOKEN"
ZONE_ID="content of ZONE_ID"
RECORD_ID="content of RECORD_ID"
RECORD_NAME=" content of RECORD_NAME"
# Get current public IP ,如果不用外部服务,你可以自己获取网卡 IP 替换
# CURRENT_IP=$(ip addr show ppp0 | grep 'inet ' | awk '{ print $2 }' | cut -d/ -f1)
CURRENT_IP=$(curl -s
https://api.ipify.org)
# Get the current DNS record IP from Cloudflare ,提交和更新请用 Authorization: Bearer 方式,其他方式不知道是我方法不对,全都报错
OLD_IP=$(curl -s -X GET "
https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records/$RECORD_ID" \
-H "Authorization: Bearer $API_TOKEN" \
-H "Content-Type: application/json" \
| jq -r '.result.content')
# Check if IP has changed
if [ "$CURRENT_IP" != "$OLD_IP" ]; then
# Update DNS record with new IP
RESULT=$(curl -s -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":"A","name":"'"$RECORD_NAME"'","content":"'"$CURRENT_IP"'","ttl":1,"proxied":false}')
# Check if update was successful
if [ "$(echo "$RESULT" | jq -r '.success')" = "true" ]; then
echo "DNS record updated successfully."
now points to $CURRENT_IP"
else
echo "Error updating DNS record:"
echo "$RESULT"
fi
fi
#创建服务
/etc/systemd/system/cloudflare-ddns.service
[Unit]
Description=Cloudflare Dynamic DNS Update
After=network-online.target
Wants=cloudflare-ddns.timer
[Service]
User=root
Type=oneshot
ExecStart=/usr/local/bin/
cloudflare_ddns.shRestart=on-failure
[Install]
WantedBy=multi-user.target
保活
/etc/systemd/system/cloudflare-ddns.timer
[Unit]
Description=Run cloudflare-ddns every 5 minutes
[Timer]
OnBootSec=1m
OnUnitActiveSec=5m
[Install]
WantedBy=timers.target