-
Notifications
You must be signed in to change notification settings - Fork 1
/
joker.py
executable file
·374 lines (339 loc) · 12.2 KB
/
joker.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
#!/usr/bin/env python3
#
# joker.com DMAPI for python
#
# (c) 2019 Alexander D. Kanevskiy <[email protected]>
#
# SPDX-License-Identifier: Apache-2.0
import os
import re
import sys
from pprint import pprint
import requests
class Joker:
def __init__(self, api_key="", username="", password="", url="https://dmapi.joker.com"):
if not api_key and not (username and password):
raise ValueError("api_key or username/password must be defined")
self.api_key = api_key
self.username = username
self.password = password
self.url = url
self.auth_sid = ""
self.supported_domains = []
self.account_info = {}
self.__session = None
self.__new_session()
def login(self):
if self.api_key:
params = {"api-key": self.api_key}
elif self.username and self.password:
params = {"username": self.username, "password": self.password}
else:
raise IOError("Can't login: missing credentials")
response = JokerResponse(self.get_request("login", params))
code, text = response.status()
if code != 0:
raise IOError(text)
if "Auth-Sid" in response.headers:
self.auth_sid = response.headers["Auth-Sid"]
else:
raise IOError("Unexpected login falure: no Auth-Sid in response")
self.__update_account_info(response.headers)
self.supported_domains = response.as_list()
return response
def logout(self):
res = ""
if self.auth_sid:
res = self.get_request("logout")
self.auth_sid = ""
self.account_info = {}
self.supported_domains = []
return JokerResponse(res)
def dns_zone_list(self, pattern=""):
params = {}
if pattern:
params["pattern"] = pattern
response = JokerResponse(self.get_request("dns-zone-list", params))
return response
def dns_zone_get(self, domain):
if not domain:
raise IOError("Domain must be specified")
response = JokerResponse(self.get_request("dns-zone-get", {"domain": domain}))
return response
def dns_zone_put(self, domain, zone):
if not domain or not zone:
raise IOError("Domain and zone must not be empty")
response = JokerResponse(
self.post_request("dns-zone-put", {"domain": domain, "zone": zone})
)
return response
def get_request(self, command, parameters={}):
url = self.url + "/request/" + command
if self.auth_sid:
parameters["auth-sid"] = self.auth_sid
self.__new_session()
try:
response = self.__session.get(url, params=parameters)
# pylint: disable=E1101
if response.status_code != requests.codes.ok:
raise IOError("HTTP Status Code: %s" % response.status_code)
return response.text
except requests.ConnectionError as e:
raise IOError("Connection Error: %s" % str(e))
except requests.HTTPError as e:
raise IOError("Http Error: %s" % str(e))
except IOError as e:
raise e
except Exception as e:
raise IOError("Unexpected Error: %s" % str(e))
def post_request(self, command, parameters={}):
url = self.url + "/request/" + command
if self.auth_sid:
parameters["auth-sid"] = self.auth_sid
self.__new_session()
try:
response = self.__session.post(url, data=parameters)
# pylint: disable=E1101
if response.status_code != requests.codes.ok:
raise IOError(
"HTTP-Status-Code: %s\n%s" % (response.status_code, response.text)
)
return response.text
except requests.ConnectionError as e:
raise IOError("Connection Error: %s" % str(e))
except requests.HTTPError as e:
raise IOError("Http Error: %s" % str(e))
except IOError as e:
raise e
except Exception as e:
raise IOError("Unexpected Error: %s" % str(e))
def __new_session(self):
if self.__session:
return
_needed_headers = {
"User-Agent": "Joker python DMAPI",
"Referer": "dmapi.joker.com",
# "Accept": "application/json, text/javascript, */*; q=0.01",
}
session = requests.Session()
session.headers.update(_needed_headers)
self.__session = session
def __update_account_info(self, headers):
important_headers = [
"Account-balance",
"Account-contract_date",
"Account-currency",
"Account-rebate",
"UID",
"User-Access",
"User-Login",
]
for key in important_headers:
if key in headers:
self.account_info[key] = headers[key]
def find_domain_for_fdqn(self, fdqn):
domain = ""
local_entry = ""
rzl = self.dns_zone_list()
if rzl.status()[0] == 0:
for dom, _ in rzl.as_separated_lists():
if fdqn.endswith(dom + ".") and len(dom) > len(domain):
domain = dom
# print("Found domain: '%s'" % domain)
# else:
# print("Unable to list zones: %s" % rzl.status)
if domain:
if fdqn == domain + ".":
local_entry = "@"
else:
local_entry = fdqn[: -len("." + domain + ".")]
return domain, local_entry
def add_txt_record(self, domain, record, value, ttl=60):
if not domain or not record or not value:
raise ValueError("domain, record or value can't be empty")
rzg = self.dns_zone_get(domain)
if rzg.status()[0] != 0:
return rzg
zl = rzg.body.splitlines()
zl.append(
'%(record)s TXT 0 "%(value)s" %(ttl)d'
% {"record": record, "value": value, "ttl": ttl}
)
zone = "\n".join(zl)
return self.dns_zone_put(domain, zone)
def remove_txt_record(self, domain, record, value=""):
if not domain or not record:
raise ValueError("domain and record can't be empty")
rzg = self.dns_zone_get(domain)
if rzg.status()[0] != 0:
return rzg
zl = rzg.body.splitlines()
old_zone = "\n".join(zl)
if value:
# TODO: Some records have additional spaces in the end of values.
line = '%(record)s TXT 0 "%(value)s"' % {"record": record, "value": value}
else:
line = "%(record)s TXT 0 " % {"record": record}
zl = [l for l in zl if not l.startswith(line)]
zone = "\n".join(zl)
if old_zone == zone:
# print("No changes in the zone: no update necessary")
return JokerResponse('Status-Code: 0\nStatus-Text: "No update needed"\n')
return self.dns_zone_put(domain, zone)
class JokerResponse:
def __init__(self, message):
self.headers = {}
self.body = ""
parts = message.split("\n\n")
if parts:
self.headers = JokerResponse.__parse_key_values(parts[0])
if len(parts) > 1:
self.body = parts[1]
def status(self):
code = -1
text = ""
if "Status-Code" in self.headers:
code = int(self.headers["Status-Code"])
if "Status-Text" in self.headers:
text = self.headers["Status-Text"]
return code, text
def as_list(self):
return self.body.splitlines()
def as_separated_lists(self):
res = []
if "Separator" in self.headers and self.headers["Separator"] == "TAB":
sep = "\t"
else:
sep = " "
for line in self.body.splitlines():
res.append(line.split(sep))
return res
def as_list_of_dicts(self):
res = []
if "Columns" in self.headers:
columns = self.headers["Columns"].split(",")
for line in self.as_separated_lists():
entry = {}
for idx, val in enumerate(line):
entry[columns[idx]] = val
res.append(entry)
return res
@staticmethod
def __parse_key_values(message):
headers = {}
for line in message.splitlines():
split = re.split(r"\s*:\s*", line, 1)
if len(split) > 1:
headers[split[0]] = split[1]
else:
headers[split[0]] = ""
return headers
def usage():
prg = sys.argv[0]
usage = """Usage:
%(prg)s: info
%(prg)s: present <FQDN> <record>
%(prg)s: cleanup <FQDN> <record>
%(prg)s: get-zone <domain>
%(prg)s: put-zone <domain> <zone-file>
Invoked with: %(args)s
""" % {
"prg": prg,
"args": sys.argv,
}
raise SystemExit(usage)
if __name__ == "__main__":
debug = False
err = None
argc = len(sys.argv)
if argc < 2:
usage()
mode = sys.argv[1]
if mode not in ("info", "present", "cleanup", "get-zone", "put-zone", "test"):
raise SystemExit("Invalid mode %s" % mode)
key = os.getenv("JOKER_API_KEY")
if not key:
raise SystemExit("JOKER_API_KEY must be defined")
if debug:
print("Logging in")
dmapi = Joker(api_key=key)
res = dmapi.login()
code, text = res.status()
if code != 0:
raise SystemExit("Unable to login: %s" % text)
if mode == "info" and argc == 2:
print("Account info:")
pprint(dmapi.account_info)
rzl = dmapi.dns_zone_list()
if rzl.status()[0] == 0:
print("Account domains:")
for domain, expire in rzl.as_separated_lists():
print("Domain: %s Expires: %s" % (domain, expire))
elif mode == "present" and argc == 4:
entry = sys.argv[2]
value = sys.argv[3]
domain, record = dmapi.find_domain_for_fdqn(entry)
if domain:
print(
"Adding record '%s' with value '%s' to domain '%s'"
% (record, value, domain)
)
try:
resp = dmapi.add_txt_record(domain, record, value)
code, text = resp.status()
if code != 0:
err = text + "\n" + str(resp.headers)
except IOError as e:
err = "Error adding TXT entry:\n" + str(e)
elif mode == "cleanup" and argc == 4:
entry = sys.argv[2]
value = sys.argv[3]
domain, record = dmapi.find_domain_for_fdqn(entry)
if domain:
print(
"Removing record '%s' with value '%s' to domain '%s'"
% (record, value, domain)
)
try:
resp = dmapi.remove_txt_record(domain, record)
code, text = resp.status()
if code != 0:
err = text + "\n" + str(resp.headers)
except IOError as e:
err = "Error removing TXT entry:\n" + str(e)
elif mode == "get-zone" and argc == 3:
rzg = dmapi.dns_zone_get(sys.argv[2])
code, text = rzg.status()
if code == 0:
print(rzg.body)
else:
err = text
elif mode == "put-zone" and argc == 4:
zone = ""
if os.path.exists(sys.argv[3]) and os.path.isfile(sys.argv[3]):
zone = open(sys.argv[3], "r").read().strip()
else:
err = "File %s either doesn't exist or not a regular file" % sys.argv[3]
if zone:
try:
rzg = dmapi.dns_zone_put(sys.argv[2], zone)
code, text = rzg.status()
if code == 0:
print(rzg.body)
else:
err = text
except IOError as e:
err = "Error while submitting zone:\n" + str(e)
else:
err = "Zone is empty"
elif mode == "test":
pass
else:
err = "Something wrong. Mode: '%s' arguments: %d" % (mode, argc)
if debug:
print("Logging out")
rl = dmapi.logout()
code, text = rl.status()
if text != "OK":
raise SystemExit("Unable to logout: %s" % text)
raise SystemExit(err)