以下是一个同时支持IPv4和IPv6的Cloudflare DDNS更新脚本:

#!/bin/sh

# Cloudflare API配置
API_TOKEN="xxx"
ZONE_ID="xxx"
# IPv4记录配置
RECORD_ID_V4="xxx"
RECORD_NAME_V4="xxx"
# IPv6记录配置(如果没有可以留空)
RECORD_ID_V6="xxx"
RECORD_NAME_V6="xxx"

# 获取当前IPv4地址
CURRENT_IPV4=$(curl -s http://ipv4.icanhazip.com)
echo "当前IPv4地址: $CURRENT_IPV4"

# 获取当前IPv6地址(如果有)
CURRENT_IPV6=$(curl -s http://ipv6.icanhazip.com || echo "")
if [ -n "$CURRENT_IPV6" ]; then
    echo "当前IPv6地址: $CURRENT_IPV6"
else
    echo "未检测到IPv6地址"
fi

# 更新DNS记录函数
update_dns_record() {
    local record_id=$1
    local record_name=$2
    local current_ip=$3
    local record_type=$4
    
    if [ -z "$record_id" ] || [ -z "$current_ip" ]; then
        echo "跳过${record_type}记录更新(未配置记录ID或未检测到IP地址)"
        return
    fi

    # 获取DNS记录当前IP
    local dns_record_response=$(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")

    local dns_record_ip=$(echo "$dns_record_response" | sed -n 's/.*"content":"\([^"]*\)".*/\1/p')
    echo "DNS记录${record_type}当前IP: $dns_record_ip"

    # 检查IP是否需要更新
    if [ "$current_ip" == "$dns_record_ip" ]; then
        echo "${record_type}记录IP地址无需更新"
    else
        echo "${record_type}记录IP地址需要更新"

        # 更新DNS记录
        local response=$(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\":\"${record_type}\",\"name\":\"${record_name}\",\"content\":\"${current_ip}\",\"ttl\":120,\"proxied\":false}")

        # 检查更新结果
        if echo "$response" | grep -q "\"success\":true"; then
            echo "${record_type}记录更新成功,新IP: ${current_ip}"
        else
            echo "${record_type}记录更新失败,错误信息: $response"
        fi
    fi
}

# 更新IPv4记录
update_dns_record "$RECORD_ID_V4" "$RECORD_NAME_V4" "$CURRENT_IPV4" "A"

# 更新IPv6记录(如果配置了)
if [ -n "$RECORD_ID_V6" ] && [ -n "$CURRENT_IPV6" ]; then
    update_dns_record "$RECORD_ID_V6" "$RECORD_NAME_V6" "$CURRENT_IPV6" "AAAA"
fi

使用说明:

  1. 需要配置以下参数:

    • API_TOKEN: Cloudflare API令牌
    • ZONE_ID: 区域ID
    • IPv4记录相关参数:

      • RECORD_ID_V4: IPv4记录的ID
      • RECORD_NAME_V4: IPv4记录的名称(如subdomain.example.com)
    • IPv6记录相关参数(可选):

      • RECORD_ID_V6: IPv6记录的ID(如果没有可以留空)
      • RECORD_NAME_V6: IPv6记录的名称
  2. 脚本功能:

    • 自动检测当前IPv4和IPv6地址
    • 分别检查Cloudflare DNS记录是否需要更新
    • 支持IPv4(A记录)和IPv6(AAAA记录)更新
    • 详细的日志输出
  3. 注意事项:

    • 如果没有IPv6地址或不需要IPv6支持,可以不配置IPv6相关参数
    • 确保API令牌有足够的权限(需要Zone.DNS编辑权限)
    • 建议设置cron定时任务自动运行此脚本
  4. 获取记录ID的方法:
    可以通过API获取:curl -X GET "https://api.cloudflare.com/client/v4/zones/YOUR_ZONE_ID/dns_records" -H "Authorization: Bearer YOUR_API_TOKEN"

标签: Cloudflare

评论已关闭