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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
|
import requests import json
class CloudflareManager: def __init__(self, email, api_key): self.email = email self.api_key = api_key self.base_url = 'https://api.cloudflare.com/client/v4' self.headers = { 'X-Auth-Email': email, 'X-Auth-Key': api_key, 'Content-Type': 'application/json' } def get_zones(self): """获取所有zone""" response = requests.get( f'{self.base_url}/zones', headers=self.headers ) return response.json() def get_zone_id(self, domain): """获取zone ID""" zones = self.get_zones() for zone in zones['result']: if zone['name'] == domain: return zone['id'] return None def get_dns_records(self, zone_id, record_type=None, name=None): """获取DNS记录列表""" url = f'{self.base_url}/zones/{zone_id}/dns_records' params = {} if record_type: params['type'] = record_type if name: params['name'] = name response = requests.get(url, headers=self.headers, params=params) return response.json() def create_dns_record(self, zone_id, record_type, name, content, ttl=1, proxied=False): """创建DNS记录""" url = f'{self.base_url}/zones/{zone_id}/dns_records' data = { 'type': record_type, 'name': name, 'content': content, 'ttl': ttl, 'proxied': proxied } response = requests.post(url, headers=self.headers, json=data) return response.json() def update_dns_record(self, zone_id, record_id, record_type, name, content, ttl=1, proxied=False): """更新DNS记录""" url = f'{self.base_url}/zones/{zone_id}/dns_records/{record_id}' data = { 'type': record_type, 'name': name, 'content': content, 'ttl': ttl, 'proxied': proxied } response = requests.put(url, headers=self.headers, json=data) return response.json() def delete_dns_record(self, zone_id, record_id): """删除DNS记录""" url = f'{self.base_url}/zones/{zone_id}/dns_records/{record_id}' response = requests.delete(url, headers=self.headers) return response.json()
if __name__ == '__main__': cf_manager = CloudflareManager( email='your_email@example.com', api_key='your_api_key' ) zone_id = cf_manager.get_zone_id('example.com') result = cf_manager.create_dns_record( zone_id=zone_id, record_type='A', name='www', content='192.168.1.100', ttl=1, proxied=True ) print(f"添加记录: {result}") records = cf_manager.get_dns_records( zone_id=zone_id, record_type='A', name='www.example.com' ) print(f"DNS记录: {records}")
|