retiolum/scripts/generate-zone.py

56 lines
1.7 KiB
Python
Raw Normal View History

2020-08-12 16:51:30 +00:00
#!/usr/bin/env python3
import sys
import datetime
from collections import defaultdict
from typing import DefaultDict, Any
2020-08-12 17:09:24 +00:00
serial = datetime.datetime.now().strftime("%Y%M%d%H")
2020-08-12 16:51:30 +00:00
2020-08-12 17:09:24 +00:00
def zone_header(domain: str) -> str:
return f"""@ 3600 IN SOA {domain}. root.r. {serial} 7200 3600 86400 3600
2020-08-12 16:51:30 +00:00
@ 3600 IN NS ns1
ns1 IN A 10.243.29.174
2020-08-12 17:38:07 +00:00
ns2 IN AAAA 42:0:3c46:70c7:8526:2adf:7451:8bbb
2020-08-12 16:51:30 +00:00
"""
def main() -> None:
dns: DefaultDict[str, Any] = defaultdict(lambda: defaultdict(dict))
rdns = {}
hostsfile = sys.argv[1]
with open(hostsfile) as f:
for line in f:
columns = line.split(" ")
2020-08-27 20:36:49 +00:00
if not columns[1].startswith("4.") and not columns[1].startswith("6."):
rdns[columns[0]] = columns[1].strip()
2020-08-12 16:51:30 +00:00
for name in columns[1:]:
hostname, tld = name.strip().rsplit(".", 1)
ip = columns[0]
record = "AAAA" if ":" in ip else "A"
dns[tld][hostname][record] = columns[0]
for zone, hosts in dns.items():
with open(f"{zone}.zone", "w") as f:
2020-08-12 17:09:24 +00:00
f.write(zone_header(zone))
2020-08-12 16:51:30 +00:00
for name, record in hosts.items():
for rtype, ip in record.items():
f.write(f"{name} IN {rtype} {ip}\n")
with open("240.10.zone", "w") as f:
2020-08-12 17:09:24 +00:00
f.write(zone_header("240.10.in-addr.arpa"))
2020-08-12 16:51:30 +00:00
for ip, name in rdns.items():
if "." in ip and ip.startswith("10.2"):
f.write(f"{ip}. IN PTR {name}.\n")
with open("42.zone", "w") as f:
2020-08-12 17:09:24 +00:00
f.write(zone_header("2.4.ip6.arpa"))
2020-08-12 16:51:30 +00:00
for ip, name in rdns.items():
if ":" in ip and ip.startswith("42:"):
f.write(f"{ip}. IN PTR {name}.\n")
if __name__ == "__main__":
main()