代码
#!/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
CURRENT_IP=$(curl -s https://api.ipify.org)
# Get the current DNS record IP from Cloudflare
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.sh
Restart=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