390 lines
13 KiB
Python
Executable File
390 lines
13 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
import ipaddress
|
|
import json
|
|
import logging
|
|
import os
|
|
import re
|
|
import socket
|
|
import ssl
|
|
import sys
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
def env_required(name):
|
|
value = os.environ.get(name, "").strip()
|
|
if not value:
|
|
sys.exit(f"ERROR: environment variable {name} is required")
|
|
return value
|
|
|
|
|
|
def env_bool(name, default):
|
|
value = os.environ.get(name, "").strip().lower()
|
|
if not value:
|
|
return default
|
|
if value in ("1", "true", "yes", "on"):
|
|
return True
|
|
if value in ("0", "false", "no", "off"):
|
|
return False
|
|
sys.exit(f"ERROR: environment variable {name} must be a boolean, got {value!r}")
|
|
|
|
|
|
def env_int(name, default):
|
|
value = os.environ.get(name, "").strip()
|
|
if not value:
|
|
return default
|
|
try:
|
|
return int(value)
|
|
except ValueError:
|
|
sys.exit(f"ERROR: environment variable {name} must be an integer, got {value!r}")
|
|
|
|
|
|
NETBOX_URL = env_required("NETBOX_URL")
|
|
NETBOX_TOKEN = env_required("NETBOX_TOKEN")
|
|
NETBOX_VERIFY_SSL = env_bool("NETBOX_VERIFY_SSL", True)
|
|
SUBNET = env_required("SUBNET")
|
|
|
|
MIKROTIK_HOST = env_required("MIKROTIK_HOST")
|
|
MIKROTIK_PORT = env_int("MIKROTIK_PORT", 8729)
|
|
MIKROTIK_USER = env_required("MIKROTIK_USER")
|
|
MIKROTIK_PASSWORD = env_required("MIKROTIK_PASSWORD")
|
|
MIKROTIK_VERIFY_SSL = env_bool("MIKROTIK_VERIFY_SSL", False)
|
|
|
|
DNS_TTL = os.environ.get("DNS_TTL", "").strip() or "5m"
|
|
MANAGE_ALL_STATIC = env_bool("MANAGE_ALL_STATIC", False)
|
|
DRY_RUN = env_bool("DRY_RUN", False)
|
|
TIMEOUT = env_int("TIMEOUT", 15)
|
|
|
|
LOG_FILE = os.environ.get("LOG_FILE", "").strip()
|
|
LOG_TO_CONSOLE = env_bool("LOG_TO_CONSOLE", True)
|
|
|
|
STATIC_PATH = "/ip/dns/static"
|
|
TTL_UNITS = {"w": 604800, "d": 86400, "h": 3600, "m": 60, "s": 1}
|
|
|
|
log = logging.getLogger("netbox-dns-sync")
|
|
|
|
|
|
class RouterOSError(Exception):
|
|
pass
|
|
|
|
|
|
class RouterOSAPI:
|
|
def __init__(self, host, port, user, password, verify, timeout):
|
|
ctx = ssl.create_default_context()
|
|
if not verify:
|
|
ctx.check_hostname = False
|
|
ctx.verify_mode = ssl.CERT_NONE
|
|
raw = socket.create_connection((host, port), timeout=timeout)
|
|
self.sock = ctx.wrap_socket(raw, server_hostname=host)
|
|
self.talk("/login", {"name": user, "password": password})
|
|
|
|
def close(self):
|
|
try:
|
|
self.sock.close()
|
|
except OSError:
|
|
pass
|
|
|
|
@staticmethod
|
|
def encode_length(n):
|
|
if n < 0x80:
|
|
return bytes([n])
|
|
if n < 0x4000:
|
|
return (n | 0x8000).to_bytes(2, "big")
|
|
if n < 0x200000:
|
|
return (n | 0xC00000).to_bytes(3, "big")
|
|
if n < 0x10000000:
|
|
return (n | 0xE0000000).to_bytes(4, "big")
|
|
return b"\xF0" + n.to_bytes(4, "big")
|
|
|
|
def recv_exact(self, n):
|
|
buf = b""
|
|
while len(buf) < n:
|
|
chunk = self.sock.recv(n - len(buf))
|
|
if not chunk:
|
|
raise RouterOSError("Connection closed by router")
|
|
buf += chunk
|
|
return buf
|
|
|
|
def read_length(self):
|
|
b = self.recv_exact(1)[0]
|
|
if b < 0x80:
|
|
return b
|
|
if b < 0xC0:
|
|
return ((b & 0x3F) << 8) | self.recv_exact(1)[0]
|
|
if b < 0xE0:
|
|
return ((b & 0x1F) << 16) | int.from_bytes(self.recv_exact(2), "big")
|
|
if b < 0xF0:
|
|
return ((b & 0x0F) << 24) | int.from_bytes(self.recv_exact(3), "big")
|
|
return int.from_bytes(self.recv_exact(4), "big")
|
|
|
|
def write_sentence(self, words):
|
|
data = b""
|
|
for word in words:
|
|
raw = word.encode("utf-8")
|
|
data += self.encode_length(len(raw)) + raw
|
|
self.sock.sendall(data + b"\x00")
|
|
|
|
def read_sentence(self):
|
|
words = []
|
|
while True:
|
|
n = self.read_length()
|
|
if n == 0:
|
|
return words
|
|
words.append(self.recv_exact(n).decode("utf-8", errors="replace"))
|
|
|
|
@staticmethod
|
|
def parse_attrs(words):
|
|
attrs = {}
|
|
for word in words:
|
|
if word.startswith("="):
|
|
key, _, value = word[1:].partition("=")
|
|
attrs[key] = value
|
|
return attrs
|
|
|
|
def talk(self, command, params=None):
|
|
words = [command] + [f"={k}={v}" for k, v in (params or {}).items()]
|
|
self.write_sentence(words)
|
|
replies, done, error = [], {}, None
|
|
while True:
|
|
sentence = self.read_sentence()
|
|
if not sentence:
|
|
continue
|
|
reply, attrs = sentence[0], self.parse_attrs(sentence[1:])
|
|
if reply == "!re":
|
|
replies.append(attrs)
|
|
elif reply == "!trap":
|
|
error = attrs.get("message", "unknown error")
|
|
elif reply == "!fatal":
|
|
raise RouterOSError(" ".join(sentence[1:]) or "fatal error")
|
|
elif reply == "!done":
|
|
done = attrs
|
|
break
|
|
if error:
|
|
raise RouterOSError(f"{command}: {error}")
|
|
return replies, done
|
|
|
|
|
|
def setup_logging():
|
|
formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s", "%Y-%m-%d %H:%M:%S")
|
|
log.setLevel(logging.INFO)
|
|
if LOG_FILE:
|
|
file_handler = logging.FileHandler(LOG_FILE)
|
|
file_handler.setFormatter(formatter)
|
|
log.addHandler(file_handler)
|
|
if LOG_TO_CONSOLE:
|
|
console = logging.StreamHandler(sys.stdout)
|
|
console.setFormatter(formatter)
|
|
log.addHandler(console)
|
|
|
|
|
|
def netbox_records(network):
|
|
ctx = ssl.create_default_context()
|
|
if not NETBOX_VERIFY_SSL:
|
|
ctx.check_hostname = False
|
|
ctx.verify_mode = ssl.CERT_NONE
|
|
scheme = "Bearer" if NETBOX_TOKEN.startswith("nbt_") else "Token"
|
|
headers = {"Authorization": f"{scheme} {NETBOX_TOKEN}", "Accept": "application/json"}
|
|
query = urllib.parse.urlencode({"parent": str(network), "limit": 1000})
|
|
url = f"{NETBOX_URL.rstrip('/')}/api/ipam/ip-addresses/?{query}"
|
|
records = set()
|
|
total = skipped = 0
|
|
while url:
|
|
log.info(f"NetBox: GET {url}")
|
|
request = urllib.request.Request(url, headers=headers)
|
|
with urllib.request.urlopen(request, context=ctx, timeout=TIMEOUT) as response:
|
|
data = json.load(response)
|
|
for item in data.get("results", []):
|
|
total += 1
|
|
name = (item.get("dns_name") or "").strip().rstrip(".")
|
|
ip = ipaddress.ip_interface(item["address"]).ip
|
|
if not name or ip.version != 4 or ip not in network:
|
|
skipped += 1
|
|
continue
|
|
records.add((ip, name))
|
|
url = data.get("next")
|
|
log.info(f"NetBox: {total} IP addresses returned, {skipped} skipped (no DNS name or out of subnet), {len(records)} DNS records")
|
|
return sorted(records)
|
|
|
|
|
|
def ttl_seconds(value):
|
|
value = (value or "").strip()
|
|
if value.isdigit():
|
|
return int(value)
|
|
total = sum(int(n) * TTL_UNITS[u] for n, u in re.findall(r"(\d+)([wdhms])", value))
|
|
clock = re.search(r"(\d+):(\d+):(\d+)", value)
|
|
if clock:
|
|
h, m, s = map(int, clock.groups())
|
|
total += h * 3600 + m * 60 + s
|
|
return total
|
|
|
|
|
|
def record_ip(rec):
|
|
try:
|
|
return ipaddress.ip_address(rec.get("address", ""))
|
|
except ValueError:
|
|
return None
|
|
|
|
|
|
def record_type(rec):
|
|
return rec.get("type", "A")
|
|
|
|
|
|
def describe(rec):
|
|
return f"{rec.get('address', '')} {rec.get('name', '')} [{rec.get('.id', '')}]"
|
|
|
|
|
|
def is_managed(rec, network):
|
|
if rec.get("dynamic") == "true" or not rec.get("name"):
|
|
return False
|
|
if MANAGE_ALL_STATIC:
|
|
return True
|
|
ip = record_ip(rec)
|
|
return record_type(rec) == "A" and ip is not None and ip.version == 4 and ip in network
|
|
|
|
|
|
def plan_changes(current, desired):
|
|
pool = list(current)
|
|
target_ttl = ttl_seconds(DNS_TTL)
|
|
updates, adds = [], []
|
|
unchanged = 0
|
|
|
|
def take(predicate):
|
|
for rec in pool:
|
|
if record_type(rec) == "A" and predicate(rec):
|
|
pool.remove(rec)
|
|
return rec
|
|
return None
|
|
|
|
def update(rec, changes):
|
|
if ttl_seconds(rec.get("ttl", "")) != target_ttl:
|
|
changes["ttl"] = DNS_TTL
|
|
if changes:
|
|
updates.append((rec, changes))
|
|
return False
|
|
return True
|
|
|
|
pending = []
|
|
for ip, name in desired:
|
|
rec = take(lambda r: record_ip(r) == ip and r.get("name") == name)
|
|
if rec:
|
|
unchanged += update(rec, {})
|
|
else:
|
|
pending.append((ip, name))
|
|
|
|
remaining = []
|
|
for ip, name in pending:
|
|
rec = take(lambda r: record_ip(r) == ip)
|
|
if rec:
|
|
update(rec, {"name": name})
|
|
else:
|
|
remaining.append((ip, name))
|
|
|
|
for ip, name in remaining:
|
|
rec = take(lambda r: r.get("name") == name)
|
|
if rec:
|
|
update(rec, {"address": str(ip)})
|
|
else:
|
|
adds.append((ip, name))
|
|
|
|
log.info(f"Plan: {unchanged} unchanged, {len(adds)} to add, {len(updates)} to update, {len(pool)} to remove")
|
|
return pool, updates, adds
|
|
|
|
|
|
def apply_changes(api, removes, updates, adds):
|
|
prefix = "DRY RUN " if DRY_RUN else ""
|
|
for rec in removes:
|
|
log.info(f"{prefix}REMOVE {describe(rec)}")
|
|
if not DRY_RUN:
|
|
api.talk(f"{STATIC_PATH}/remove", {".id": rec[".id"]})
|
|
for rec, changes in updates:
|
|
detail = ", ".join(f"{k}: {rec.get(k, '')} -> {v}" for k, v in changes.items())
|
|
log.info(f"{prefix}UPDATE {describe(rec)} ({detail})")
|
|
if not DRY_RUN:
|
|
api.talk(f"{STATIC_PATH}/set", {".id": rec[".id"], **changes})
|
|
for ip, name in adds:
|
|
if DRY_RUN:
|
|
log.info(f"{prefix}ADD {ip} {name} ttl={DNS_TTL}")
|
|
continue
|
|
_, done = api.talk(f"{STATIC_PATH}/add", {"name": name, "address": str(ip), "ttl": DNS_TTL, "type": "A"})
|
|
log.info(f"ADD {ip} {name} ttl={DNS_TTL} [{done.get('ret', '?')}]")
|
|
|
|
|
|
def reorder(api, network, desired):
|
|
prefix = "DRY RUN " if DRY_RUN else ""
|
|
records = api.talk(f"{STATIC_PATH}/print")[0]
|
|
order = [r[".id"] for r in records]
|
|
index, labels = {}, {}
|
|
for r in records:
|
|
labels[r[".id"]] = describe(r)
|
|
if is_managed(r, network) and record_type(r) == "A":
|
|
index.setdefault((record_ip(r), r.get("name")), r[".id"])
|
|
target = [index[key] for key in desired if key in index]
|
|
moves = 0
|
|
for i in range(len(target) - 2, -1, -1):
|
|
item, anchor = target[i], target[i + 1]
|
|
pos = order.index(anchor)
|
|
if pos > 0 and order[pos - 1] == item:
|
|
continue
|
|
log.info(f"{prefix}MOVE {labels[item]} before {labels[anchor]}")
|
|
if not DRY_RUN:
|
|
api.talk(f"{STATIC_PATH}/move", {"numbers": item, "destination": anchor})
|
|
order.remove(item)
|
|
order.insert(order.index(anchor), item)
|
|
moves += 1
|
|
if moves == 0:
|
|
log.info("Order: records already sorted by IP")
|
|
return moves
|
|
|
|
|
|
def main():
|
|
try:
|
|
setup_logging()
|
|
except OSError as exc:
|
|
print(f"ERROR: cannot open log file {LOG_FILE}: {exc}", file=sys.stderr)
|
|
return 1
|
|
|
|
network = ipaddress.ip_network(SUBNET, strict=False)
|
|
log.info(f"Sync started: NetBox {NETBOX_URL} -> MikroTik {MIKROTIK_HOST}:{MIKROTIK_PORT}, subnet {network}, ttl {DNS_TTL}, dry_run={DRY_RUN}, manage_all_static={MANAGE_ALL_STATIC}")
|
|
|
|
try:
|
|
desired = netbox_records(network)
|
|
except Exception as exc:
|
|
log.error(f"NetBox query failed: {exc}")
|
|
return 1
|
|
|
|
if not desired:
|
|
log.error("NetBox returned no DNS records, aborting to avoid wiping the CHR")
|
|
return 1
|
|
|
|
try:
|
|
log.info(f"MikroTik: connecting to {MIKROTIK_HOST}:{MIKROTIK_PORT} as {MIKROTIK_USER} (verify_ssl={MIKROTIK_VERIFY_SSL})")
|
|
api = RouterOSAPI(MIKROTIK_HOST, MIKROTIK_PORT, MIKROTIK_USER, MIKROTIK_PASSWORD, MIKROTIK_VERIFY_SSL, TIMEOUT)
|
|
log.info("MikroTik: login successful")
|
|
except (OSError, RouterOSError) as exc:
|
|
log.error(f"MikroTik connection failed: {exc}")
|
|
return 1
|
|
|
|
try:
|
|
all_static = api.talk(f"{STATIC_PATH}/print")[0]
|
|
current = [r for r in all_static if is_managed(r, network)]
|
|
log.info(f"MikroTik: {len(all_static)} static records, {len(current)} managed by this script")
|
|
removes, updates, adds = plan_changes(current, desired)
|
|
apply_changes(api, removes, updates, adds)
|
|
moves = reorder(api, network, desired)
|
|
suffix = " (dry run)" if DRY_RUN else ""
|
|
log.info(f"Sync finished: {len(adds)} added, {len(updates)} updated, {len(removes)} removed, {moves} moved{suffix}")
|
|
except (OSError, RouterOSError) as exc:
|
|
log.error(f"MikroTik sync failed: {exc}")
|
|
return 1
|
|
finally:
|
|
api.close()
|
|
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
sys.exit(main())
|
|
except Exception:
|
|
log.exception("Unexpected error")
|
|
sys.exit(1)
|