千家信息网

CloudFlare API:批量添加域名并添加解析记录

发表于:2025-01-20 作者:千家信息网编辑
千家信息网最后更新 2025年01月20日,小生博客:http://xsboke.blog.51cto.com -------谢谢您的参考,如有疑问,欢迎交流这里先说一下,CloudFlare是一家
千家信息网最后更新 2025年01月20日CloudFlare API:批量添加域名并添加解析记录

小生博客:http://xsboke.blog.51cto.com

                        -------谢谢您的参考,如有疑问,欢迎交流

这里先说一下,CloudFlare是一家DNS供应商(我是这么理解的),他有提供很多服务(HTTPS/CDN等等),具体的大家可以自己去官网看一下:www.cloudflare.com

CloudFlare建议使用linux的curl命令使用开发的API

因shell不能很好的处理CloudFlare返回的json数据,所以在使用shell的基础上,增加了python脚本

本文件一共有四个脚本文件配合使用:

  1. domians.txt :用来存放需要添加的域名
  2. env.env :存放各种变量
  3. filter_zone_id.py :用于将CloudFlare返回的数据过滤(过滤出域名及其区域ID)
  4. filter_dns_id.py :用于将CloudFlare返回的数据过滤(过滤出解析记录及其区域ID)
  5. main.sh :存放linux命令,执行时也是执行这一个脚本即可

一、 domain.txt就不用介绍了,就是把顶级域名写到里面,一行一个
二、 env.env

  #!/bin/bash#通用变量#当前目录PWD=$(pwd)PYTHON=$(which python)ECHO=$(which echo)#这里DNS指的是解析记录#账号CF_API_EMAIL=CloudFlare的登录账号#秘钥CF_API_KEY=在用户信息里面查看"Global KEY"#组织名organization_name="组织名"#组织IDorganization_id="组织ID"#设置CNAME 和 IPCONTENT_CNAME=域名需要解析的别名"CNAME"CONTENT_IP=域名需要解析的别名IP#get_zone_id.cf     -- 存放新增域名时Cloudflare返回的JSON 数据#get_dns_id.cf      -- 存放获取DNS_ID时Cloudflare返回的JSON 数据#filter_zone_id.py  -- 用于从 "get_zone_id.cf" 中过滤出域名及其相对应的区域ID并写入文件 "zone_id.cf"#filter_dns_id.py   -- 用于从 "get_dns_id.cf" 中过滤出DNS_ID及其DNS_NAME并写入文件 "dns_id.cf"

二、main.sh

#!/bin/bashsource ./env.env#新增域名for domain in $(cat $PWD/domains.txt)do    curl -X POST -H "X-Auth-Key: ${CF_API_KEY}" \    -H "X-Auth-Email: ${CF_API_EMAIL}" \    -H "Content-Type: application/json" "https://api.cloudflare.com/client/v4/zones" \     --data '{"name":"'"${domain}"'","jump_start":true,"organization":{"name":"'"${organization_name}"'","id":"'"${organization_id}"'"}}' >> $PWD/get_zone_id.cf    ${ECHO} -e "\n" >> $PWD/get_zone_id.cfdone#执行python脚本,过滤出域名的区域ID$PYTHON $PWD/filter_zone_id.py#获取DNS ID列表while read linedo    ZONE_NAME=$(${ECHO} "$line" | awk '{print $1}')    ZONE_ID=$(${ECHO} "$line" | awk '{print $2}')    curl -X GET "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records" \         -H "X-Auth-Email: ${CF_API_EMAIL}" -H "X-Auth-Key: ${CF_API_KEY}" \         -H "Content-Type: application/json" >> $PWD/get_dns_id.cf    ${ECHO} -e "\n" >> $PWD/get_dns_id.cfdone < $PWD/zone_id.cf#执行python脚本,过滤出DNS_ID$PYTHON $PWD/filter_dns_id.py#删除DNS记录#删除DNS记录还需要指定区域ID,每个域名的区域DI不同,所以进行一个判断,判断DNS_NAME是否模糊匹配之前取到的ZONE_NAME#如果匹配则使用这个ZONE_IDwhile read zonedo    ZONE_NAME=$(${ECHO} "$zone" | awk '{print $1}')    ZONE_ID=$(${ECHO} "$zone" | awk '{print $2}')    while read dns    do        DNS_NAME=$(${ECHO} "$dns" | awk '{ print $1 }')        DNS_ID=$(${ECHO} "$dns" | awk '{ print $2 }')        if [[ "*$DNS_NAME" =~ "$ZONE_NAME" ]]        then            curl -X DELETE "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records/${DNS_ID}" \                 -H "X-Auth-Email:${CF_API_EMAIL}" \                 -H "X-Auth-Key:${CF_API_KEY}" \                 -H "Content-Type:application/json"        fi    done < $PWD/dns_id.cfdone < $PWD/zone_id.cf#增加DNS记录#TTL=1 为自动#proxied=true 使用CF的CDN,等于false是不使用#data传入变量格式: "'"$EVN"'"#设置变量while read linedo    ZONE_NAME=$(${ECHO} "$line" | awk '{print $1}')    ZONE_ID=$(${ECHO} "$line" | awk '{print $2}')     curl -X POST "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records" \         -H "X-Auth-Email:${CF_API_EMAIL}" \         -H "X-Auth-Key:${CF_API_KEY}" \         -H "Content-Type:application/json" \         --data '{"type":"A","name":"@","content":"'"${CONTENT_IP}"'","ttl":1,"priority":10,"proxied":true}'    curl -X POST "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records" \         -H "X-Auth-Email:${CF_API_EMAIL}" \         -H "X-Auth-Key:${CF_API_KEY}" \         -H "Content-Type:application/json" \         --data '{"type":"CNAME","name":"www","content":"'"${CONTENT_CNAME}"'","ttl":1,"priority":10,"proxied":false}'    curl -X POST "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records" \         -H "X-Auth-Email:${CF_API_EMAIL}" \         -H "X-Auth-Key:${CF_API_KEY}" \         -H "Content-Type:application/json" \         --data '{"type":"CNAME","name":"m","content":"'"${CONTENT_CNAME}"'","ttl":1,"priority":10,"proxied":false}'done < $PWD/zone_id.cf

