首先找到 RECORD_ID
登陆 https://dash.cloudflare.com 找到域名的 ZONE_ID 和 API_TOKEN
输入:
curl -X GET "https://api.cloudflare.com/client/v4/zones/$ZONEID/dns_records" \
-H "Authorization: Bearer $API_TOKEN" \
-H "Content-Type: application/json"
创建脚本
vi /usr/local/bin/cloudflare_ddns.sh
#!/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"
# Telegram bot credentials
TELEGRAM_BOT_TOKEN=" content of TELEGRAM_BOT_TOKEN"
TELEGRAM_CHAT_ID="content of TELEGRAM_CHAT_ID"
# Function to send Telegram message
send_telegram_message() {
message="$1"
curl -s -X POST "https://api.telegram.org/$TELEGRAM_BOT_TOKEN/sendMessage" \
-d "chat_id=$TELEGRAM_CHAT_ID" \
-d "text=$message" \
-d "parse_mode=HTML"
}
# 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."
send_telegram_message "<b>DNS record updated:</b> $RECORD_NAME now points to $CURRENT_IP"
else
echo "Error updating DNS record:"
echo "$RESULT"
send_telegram_message "<b>Error updating DNS record:</b> $RESULT"
fi
fi
给权限 chmod +x /usr/local/bin/cloudflare_ddns.sh
安装 jq apt install jq
vi /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
vi /etc/systemd/system/cloudflare-ddns.timer
[Unit]
Description=Run cloudflare-ddns every 5 minutes
[Timer]
OnBootSec=1m
OnUnitActiveSec=5m
[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable cloudflare-ddns
sudo systemctl start cloudflare-ddns
sudo systemctl enable cloudflare-ddns.timer
sudo systemctl start cloudflare-ddns.timer
查看日志:
sudo journalctl -u cloudflare-ddns.service --no-pager