返回

完整指南:使用API和Shell脚本更新Cloudflare DNS记录

日志

概述

本文介绍如何使用Shell脚本和Cloudflare的API自动更新DNS记录。我们将使用一个简单的Shell脚本来获取公共IP地址并更新指定域名的DNS记录。

前提条件

在开始之前,确保你具备以下条件:

  • 你已经有一个Cloudflare账户,并且拥有对应域名的管理权限。
  • 你已经安装了Shell环境,并且可以执行Shell脚本。
  • 你已经获得了Cloudflare的API密钥(Auth Email和Auth Key)。

步骤

  1. 下载并配置Shell脚本
    • 首先,将Shell脚本下载到你的本地计算机,并将其保存为update_dns.sh
    • 打开update_dns.sh文件,找到以下变量并进行相应的修改:
      • auth_email:替换为你的Cloudflare账户的Auth Email。
      • auth_key:替换为你的Cloudflare账户的Auth Key。
      • zone_name:替换为你要更新DNS记录的域名。
      • record_name:替换为你要更新的DNS记录名称的前缀。
      • record_count:替换为你要更新的DNS记录的数量。
      • record_type:替换为你要更新的DNS记录的类型。
    • 保存并关闭文件。
  2. 执行Shell脚本
    • 打开终端或命令行界面,导航到存储Shell脚本的目录。
    • 运行以下命令以赋予脚本执行权限:
      chmod +x update_dns.sh
      
    • 执行Shell脚本:
      ./update_dns.sh
      
  3. 检查更新结果
    • 执行完脚本后,它会获取公共IP地址并尝试更新指定域名的DNS记录。
    • 在脚本运行完成后,你将看到每个更新的DNS记录的结果。

下面是完整的脚本

#!/bin/bash

## 绝对路径
cd "/CloudflareST_darwin_amd64"
auth_email="*" ## cloduflare邮箱
auth_key="*" ## cloduflare Key
zone_name="*" ## 空间名字,也就是主域名,不带www, 例如:example.com
record_name="*" ## 修改域名的前缀
record_count=11
record_type="A"

PUBLIC_IP=$(curl --silent http://4.ipw.cn)
echo "请确认该机器没有通过代理,你的IP地址是:$PUBLIC_IP"


# ./CloudflareST -p 0

zone_identifier=$(curl -X GET "https://api.cloudflare.com/client/v4/zones?name=$zone_name" -H "X-Auth-Email: $auth_email" -H "X-Auth-Key: $auth_key" -H "Content-Type: application/json" | jq -r '.result[0].id')
echo "zone_identifier: $zone_identifier"



n=0
while IFS=',' read -r i _ _ _ _ _; do
    echo "IP 地址: $i"
	if [ $n -ne 0 ]; then
		record=$(curl -X GET "https://api.cloudflare.com/client/v4/zones/${zone_identifier}/dns_records?name=$record_name$record_count.$zone_name" -H "Content-Type: application/json" -H "X-Auth-Email: $auth_email" -H "X-Auth-Key: $auth_key" | jq -r '.result[0].id')
        echo "record_id: $record"
        echo "更新DNS记录"
        result=$(curl -X PUT "https://api.cloudflare.com/client/v4/zones/${zone_identifier}/dns_records/${record}" -H "Content-Type: application/json" -H "X-Auth-Email: $auth_email" -H "X-Auth-Key: $auth_key" --data "{\"type\":\"$record_type\",\"name\":\"$record_name$record_count.$zone_name\",\"content\":\"$i\",\"ttl\":60,\"proxied\":false}" | jq -r '.success')
		echo "$record_name$record_count.$zone_name 域名地址更新为: $i"
		echo "更新结果: $result"
	fi
	n=$((n+1))
	record_count=$((record_count-1))
	if [ $record_count -le 0 ]; then
		break
	fi
done < result.csv

总结

通过使用Shell脚本和Cloudflare的API,你可以轻松自动化更新DNS记录的过程。这对于需要频繁更新记录的情况非常有用,例如服务器迁移、IP地址更改等。