獲取舊域名記錄並 批量添加到新域名 Cloudflare DNS解析

機場運營·Python · 01-21 · 251 人浏览
獲取舊域名記錄並 批量添加到新域名 Cloudflare DNS解析

實現功能:獲取托管在Cloudflare中的舊域名DNS解析記錄,並添加到新域名記錄。
例如舊域名為 a.com,子域名為 b.a.comc.a.com,解析的IP地址分別為1.1.1.12.2.2.2
我要用新的域名b.com 解析a.com域名相同的dns記錄,也就是b.b.comc.b.com,解析的IP地址分別為1.1.1.12.2.2.2,一個個手動添加太麻煩了,於是用以下脚本,就可以一鍵添加記錄。獲取a.com所有的dns解析記錄,然後批量添加到b.com,IP地址也同步。

注意:使用脚本請配置好你的Cloudflare Api 和 Email 其它一般默認就好了,'proxied': False 代表不開啓雲朵CDN,默認開啓雲朵CDN

import re
import requests

api_key = 'Your_Key'
email = 'Your_Email'

def get_zone_id(domain):
   headers = {
      'X-Auth-Email': email,
      'X-Auth-Key': api_key,
      'Content-Type': 'application/json'
   }
   url = f'https://api.cloudflare.com/client/v4/zones?name={domain}'
   response = requests.get(url, headers=headers)
   return response.json()['result'][0]['id']

def get_config(domain):
   headers = {
      'X-Auth-Email': email,
      'X-Auth-Key': api_key,
      'Content-Type': 'application/json'
   }
   zone_id = get_zone_id(domain)
   url = f'https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records'
   response = requests.get(url, headers=headers)
   dns_records = []
   for record in response.json()['result']:
      dns_records.append({
            'Type': record['type'],
            'Name': record['name'],
            'Content': record['content']
      })
   return dns_records

def DNS_ADD(domain, record_type, prefix, record_content):
   headers = {
      'X-Auth-Email': email,
      'X-Auth-Key': api_key,
      'Content-Type': 'application/json'
   }
   zone_id = get_zone_id(domain)
   url = f'https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records'
   config_domain = prefix + '.' + domain
   data = {
      'type': record_type,
      'name': config_domain,
      'content': record_content,
      'ttl': 120,
      'proxied': True
   }
   response = requests.post(url, headers=headers, json=data)
   if response.status_code == 200:
      print('Successfully:' + config_domain + ' ' + record_type + ' ' + record_content)
   else:
      print('Failed:' + config_domain + ' ' + record_type + ' ' + record_content)
old_domain = input('請輸入要獲取解析記錄的域名:')
new_domain = input('請輸入要添加解析記錄的域名')
config_json = get_config(old_domain)

for config in config_json:
   return_domain = config['Name']
   record_type = config['Type']
   record_content = config['Content']
   try:
      prefix = re.findall('(.*)\.' + old_domain, return_domain)[0]
      DNS_ADD(new_domain, record_type, prefix, record_content)
   except Exception as e:
      print(f"Error occurred: {e}")
Script Python Cloudflare
本站立足于美利堅合衆國,請讀者自覺遵守當地法律!如有違規,本站不承擔任何法律責任! This site is based in the United States of America, readers are requested to abide by local laws! If there are any violations, this site does not bear any legal responsibility! Theme Jasmine by Kent Liao