本文目录导读:

- 核心思路
- 方案一:使用 Python + 云厂商 SDK(以阿里云为例)
- 方案二:使用 Cloudflare API + Shell (curl + jq)
- 方案三:使用通用 HTTP API 调用(Python + requests)
- 通用最佳实践建议
- 最终建议
批量配置CDN域名通常需要调用云服务商提供的 API(应用程序编程接口),通过脚本(如Shell、Python)结合命令行工具(如阿里云CLI、腾讯云CLI)或直接发送HTTP请求来实现。
由于不同云厂商(阿里云、腾讯云、AWS CloudFront、Cloudflare)的API结构不同,下面我会以阿里云CDN和Cloudflare为例,给出通用的脚本思路和具体代码示例。
核心思路
- 准备数据:一个包含域名、源站、加速区域等信息的CSV或JSON文件。
- 获取凭证:从环境变量或配置文件读取云厂商的 AccessKey 和 SecretKey。
- 编写循环:遍历数据文件,逐条调用 API 创建或更新 CDN 配置。
- 错误处理:记录失败项并重试或跳过。
使用 Python + 云厂商 SDK(以阿里云为例)
这是最灵活、最可控的方式,假设你需要批量添加CDN域名,源站均为 origin.example.com。
前置准备
# 安装阿里云Python SDK pip install alibabacloud_cdn20180510
Python 脚本 batch_add_cdn.py
import json
import csv
import os
from alibabacloud_cdn20180510.client import Client as CdnClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_cdn20180510 import models as cdn_models
def create_client():
# 从环境变量读取密钥(更安全)
config = open_api_models.Config(
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
config.endpoint = 'cdn.aliyuncs.com'
return CdnClient(config)
def add_cdn_domain(client, domain, source_ip, type='ipaddr'):
# 构建添加域名的请求
add_req = cdn_models.AddCdnDomainRequest(
domain_name=domain,
cdn_type='web', # 可选:web, download, video
sources=json.dumps([{
'content': source_ip,
'type': type, # ipaddr / domain / oss
'priority': '20',
'port': 80,
'weight': '10'
}]),
resource_group_id='', # 可选资源组ID
scope='domestic' # domestic / overseas / global
)
try:
resp = client.add_cdn_domain(add_req)
print(f"[OK] {domain} 添加成功,RequestId: {resp.body.request_id}")
return True
except Exception as e:
print(f"[ERROR] {domain} 添加失败: {str(e)}")
return False
def main():
# 假设输入文件 domains.csv 格式:domain,source_ip
csv_file = 'domains.csv'
client = create_client()
with open(csv_file, 'r', encoding='utf-8') as f:
reader = csv.reader(f)
next(reader) # 跳过表头
for row in reader:
domain = row[0].strip()
source = row[1].strip()
if not domain or not source:
continue
add_cdn_domain(client, domain, source)
if __name__ == '__main__':
main()
使用方法:
- 创建
domains.csv:domain,source_ip img1.example.com,1.2.3.4 img2.example.com,1.2.3.5 video.example.com,oss://my-bucket
- 设置环境变量并运行:
export ALIBABA_CLOUD_ACCESS_KEY_ID="your_key_id" export ALIBABA_CLOUD_ACCESS_KEY_SECRET="your_key_secret" python batch_add_cdn.py
使用 Cloudflare API + Shell (curl + jq)
如果使用的是Cloudflare(国外常用CDN),API较为简洁,适合用Shell脚本处理。
Shell 脚本 batch_cloudflare.sh
#!/bin/bash
# 配置
CF_API_TOKEN="your_api_token" # 建议从环境变量读取
ZONE_ID="your_zone_id" # 域名所在的Zone ID
# 输入文件:每行一个子域名
input_file="domains.txt"
# 公共配置(源站)
ORIGIN_IP="123.123.123.123"
TTL=120
PROXY=true # true=开启CDN代理,false=仅DNS
# 读取每一行
while IFS= read -r subdomain; do
# 跳过空行和注释
[[ -z "$subdomain" || "$subdomain" =~ ^# ]] && continue
full_domain="${subdomain}.example.com"
# 构建JSON请求体
json_data=$(cat <<EOF
{
"type": "A",
"name": "$subdomain",
"content": "$ORIGIN_IP",
"ttl": $TTL,
"proxied": $PROXY
}
EOF
)
echo "正在配置: $full_domain"
# 发送API请求创建DNS记录(Cloudflare DNS即CDN)
response=$(curl -s -X POST "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
-d "$json_data")
# 检查结果
success=$(echo "$response" | jq -r '.success')
if [ "$success" = "true" ]; then
echo "[OK] $full_domain 已添加"
else
errors=$(echo "$response" | jq -c '.errors[]')
echo "[ERROR] $full_domain 失败: $errors"
fi
# 避免API限速,每请求休息0.5秒
sleep 0.5
done < "$input_file"
使用方法:
- 创建
domains.txt(每行一个子域名前缀):img static cdn # 可添加注释行 video - 给脚本执行权限并运行:
chmod +x batch_cloudflare.sh CF_API_TOKEN="your_token" ZONE_ID="your_zone" ./batch_cloudflare.sh
使用通用 HTTP API 调用(Python + requests)
适用于任何提供HTTP API的CDN厂商,标准化程度更高。
import requests
import csv
import time
# 假设使用某CDN厂商API
API_BASE = "https://api.examplecdn.com/v1"
API_KEY = "your_api_key"
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
def create_cdn_domain(domain, origin):
url = f"{API_BASE}/domains"
payload = {
"domain": domain,
"origin": origin,
"type": "web",
"region": "global"
}
r = requests.post(url, json=payload, headers=headers)
return r.status_code == 200, r.text
def batch_add_domains(csv_file='domains.csv'):
with open(csv_file, 'r') as f:
reader = csv.DictReader(f)
for row in reader:
domain = row['domain'].strip()
origin = row['origin'].strip()
if not domain or not origin:
continue
success, msg = create_cdn_domain(domain, origin)
status = "[OK]" if success else "[FAIL]"
print(f"{status} {domain} -> {msg}")
time.sleep(1) # 避免API限流
if __name__ == "__main__":
batch_add_domains()
通用最佳实践建议
- 避免硬编码密钥:始终使用环境变量或密钥管理服务(如AWS Secret Manager)。
- 幂等性与重试:添加脚本时,最好先检查域名是否已存在(调用DescribeDomainList等接口),避免重复创建导致报错。
- 日志与进度:将输出重定向到日志文件,方便排查:
python batch_add_cdn.py > cdn_batch.log 2>&1
- API限流:大多数厂商有速率限制(例如每秒10次请求),在循环中适当添加
time.sleep(0.3)。 - 批量更新配置:如果只是更改某个配置(如源站、HTTPS证书),可以先通过
DescribeCdnDomain获取已有列表,再逐条调用ModifyCdnDomain更新。
最终建议
- 如果你同时使用多个云厂商:推荐用 Terraform 或 Pulumi 的CDN Provider,通过声明式配置文件批量管理,效果最佳。
- 如果你只需要一次性批量添加:直接使用云厂商控制台的“批量导入”功能(阿里云、腾讯云都有),无需写脚本。
- 如果你需要定期批量调整:上述Python脚本最易于维护和扩展。
如果你能提供具体的云厂商名称和需要配置的参数(源站类型、HTTPS、缓存规则等),我可以给出更精确的代码示例。