-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdynflare
executable file
·264 lines (238 loc) · 7.51 KB
/
dynflare
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
#!/usr/bin/env python3
# imports
import argparse, os, sys, re, random, json
from datetime import datetime, tzinfo, timedelta
try:
from configparser import ConfigParser, NoOptionError
from io import StringIO
import urllib.request as urllib2
except ImportError: # Python 2 fallback
from ConfigParser import SafeConfigParser as ConfigParser
from ConfigParser import NoOptionError
from cStringIO import StringIO
import urllib2
# classes
# there's no datetime.timezone until Python 3.2
class UTC(tzinfo):
'''UTC'''
def utcoffset(self, dt):
return timedelta(0)
def tzname(self, dt):
return 'UTC'
def dst(self, dt):
return timedelta(0)
class MethodRequest(urllib2.Request):
def __init__(self, *args, **kwargs):
if 'method' in kwargs:
self._method = kwargs['method']
del kwargs['method']
else:
self._method = None
return urllib2.Request.__init__(self, *args, **kwargs)
def get_method(self, *args, **kwargs):
if self._method is not None:
return self._method
return urllib2.Request.get_method(self, *args, **kwargs)
# functions
def timestamp():
return datetime.now(UTC()).ctime()
def dequote(s):
if (s[0] == s[-1]) and s.startswith(("'", '"')):
return s[1:-1]
return s
def read_conf_value(cfg, value):
return dequote(cfg.get('default', value))
def read_conf(cfg, stream):
try:
cfg.read_file(stream)
except AttributeError: # Python 2 fallback
cfg.readfp(stream)
def get_conf_values(conf, token, email, key):
if type(conf) is type(None):
return
cfg = ConfigParser()
with open(os.path.expanduser(conf)) as stream:
# workaround ConfigParser's deficiency
stream = StringIO(u'[default]\n' + stream.read())
read_conf(cfg, stream)
try:
os.environ['CLOUDFLARE_API_KEY'] = read_conf_value(cfg, token)
except NoOptionError:
try:
os.environ['CLOUDFLARE_EMAIL'] = read_conf_value(cfg, email)
os.environ['CLOUDFLARE_API_KEY'] = read_conf_value(cfg, key)
except NoOptionError:
sys.exit('Fatal: invalid config file. Expecting email + key or token!')
def set_email(email):
em = os.environ.get('CLOUDFLARE_EMAIL')
em = email if type(email) is not type(None) else em
if type(em) is not type(None):
os.environ['CLOUDFLARE_EMAIL'] = em
def set_api_key(api_key):
ak = os.environ.get('CLOUDFLARE_API_KEY')
ak = api_key if type(api_key) is not type(None) else ak
if type(ak) is type(None):
sys.exit('Fatal: you must specify at least an API token!')
os.environ['CLOUDFLARE_API_KEY'] = ak
def get_cf_ip(name, type):
headers = { 'accept': 'application/dns-json' }
url = 'https://cloudflare-dns.com/dns-query?name=' + name + '&type=' + type
res = http_request(url, headers)
record = json.loads(res)
if record['Status'] != 0:
return ''
try:
return record['Answer'][0]['data']
except:
return ''
def get_my_ip():
cfg = ConfigParser()
cf_trace = http_request('https://cloudflare.com/cdn-cgi/trace')
stream = StringIO(u'[default]\n' + cf_trace)
read_conf(cfg, stream)
return read_conf_value(cfg, 'ip')
def http_request(url, headers = {}, method = 'GET', data=b''):
method = method.upper()
try:
if method == 'GET':
req = urllib2.Request(url=url, headers=headers)
else:
req = MethodRequest(url=url, headers=headers, data=data, method=method)
res = urllib2.urlopen(req)
res_body = res.read()
return res_body.decode('utf-8')
except Exception as err:
sys.exit('[%s] %s request to %s responded with %s' % (timestamp(), method, url, err))
def get_cloudflare_api_url():
return 'https://api.cloudflare.com/client/v4/'
def get_cloudflare_headers():
try:
return {
'x-auth-email': os.environ['CLOUDFLARE_EMAIL'],
'x-auth-key': os.environ['CLOUDFLARE_API_KEY'],
'content-type': 'application/json'
}
except:
return {
'Authorization': 'Bearer ' + os.environ['CLOUDFLARE_API_KEY'],
'content-type': 'application/json'
}
def zones_dns_records(zid):
return get_cloudflare_api_url() + 'zones/' + zid + '/dns_records'
def zones_dns_record(zid, rid):
return zones_dns_records(zid) + '/' + rid
def get_record_info(zid, host, type):
url = zones_dns_records(zid) + '?name=' + host + '&type' + type
req = http_request(url, get_cloudflare_headers())
record_info = json.loads(req)
return record_info['result'][0]
def json_encode(dict):
return json.dumps(dict).encode('utf-8')
def create_dns_record(zid, host, type, ttl, ip):
url = zones_dns_records(zid)
data = {
'name': host,
'type': type,
'content': ip,
'ttl': ttl
}
http_request(url, get_cloudflare_headers(), 'post', json_encode(data))
print('[%s] Created %s with content %s' % (timestamp(), host, ip))
def update_dns_record(zid, host, type, ttl, ip):
rinf = get_record_info(zid, host, type)
rid = rinf['id']
url = zones_dns_record(zid, rid)
data = {
'type': type,
'content': ip,
'ttl': ttl
}
http_request(url, get_cloudflare_headers(), 'patch', json_encode(data))
print('[%s] Updated %s with content %s' % (timestamp(), host, ip))
def upsert_dns_record(zid, host, type, ttl, my_ip, cf_ip):
type = type.upper()
if cf_ip == '':
create_dns_record(zid, host, type, ttl, my_ip)
elif my_ip != cf_ip:
update_dns_record(zid, host, type, ttl, my_ip)
else:
print('[%s] Host %s is already up to date with %s' % (timestamp(), host, my_ip))
def get_args():
parser = argparse.ArgumentParser(
description = '''
Dynamic DNS script for updating a record with your machine's public IP address.
Supports Cloudflare DNS hosted zones.
''',
epilog = '''
EMAIL and API_KEY may be read from environment as CLOUDFLARE_EMAIL and
CLOUDFLARE_API_KEY. They need to be specified as arguments only
when the environment variables are undefined or when they need to be
overridden.
'''
)
parser.add_argument(
'--host',
dest = 'host',
type = str,
help = 'DNS hostname to update.',
required = True
)
parser.add_argument(
'--zone-id',
dest = 'zone_id',
type = str,
help = 'Cloudflare Zone ID',
required = True
)
parser.add_argument(
'--email',
dest = 'email',
type = str,
help = 'Cloudflare email address. Only required for global API key.'
)
parser.add_argument(
'--api-key',
dest = 'api_key',
type = str,
help = 'Cloudflare API key or API token.'
)
parser.add_argument(
'--record-type',
dest = 'record_type',
type = str,
help = 'Cloudflare DNS zone record type',
default = 'A'
)
parser.add_argument(
'--ttl',
dest = 'ttl',
type = int,
help = 'Cloudflare DNS host record TTL',
default = 60
)
parser.add_argument(
'--conf-certbot',
dest = 'conf_certbot',
type = str,
help = ('Configuration file containing email + key or token using same syntax as '
'the Certbot Cloudflare plug-in.')
)
parser.add_argument(
'--conf-acmesh',
dest = 'conf_acmesh',
type = str,
help = ('Configuration file containing email + key or token using same syntax as '
'the acme.sh Cloudflare dnsapi.')
)
return parser.parse_args()
def main(args):
get_conf_values(args.conf_certbot, 'dns_cloudflare_api_token', 'dns_cloudflare_email', 'dns_cloudflare_api_key')
get_conf_values(args.conf_acmesh, 'SAVED_CF_Token', 'SAVED_CF_Email', 'SAVED_CF_Key')
set_email(args.email)
set_api_key(args.api_key)
my_ip = get_my_ip()
cf_ip = get_cf_ip(args.host, args.record_type)
upsert_dns_record(args.zone_id, args.host, args.record_type, args.ttl, my_ip, cf_ip)
# implementation
if __name__ == '__main__':
main(get_args())