三、filter_zone_id.py

#!/usr/bin/env python#*- coding:utf-8 -*#打开文件获取添加域名成功后返回的数据,然后获取到域名的区域ID#通过区域ID获取DNS列表import jsonimport osimport traceback#traceback 完整输出报错信息#str(e) 只给出异常信息,不包括异常信息的类型,如1/0的异常信息#repr(e) 给出较全的异常信息,包括异常信息的类型,如1/0的异常信息PWD = os.getcwd()PWD_GET = PWD+'/get_zone_id.cf'PWD_ZONE = PWD+'/zone_id.cf'ERROR_FILE = PWD+'/zone_error.log'#读取添加域名时返回的字符串,并且循环写入字典,以便于过滤出域名的区域IDwith open (PWD_GET,'r') as file:    i = 0    j = 0    dict = {}    list = []    for line in file:        if line.strip  == " " or line == "\n" or line == " \n":            continue        try:            dict[i]=json.loads(line)            i+=1        except Exception as e:            j+=1            with open (ERROR_FILE,'a+') as file:                title = "----------\t\t第%d条报错信息\t\t---------"%(j) + "\n"                #info = "报错信息:" + traceback.format_exc() + "\n"                info = "报错信息:" + repr(e) + "\n"                mation = "报错行:" + line + "\n"                file.writelines(title)                file.writelines(info)                file.writelines(mation)            continue#获取所有的key,然后进行循环遍历,获取每个域名的区域IDkeys_list = dict.keys()for key in keys_list:    ID=dict[key]['result']['id']    NAME=dict[key]['result']['name']    with open (PWD_ZONE,'a+') as file:        line = NAME + " " + ID + "\n"        file.writelines(line)

四、filter_dns_id.py

#!/usr/bin/env python#*- coding:utf-8 -*#打开文件读取cloudflare返回的DNS IDimport jsonimport osPWD = os.getcwd()PWD_GET = PWD+'/get_dns_id.cf'PWD_DNS = PWD+'/dns_id.cf'#读取获取DNS ID时返回的字符串,并且循环写入字典,以便于过滤出DNS IDwith open (PWD_GET,'r') as file:    i = 0    dict = {}    for line in file:        if line.strip  == " " or line == "\n" or line == " \n":            continue        dict[i]=json.loads(line)        i+=1key_list = dict.keys()for key in key_list:    list =  dict[key]['result']    #一个域名可能有多个DNS记录,cloudflare返回的是一个列表,列表中是一个一个的字典,    #一个key-values代表一个DNS记录,所以这里需要遍历列表中的字典    #通过取列表的索引值,循环每一个位置的字典    for i in list:        with open (PWD_DNS,'a+') as file:            line = i['name'] + " " + i['id'] + "\n"            file.writelines(line)
0