使用 Cloudflare API 实现动态 DNS

Carinnan

在 ChatGPT 的帮助下,我写了以下脚本:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/usr/bin/env bash

# 设置 Cloudflare API 密钥、电子邮件地址和区域 ID
api_key=""
email=""
zone_identifier=""
record_identifier=""

# 设置要更新的 DNS 记录
record_name="aaa.example.com"
proxied=false
record_type="AAAA"
comment="IPv6 update"

# 以 IPv6 为例
ipv6_address=""

curl --request PUT \
    --url "https://api.cloudflare.com/client/v4/zones/${zone_identifier}/dns_records/${record_identifier}" \
    --header 'Content-Type: application/json' \
    --header "X-Auth-Email: ${email}" \
    --header "X-Auth-Key: ${api_key}" \
    --data "{
    \"content\": \"${ipv6_address}\",
    \"name\": \"${record_name}\",
    \"proxied\": ${proxied},
    \"type\": \"${record_type}\",
    \"comment\": \"${comment}\"
}"

其中的空项大都可以在登录 Cloudflare 后查询到。需要注意的是,record_identifier 也需要通过 API 获取:

1
2
3
4
curl -X GET "https://api.cloudflare.com/client/v4/zones/$zone_ID/dns_records" \
    -H "X-Auth-Email: your_email" \
    -H "X-Auth-Key: your_api_key" \
    -H "Content-Type: application/json"

在上述命令中替换自己的 zone_ID、电子邮件和 X-Auth-Key,即可获得包含 record_identifier 的 JSON 响应。

至于我为什么以 IPv6 为例呢?看到 DDNS,看到 IPv6……自然是因为可以借此用家里的云设备提供公网服务啦。