cloudflare dns管理脚本

Introduction

一个简单、方便的Cloudflare DNS管理脚本
基于 Cloudflare API 实现对DNS记录的增删改查,配合crontab也可以当DDNS用
对DNS记录的修改保存至文件,默认日志文件路径:/var/log/cloudflare_dns.log

Requirement

修改脚本中以下4个变量
cf_id = “cloudflare账号(邮箱)”
cf_key = “global api key”
zone_id = “域名的zone_id”
zone_name = ‘根域名名称’

Example

cloudflare requirement

USAGE

Parameters

-n, --name dns记录名
-c, --content dns记录内容
-t, --type dns记录类型 (default: A)
-d, --delete-n 同时使用,删除 -n 指定的dns记录

Example

  • 列出所有DNS记录
    python3 cloudflare_dns.py
    output:

    1
    2
    3
    od.kwin.win A 1.1.1.1
    blog.kwin.win A 2.2.2.2
    ...
  • 列出指定记录
    python3 cloudflare_dns.py -n od
    output:

    1
    od.kwin.win A 1.1.1.1
  • 创建或更新记录(无则创建有则更新)
    python3 cloudflare_dns.py -n test -c 1.1.1.1
    output:

    1
    2
    New record:
    test.kwin.win A 1.1.1.1

    python3 cloudflare_dns.py -n test -c 1.0.0.1
    output:

    1
    2
    3
    test.kwin.win A 1.1.1.1
    Changed to
    test.kwin.win A 1.0.0.1
  • 删除指定记录
    python3 cloudflare_dns.py -n test -d
    output:

    1
    2
    test.kwin.win A 1.0.0.1
    Deleted

    Log

    log

Source Code

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
#!/usr/bin/env python3
# coding = utf-8
import httpx
import argparse
import logging

cf_id = "cloudflare account id(mail)"
cf_key = "global api key"
zone_id = "domain zone id"
zone_name = 'domain zone name'


def list_record(name=''):
global record
params = {'name': f'{name}.{zone_name}'} if name else {'per_page': 100}
resp = httpx.get(base_url, headers=headers, params=params)
for msg in resp.json()['result']:
print(eval(req_msg))
if name:
record = eval(req_msg)
return msg['id']


def new_record(name, content, record_id, record_type='A'):
data = {'type': record_type, 'name': name, 'content': content}
if record_id:
msg = httpx.put(f'{base_url}/{record_id}', headers=headers,
json=data).json()['result']
print('Changed to')
logging.info(f'update: {eval(req_msg)}')
else:
msg = httpx.post(base_url, headers=headers, json=data).json()['result']
print('New record:')
logging.info(f'create: {eval(req_msg)}')
print(eval(req_msg))


def delete_record(record_id):
if record_id:
msg = httpx.delete(f'{base_url}/{record_id}', headers=headers)
if msg.json()['success']:
print('Deleted')
logging.info(f'delete: {record}')
else:
print(f'Record not found: {name}')


def get_parser():
parser = argparse.ArgumentParser(
description="Manipulate DNS records hosted on cloudflare")
parser.add_argument('-n', '--name')
parser.add_argument('-c', '--content')
parser.add_argument('-t', '--type', default='A')
parser.add_argument('-d', '--delete', action="store_true")
return parser


if __name__ == '__main__':
logging.basicConfig(filename='/var/log/cloudflare_dns.log',
format='%(levelname)s %(asctime)s %(message)s',
level=logging.INFO)
req_msg = """f'{msg["name"]} {msg["type"]} {msg["content"]}'"""
base_url = f'https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records'
headers = {
'X-Auth-Email': cf_id,
'X-Auth-Key': cf_key,
'Content-Type': 'application/json'
}
args = get_parser().parse_args()
name = args.name
content = args.content
record_type = args.type
delete = args.delete
if name and delete:
delete_record(list_record(name))
elif name and content:
new_record(name, content, list_record(name), record_type)
else:
list_record(name)

Referennce

Cloudflare API v4 Documentation
Python: Argparse Tutorial
Python: Logging HOWTO

Author: kwin
Link: https://blog.kwin.win/2021/02/25/cloudflare-dns-manipulate/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.