-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
571 lines (518 loc) · 23.1 KB
/
main.py
File metadata and controls
571 lines (518 loc) · 23.1 KB
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
import csv
import json
import argparse
import sys
import time
import socket
import ipaddress
from typing import Dict, Tuple, List, Optional
import requests
from requests.auth import HTTPBasicAuth
API_BASE = "https://api.name.com/core/v1"
SKIP_TYPES = {"SOA", "NS"}
def parse_basic(token_arg: str) -> Tuple[str, str]:
if ":" not in token_arg:
raise SystemExit("Use --token in the form USERNAME:APITOKEN")
u, t = token_arg.split(":", 1)
if not u or not t:
raise SystemExit("Invalid --token. Expected USERNAME:APITOKEN")
return u, t
def session_basic(user: str, token: str) -> requests.Session:
s = requests.Session()
s.auth = HTTPBasicAuth(user, token)
s.headers.update({"Content-Type": "application/json"})
return s
def list_records(sess: requests.Session, domain: str) -> List[Dict]:
url = f"{API_BASE}/domains/{domain}/records"
r = sess.get(url, timeout=30)
r.raise_for_status()
return r.json().get("records", [])
def create_record(sess: requests.Session, domain: str, payload: Dict) -> Dict:
url = f"{API_BASE}/domains/{domain}/records"
body = api_payload(payload)
r = sess.post(url, data=json.dumps(body), timeout=30)
r.raise_for_status()
return r.json()
def update_record(sess: requests.Session, domain: str, rec_id: int, payload: Dict) -> Dict:
url = f"{API_BASE}/domains/{domain}/records/{rec_id}"
body = api_payload(payload)
r = sess.put(url, data=json.dumps(body), timeout=30)
r.raise_for_status()
return r.json()
def to_rel_host(host: str, zone: str) -> str:
"""
Normalize a host to a relative label for the given zone.
'' or '@' or 'example.com' -> '@' for zone 'example.com'
'www.example.com' -> 'www' for zone 'example.com'
'api' -> 'api'
'x.other.com' (not in zone) -> 'x.other.com'
"""
h = (host or "").strip(".")
z = (zone or "").strip(".")
if not h or h == "@" or h.lower() == z.lower():
return "@"
suf = "." + z.lower()
return h[: -len(suf)].rstrip(".") if h.lower().endswith(suf) else h
def map_suffix(host: str, mapping: Tuple[str, str]) -> str:
"""
Rewrite the suffix of a fully qualified host. Keeps the stem.
old.com -> new.com:
'www.old.com' -> 'www.new.com'
'old.com' -> 'new.com'
"""
if not host:
return host
old, new = mapping
old = old.strip(".").lower()
new = new.strip(".")
h = host.strip(".")
if h.lower() == old:
return new
if h.lower().endswith("." + old):
stem = h[: -(len(old))].rstrip(".")
return (stem + "." + new).strip(".")
return host
def load_csv_rows(path: str) -> List[Dict]:
with open(path, newline="", encoding="utf-8") as f:
r = csv.DictReader(f)
need = ["Type", "Host", "Answer", "TTL", "Priority"]
miss = [c for c in need if c not in (r.fieldnames or [])]
if miss:
raise SystemExit(f"CSV missing columns: {miss}")
rows = []
for row in r:
rows.append({k: (v.strip() if v is not None else "") for k, v in row.items()})
return rows
def payload_from_csv_row(row: Dict, target_zone: str, suffix_map: Optional[Tuple[str, str]] = None) -> Optional[Dict]:
rtype = row["Type"].upper()
if rtype in SKIP_TYPES:
return None
host = row["Host"].strip()
if suffix_map and host:
host = map_suffix(host, suffix_map)
host_rel = to_rel_host(host, target_zone)
ttl = int(row["TTL"]) if row.get("TTL") else 300
payload = {"type": rtype, "host": host_rel, "answer": row["Answer"], "ttl": ttl}
prio = row.get("Priority", "")
if rtype in ("MX", "SRV") and prio != "":
payload["priority"] = int(prio)
return payload
def payload_from_api_record(rec: Dict, source_zone: str, target_zone: str, suffix_map: Optional[Tuple[str, str]] = None) -> Optional[Dict]:
rtype = rec.get("type", "").upper()
if rtype in SKIP_TYPES:
return None
src_host = rec.get("host", "@") or "@"
if suffix_map:
fqdn = source_zone if src_host in ("@", "") else f"{src_host}.{source_zone}"
fqdn_mapped = map_suffix(fqdn, suffix_map)
host_rel = to_rel_host(fqdn_mapped, target_zone)
else:
host_rel = src_host
payload = {
"type": rtype,
"host": host_rel,
"answer": rec.get("answer", ""),
"ttl": int(rec.get("ttl", 300)),
}
if rtype in ("MX", "SRV") and rec.get("priority") not in (None, ""):
payload["priority"] = int(rec["priority"])
if rtype == "SRV":
if rec.get("port") not in (None, ""):
payload["port"] = int(rec["port"])
if rec.get("weight") not in (None, ""):
payload["weight"] = int(rec["weight"])
return payload
def key_ht(payload: Dict, zone: str = None) -> Tuple[str, str, Optional[int]]:
h = payload.get("host", "@")
if zone is not None:
h = to_rel_host(h, zone)
t = (payload.get("type") or "").upper()
pri: Optional[int] = None
if t in ("MX", "SRV"):
p = payload.get("priority")
if p not in (None, ""):
pri = int(p)
return (h, t, pri)
def same_record(a: Dict, b: Dict) -> bool:
fields = ["type", "host", "answer", "ttl", "priority", "port", "weight"]
for f in fields:
av = a.get(f, None)
bv = b.get(f, None)
if f == "ttl":
av = int(av) if av not in (None, "") else None
bv = int(bv) if bv not in (None, "") else None
if av != bv:
return False
return True
def resolve_host(hostname: str) -> List[str]:
"""Return a list of unique IPs for hostname. Empty list on failure."""
try:
info = socket.getaddrinfo(hostname, None, proto=socket.IPPROTO_TCP)
except Exception:
return []
addrs = []
for _, _, _, _, sockaddr in info:
ip = sockaddr[0]
addrs.append(ip)
return sorted(set(addrs))
def prompt_yes_no(q: str) -> bool:
while True:
ans = input(f"{q.strip()} ").strip().lower()
if ans in ("y", "yes"):
return True
if ans in ("n", "no"):
return False
print("Please enter y or n.")
def prompt_choice(q: str, choices: List[str]) -> str:
choices_norm = [c.upper() for c in choices]
while True:
ans = input(f"{q.strip()} {choices_norm}: ").strip().upper()
if ans in choices_norm:
return ans
print(f"Please choose one of {choices_norm}")
def prompt_ipv4(q: str) -> str:
while True:
s = input(q).strip()
try:
ipaddress.IPv4Address(s)
return s
except Exception:
print("Please enter a valid IPv4 address.")
def prompt_ipv6(q: str) -> str:
while True:
s = input(q).strip()
try:
ipaddress.IPv6Address(s)
return s
except Exception:
print("Please enter a valid IPv6 address.")
def prompt_ttl(default_val: int = 300) -> int:
while True:
s = input(f"Enter TTL seconds [{default_val}]: ").strip()
if s == "":
return default_val
try:
v = int(s)
if v > 0:
return v
except Exception:
pass
print("Please enter a positive integer.")
def ensure_mx_answer_ready(sess: requests.Session, target_zone: str, mx_answer: str, dry_run: bool = False) -> str:
"""
Expand short answers, verify resolution, and optionally create a host record.
Returns the FQDN to use as the MX answer.
If CNAME target does not resolve, block creation and re-prompt for record type.
"""
ans = (mx_answer or "").strip().strip(".")
fqdn = ans if "." in ans else f"{ans}.{target_zone}".strip(".")
addrs = resolve_host(fqdn)
if addrs:
print(f"[MX check] {fqdn} resolves to: {', '.join(addrs)}")
return fqdn
print(f"[MX check] {fqdn} did not resolve to an IP.")
if not prompt_yes_no("Create a host record now (y/n)?"):
if prompt_yes_no("Proceed with MX even though it does not resolve (y/n)?"):
return fqdn
raise SystemExit("Aborted. MX target does not resolve.")
host_label = to_rel_host(fqdn, target_zone)
while True:
rtype = prompt_choice("Choose record type to create for the host", ["A", "AAAA", "CNAME"])
if rtype == "A":
ip = prompt_ipv4("Enter IPv4 address for A: ")
ttl = prompt_ttl(300)
payload = {"type": "A", "host": host_label, "answer": ip, "ttl": ttl}
if dry_run:
print(f"DRY RUN create A {host_label} -> {ip}")
else:
try:
create_record(sess, target_zone, payload)
print(f"Created A {host_label} -> {ip}")
except requests.HTTPError as e:
print(f"Failed to create A: {e} {getattr(e.response,'text','')}", file=sys.stderr)
continue
break
if rtype == "AAAA":
ip6 = prompt_ipv6("Enter IPv6 address for AAAA: ")
ttl = prompt_ttl(300)
payload = {"type": "AAAA", "host": host_label, "answer": ip6, "ttl": ttl}
if dry_run:
print(f"DRY RUN create AAAA {host_label} -> {ip6}")
else:
try:
create_record(sess, target_zone, payload)
print(f"Created AAAA {host_label} -> {ip6}")
except requests.HTTPError as e:
print(f"Failed to create AAAA: {e} {getattr(e.response,'text','')}", file=sys.stderr)
continue
break
if rtype == "CNAME":
cname_target = input("Enter CNAME target FQDN: ").strip().strip(".")
if "." not in cname_target:
cname_target = f"{cname_target}.{target_zone}".strip(".")
test_addrs = resolve_host(cname_target)
if not test_addrs:
print(f"[CNAME check] {cname_target} does not resolve. Creation blocked.")
if not prompt_yes_no("Try again choosing a different record type (y/n)?"):
raise SystemExit("Aborted. CNAME target did not resolve.")
continue
print(f"[CNAME check] {cname_target} resolves to: {', '.join(test_addrs)}")
ttl = prompt_ttl(300)
payload = {"type": "CNAME", "host": host_label, "answer": cname_target, "ttl": ttl}
if dry_run:
print(f"DRY RUN create CNAME {host_label} -> {cname_target}")
else:
try:
create_record(sess, target_zone, payload)
print(f"Created CNAME {host_label} -> {cname_target}")
except requests.HTTPError as e:
print(f"Failed to create CNAME: {e} {getattr(e.response,'text','')}", file=sys.stderr)
continue
break
final_addrs = resolve_host(fqdn)
if final_addrs:
print(f"[Post-create check] {fqdn} resolves to: {', '.join(final_addrs)}")
else:
print(f"[Post-create check] {fqdn} still does not resolve.")
return fqdn
def upsert_into_target(sess: requests.Session, target_domain: str, desired_payloads: List[Dict], upsert: bool = True, dry_run: bool = False) -> Tuple[int, int, int]:
try:
existing = list_records(sess, target_domain)
except requests.HTTPError as e:
body = getattr(e.response, "text", "")
raise SystemExit(f"Failed to list records for {target_domain}: {e} {body}")
existing_map: Dict[Tuple[str, str, Optional[int]], Dict] = {}
for rec in existing:
rel = to_rel_host(rec.get("host", "@"), target_domain)
t = (rec.get("type") or "").upper()
pri: Optional[int] = None
if t in ("MX", "SRV"):
p = rec.get("priority")
if p not in (None, ""):
pri = int(p)
existing_map[(rel, t, pri)] = rec
created = updated = skipped = 0
for p in desired_payloads:
if not p:
continue
p["host"] = to_rel_host(p.get("host", "@"), target_domain)
p["type"] = (p.get("type") or "").upper()
# normalize priority presence for MX/SRV
if p["type"] in ("MX", "SRV"):
if p.get("priority") not in (None, ""):
p["priority"] = int(p["priority"])
else:
p["priority"] = None
key = (p["host"], p["type"], p.get("priority") if p["type"] in ("MX", "SRV") else None)
match = existing_map.get(key)
if match:
existing_comp = {
"type": (match.get("type") or "").upper(),
"host": to_rel_host(match.get("host", "@"), target_domain),
"answer": match.get("answer"),
"ttl": int(match.get("ttl", 300)) if match.get("ttl") not in (None, "") else 300,
"priority": int(match["priority"]) if match.get("priority") not in (None, "") else None,
"port": match.get("port"),
"weight": match.get("weight"),
}
if same_record(p, existing_comp):
print(f"Skip unchanged {p['type']} {p['host']}{'' if p['type'] not in ('MX','SRV') else f' (pri {p.get('priority')})'}")
skipped += 1
continue
if upsert:
if dry_run:
print(f"DRY RUN update {p['type']} {p['host']} -> {p['answer']}{'' if p['type']!='MX' else f' (pri {p.get('priority')})'}")
else:
try:
update_record(sess, target_domain, match["id"], p)
print(f"Updated {p['type']} {p['host']} -> {p['answer']}{'' if p['type']!='MX' else f' (pri {p.get('priority')})'}")
except requests.HTTPError as e:
body = getattr(e.response, "text", "")
raise SystemExit(f"Update failed: {e} {body}")
updated += 1
else:
if dry_run:
print(f"DRY RUN create {p['type']} {p['host']} -> {p['answer']}{'' if p['type']!='MX' else f' (pri {p.get('priority')})'}")
else:
try:
create_record(sess, target_domain, p)
print(f"Created {p['type']} {p['host']} -> {p['answer']}{'' if p['type']!='MX' else f' (pri {p.get('priority')})'}")
except requests.HTTPError as e:
body = getattr(e.response, "text", "")
raise SystemExit(f"Create failed: {e} {body}")
created += 1
else:
if dry_run:
print(f"DRY RUN create {p['type']} {p['host']} -> {p['answer']}{'' if p['type']!='MX' else f' (pri {p.get('priority')})'}")
else:
try:
create_record(sess, target_domain, p)
print(f"Created {p['type']} {p['host']} -> {p['answer']}{'' if p['type']!='MX' else f' (pri {p.get('priority')})'}")
except requests.HTTPError as e:
body = getattr(e.response, "text", "")
raise SystemExit(f"Create failed: {e} {body}")
created += 1
time.sleep(0.05)
return created, updated, skipped
def validate_manual_args(args):
if not args.add:
return
if not args.add_type or not args.add_answer:
raise SystemExit("When using --add you must provide --type and --answer")
t = args.add_type.upper()
if t == "MX":
if args.add_priority is None:
raise SystemExit("When --type MX you must provide --pri for the MX priority")
else:
if not args.add_host:
raise SystemExit("When using --add for non-MX you must provide --host")
if args.add_ttl is not None and args.add_ttl <= 0:
raise SystemExit("--ttl must be a positive integer")
def build_manual_payload(args, target_zone):
rtype = args.add_type.upper().strip()
ttl = args.add_ttl if args.add_ttl is not None else 300
if rtype == "MX":
host_rel = "@"
ans = args.add_answer.strip()
ans_fqdn = ans if "." in ans else f"{ans}.{target_zone}".strip(".")
payload = {"type": "MX", "host": host_rel, "answer": ans_fqdn, "ttl": int(ttl), "priority": int(args.add_priority)}
return payload
host_rel = to_rel_host((args.add_host or "@").strip(), target_zone)
return {"type": rtype, "host": host_rel, "answer": args.add_answer.strip(), "ttl": int(ttl)}
def upsert_single(sess, target_domain, payload, do_upsert=True, dry_run=False):
payload["type"] = (payload.get("type") or "").upper()
if payload["type"] == "MX":
payload["host"] = "@"
if payload.get("priority") not in (None, ""):
payload["priority"] = int(payload["priority"])
else:
raise SystemExit("MX requires --pri")
else:
payload["host"] = to_rel_host(payload.get("host", "@"), target_domain)
try:
existing = list_records(sess, target_domain)
except requests.HTTPError as e:
body = getattr(e.response, "text", "")
raise SystemExit(f"Failed to list records: {e} {body}")
match = None
for rec in existing:
if to_rel_host(rec.get("host","@"), target_domain) != payload["host"]:
continue
if (rec.get("type") or "").upper() != payload["type"]:
continue
if payload["type"] in ("MX","SRV"):
rp = rec.get("priority")
rp = int(rp) if rp not in (None,"") else None
if rp != payload.get("priority"):
continue
match = rec
break
if match:
if do_upsert:
if dry_run:
print(f"DRY RUN update {payload['type']} {payload['host']} -> {payload['answer']}{'' if payload['type']!='MX' else f' (pri {payload.get('priority')})'}")
else:
try:
update_record(sess, target_domain, match["id"], payload)
print(f"Updated {payload['type']} {payload['host']} -> {payload['answer']}{'' if payload['type']!='MX' else f' (pri {payload.get('priority')})'}")
except requests.HTTPError as e:
body = getattr(e.response, "text", "")
raise SystemExit(f"Update failed: {e} {body}")
else:
if dry_run:
print(f"DRY RUN create {payload['type']} {payload['host']} -> {payload['answer']}{'' if payload['type']!='MX' else f' (pri {payload.get('priority')})'}")
else:
try:
create_record(sess, target_domain, payload)
print(f"Created {payload['type']} {payload['host']} -> {payload['answer']}{'' if payload['type']!='MX' else f' (pri {payload.get('priority')})'}")
except requests.HTTPError as e:
body = getattr(e.response, "text", "")
raise SystemExit(f"Create failed: {e} {body}")
else:
if dry_run:
print(f"DRY RUN create {payload['type']} {payload['host']} -> {payload['answer']}{'' if payload['type']!='MX' else f' (pri {payload.get('priority')})'}")
else:
try:
create_record(sess, target_domain, payload)
print(f"Created {payload['type']} {payload['host']} -> {payload['answer']}{'' if payload['type']!='MX' else f' (pri {payload.get('priority')})'}")
except requests.HTTPError as e:
body = getattr(e.response, "text", "")
raise SystemExit(f"Create failed: {e} {body}")
def api_payload(p: dict) -> dict:
q = dict(p)
# Apex should be empty string for the API
if q.get("host") in ("@", ""):
q["host"] = ""
# Normalize TTL
if "ttl" in q and q["ttl"] not in (None, ""):
q["ttl"] = int(q["ttl"])
# Only send priority for MX/SRV
t = (q.get("type") or "").upper()
if t not in ("MX", "SRV"):
q.pop("priority", None)
elif q.get("priority") not in (None, ""):
q["priority"] = int(q["priority"])
return q
def main():
ap = argparse.ArgumentParser(
description="Sync Name.com DNS from a source domain and/or CSV into a target domain, or manually add a record"
)
ap.add_argument("--token", required=True, help="USERNAME:APITOKEN (Basic Auth)")
ap.add_argument("--from", dest="src_domain", help="Source domain to read from")
ap.add_argument("--csv", help="CSV with columns Type,Host,Answer,TTL,Priority")
ap.add_argument("--to", dest="dst_domain", required=True, help="Target domain to write to")
ap.add_argument("--map-suffix",
help="Rewrite suffix old.zone=new.zone while importing. Use it if your CSV or source records contain fully qualified names you want rewritten. It just finds and replaces the suffix.")
ap.add_argument("--upsert", action="store_true", help="Update existing host+type instead of duplicating")
ap.add_argument("--dry-run", action="store_true", help="Show actions without calling the API")
ap.add_argument("--add", action="store_true", help="Manually add a single DNS record")
ap.add_argument("--type", dest="add_type", help="Record type, e.g., A, AAAA, CNAME, MX, TXT")
ap.add_argument("--host", dest="add_host", help="Record host label. Use @ for root. Ignored for MX")
ap.add_argument("--answer", dest="add_answer", help="Record answer, e.g., IP or target")
ap.add_argument("--ttl", dest="add_ttl", type=int, help="Record TTL in seconds (default 300)")
ap.add_argument("--pri", dest="add_priority", type=int, help="Priority for MX (required when --type MX)")
args = ap.parse_args()
user, tok = parse_basic(args.token)
sess = session_basic(user, tok)
suffix_map: Optional[Tuple[str, str]] = None
if args.map_suffix:
if "=" not in args.map_suffix:
raise SystemExit("Use --map-suffix old.zone=new.zone")
old, new = args.map_suffix.split("=", 1)
suffix_map = (old, new)
validate_manual_args(args)
if args.add:
payload = build_manual_payload(args, args.dst_domain)
if payload["type"] == "MX":
payload["answer"] = ensure_mx_answer_ready(sess, args.dst_domain, payload["answer"], dry_run=args.dry_run)
upsert_single(sess, args.dst_domain, payload, do_upsert=args.upsert, dry_run=args.dry_run)
return
desired = {}
if args.src_domain:
try:
src_recs = list_records(sess, args.src_domain)
except requests.HTTPError as e:
print(f"Failed to list records for {args.src_domain}: {e} {getattr(e.response, 'text', '')}", file=sys.stderr)
sys.exit(1)
for rec in src_recs:
p = payload_from_api_record(rec, args.src_domain, args.dst_domain, suffix_map)
if p:
desired[key_ht(p, args.dst_domain)] = p
if args.csv:
for row in load_csv_rows(args.csv):
p = payload_from_csv_row(row, args.dst_domain, suffix_map)
if p:
desired[key_ht(p, args.dst_domain)] = p
if not desired:
print("Nothing to do. No source records and no CSV rows.")
return
created, updated, skipped = upsert_into_target(
sess,
args.dst_domain,
list(desired.values()),
upsert=args.upsert,
dry_run=args.dry_run,
)
print(f"Done. Created: {created}, Updated: {updated}, Skipped: {skipped}")
if __name__ == "__main__":
main()