-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cf-dns-update.py
284 lines (211 loc) · 6.85 KB
/
cf-dns-update.py
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# -*- coding: utf-8 -*-
"""
Dynamic DNS record update utility for CloudFlare DNS service.
(c) Dung Nguyen (nhymxu)
"""
import argparse
import json
import urllib.error
import urllib.parse
import urllib.request
from configparser import ConfigParser
from os import path
CF_API_TOKEN = ''
IS_DRYRUN = False
PUBLIC_IP_SERVICE = 'amazonaws'
def make_request(method="GET", url="", request_body=None):
"""
Send API request ( json type )
:param method:
:param url:
:param request_body:
:return:
"""
headers = {
'Authorization': "Bearer {}".format(CF_API_TOKEN),
'Content-Type': 'application/json'
}
data = None
if request_body:
# data = urllib.parse.urlencode(request_body)
data = request_body.encode('ascii')
try:
req = urllib.request.Request(url, headers=headers, data=data, method=method)
with urllib.request.urlopen(req) as response:
resp_content = response.read()
return resp_content
except urllib.error.HTTPError as e:
print(e.code)
print(e.read())
except urllib.error.URLError as e:
print(e.reason)
return False
def get_local_ip():
"""
Get current public IP of server
:return: string
"""
svc_list = {
'amazonaws': 'https://checkip.amazonaws.com/',
'ifconfig.me': 'https://ifconfig.me/ip',
'icanhazip.com': 'https://icanhazip.com/',
'ipecho': 'https://ipecho.net/plain',
}
if PUBLIC_IP_SERVICE not in svc_list:
raise ValueError("Unknown service")
endpoint = svc_list[PUBLIC_IP_SERVICE]
return make_request(url=endpoint).strip().decode('utf-8')
def get_old_ip():
"""
Get old public IP if exist
:return:
"""
old_ip = None
if path.exists("old_ip.txt"):
with open('old_ip.txt', 'r') as fp:
old_ip = fp.read().strip()
return old_ip
def save_old_ip(ip):
"""
Write current public IP to file
:param ip:
:return:
"""
with open('old_ip.txt', 'w+') as fp:
fp.write(ip)
def get_record_id(zone_id, record_name):
"""
Get CloudFlare record id from domain/sub-domain name
:param zone_id:
:param record_name:
:return:
"""
endpoint = "https://api.cloudflare.com/client/v4/zones/{}/dns_records?name={}&type=A".format(
zone_id,
record_name
)
response = make_request("GET", endpoint)
data = json.loads(response)
if not data['success']:
return False
for record in data['result']:
if record['name'] == record_name:
return record['id']
return False
def update_host(zone_id, record_name, public_ip, is_proxied):
"""
Update host to CloudFlare
:param zone_id:
:param record_name:
:param public_ip:
:param is_proxied:
:return:
"""
record_id = get_record_id(zone_id, record_name)
if not record_id:
print("Record not found")
return False
endpoint = "https://api.cloudflare.com/client/v4/zones/{}/dns_records/{}".format(
zone_id,
record_id
)
payload = {
"type": "A",
"name": record_name,
"content": public_ip,
"proxied": is_proxied
}
response = make_request(
method="PUT",
url=endpoint,
request_body=json.dumps(payload)
)
data = json.loads(response)
if not data['success']:
print("Failed to update {}:{}".format(record_name, public_ip))
return False
print("Success update {}:{}".format(record_name, public_ip))
return True
def get_config(config_path='config.ini'):
"""
Read and parsing config from ini file.
Set global var CF_API_TOKEN
:return:
"""
global CF_API_TOKEN
global PUBLIC_IP_SERVICE
if not path.exists(config_path):
raise RuntimeError("config file not found")
config = ConfigParser()
config.read(config_path)
if "common" not in config:
raise Exception("Common config not found.")
if "CF_API_TOKEN" not in config['common'] or not config['common']['CF_API_TOKEN']:
raise Exception("Missing CloudFlare API Token on config file")
CF_API_TOKEN = config['common']['CF_API_TOKEN']
if config['common'].get('CHECK_IP_SERVICE'):
PUBLIC_IP_SERVICE = config['common']['CHECK_IP_SERVICE']
config_sections = config.sections()
config_sections.remove("common")
if not config_sections:
raise Exception("Empty site to update DNS")
return config, config_sections
def process_section(section_data, public_ip):
"""
Process all record in section
:param section_data:
:param public_ip:
:return:
"""
base_domain = section_data["base_domain"].strip()
record_list = section_data["records"].strip().split("|")
proxied_record_list = section_data["proxied_records"].strip().split("|") if "proxied_records" in section_data else ""
for record in record_list:
record = record.strip()
dns_record = base_domain
is_proxied = False
if record != '@':
dns_record = "{}.{}".format(record, base_domain)
if IS_DRYRUN:
print("[DRY RUN] Update record `{}` in zone id `{}`".format(dns_record, section_data['zone_id']))
continue
if record in proxied_record_list:
is_proxied = True
update_host(section_data['zone_id'], dns_record, public_ip, is_proxied)
def main(args):
"""
Argument from input
:param args:
:return:
"""
config, config_sections = get_config(config_path=args.config)
public_ip = get_local_ip()
print("")
print("--- [{}] Public IP: {}".format(PUBLIC_IP_SERVICE, public_ip))
if not IS_DRYRUN and public_ip == get_old_ip():
print("Skip update")
exit()
for section in config_sections:
print("")
print("--- Updating {} ---".format(section))
if "base_domain" not in config[section] or not config[section]["base_domain"]:
print("Not found `base_domain` config on section `{}`".format(section))
continue
if "records" not in config[section] or not config[section]["records"]:
print("Not found `records` config on section `{}`".format(section))
continue
process_section(section_data=config[section], public_ip=public_ip)
if not IS_DRYRUN:
print("Save old IP")
save_old_ip(public_ip)
if __name__ == "__main__":
nx_parser = argparse.ArgumentParser(
prog='cf-dns-update',
usage='%(prog)s [options] --config config_path',
description='Dynamic DNS record update utility for CloudFlare DNS service.'
)
nx_parser.add_argument('--config', action='store', type=str, default='config.ini')
nx_parser.add_argument('--dryrun', '--check', action='store_true')
input_args = nx_parser.parse_args()
IS_DRYRUN = input_args.dryrun
main(args=input_args)