feat: rebuild app with Qt UI, installer and safer switch sync

- Replace the Tkinter app with a PySide6 UI: sidebar navigation, central
  profile switcher, autosave, light/dark theme, background tasks with
  progress and cancel, toasts and a filterable activity log
- Split logic into netbox_sync.core (config, NetBox, VMware/Proxmox,
  VM import, switches) and netbox_sync.ui
- Replace the three-dialog import chain with a four-step import wizard;
  support the global VRF and match VMs per cluster
- Expose the previously unreachable VRF/prefix batch tool
- Switch sync: no silent LLDP config changes, TOFU host key checks,
  platform auto-detection, Comware name normalization, fixed AOS-S and
  Comware LLDP parsing, FQDN/management-IP cable matching, dry-run
  preview, interface types only set on create
- Add PyInstaller onedir spec, Inno Setup installer and build.ps1
- Add pytest suite with an in-memory NetBox fake
- Stop tracking the built exe

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-10-12 15:15:23 +02:00
1 parent e983791baa
commit 4878275f2a
50 files changed
+7960 -3186

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""UI-independent synchronization logic."""
+229
View File
@@ -0,0 +1,229 @@
"""Customer profiles, application settings and DPAPI-protected secrets."""
import base64
import ctypes
import json
import logging
import os
import sys
from pathlib import Path
from netbox_sync import CONFIG_DIR_NAME
SECRET_KEYS = ("password", "token_secret")
CONFIG_VERSION = 5
DEFAULT_SETTINGS = {
"theme": "system", # system | light | dark
"parallel_ssh": 4, # concurrent switch discoveries
"enable_lldp": False, # allow configuration changes on switches
"create_cables": True,
}
log = logging.getLogger(__name__)
def config_dir():
if sys.platform == "win32":
base = Path(os.environ.get("APPDATA", Path.home()))
else:
base = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
return base / CONFIG_DIR_NAME
def config_path():
return config_dir() / "config.json"
def log_dir():
return config_dir() / "logs"
def known_hosts_path():
return config_dir() / "known_hosts"
# --------------------------------------------------------------------------
# Windows DPAPI
# --------------------------------------------------------------------------
if sys.platform == "win32":
from ctypes import wintypes
class _DataBlob(ctypes.Structure):
_fields_ = [("cbData", wintypes.DWORD), ("pbData", ctypes.POINTER(ctypes.c_byte))]
def _blob(data):
buffer = ctypes.create_string_buffer(data, len(data))
return _DataBlob(len(data), ctypes.cast(buffer, ctypes.POINTER(ctypes.c_byte))), buffer
class SecretError(RuntimeError):
"""A stored secret cannot be decrypted by the current Windows user."""
def protect(value):
"""Encrypt a value for the current Windows user with DPAPI."""
if not value:
return ""
if sys.platform != "win32":
raise RuntimeError("Verschlüsselte Profile werden derzeit nur unter Windows unterstützt.")
source, _buffer = _blob(value.encode("utf-8"))
result = _DataBlob()
if not ctypes.windll.crypt32.CryptProtectData(
ctypes.byref(source), "NetBox VM Import", None, None, None, 0, ctypes.byref(result)
):
raise ctypes.WinError()
try:
return base64.b64encode(ctypes.string_at(result.pbData, result.cbData)).decode("ascii")
finally:
ctypes.windll.kernel32.LocalFree(result.pbData)
def unprotect(value):
"""Decrypt a DPAPI value for the current Windows user."""
if not value:
return ""
if sys.platform != "win32":
raise SecretError("DPAPI ist nur unter Windows verfügbar.")
source, _buffer = _blob(base64.b64decode(value))
result = _DataBlob()
if not ctypes.windll.crypt32.CryptUnprotectData(
ctypes.byref(source), None, None, None, None, 0, ctypes.byref(result)
):
raise SecretError("Gespeichertes Geheimnis kann mit diesem Windows-Konto nicht entschlüsselt werden.")
try:
return ctypes.string_at(result.pbData, result.cbData).decode("utf-8")
finally:
ctypes.windll.kernel32.LocalFree(result.pbData)
# --------------------------------------------------------------------------
# Profile store
# --------------------------------------------------------------------------
def empty_profile(name):
return {
"name": name,
"netbox_url": "",
"netbox_token": "",
"netbox_ignore_ssl": False,
"sources": [],
"switches": [],
}
class ProfileStore:
def __init__(self, path=None):
self.path = Path(path) if path else config_path()
self.decrypt_failures = []
def _decrypt(self, value, context):
try:
return unprotect(value)
except Exception as error: # noqa: BLE001 - a broken secret must not block the app
self.decrypt_failures.append(context)
log.warning("Secret für %s nicht lesbar: %s", context, error)
return ""
def _decrypt_record(self, record, context):
item = dict(record)
for key in SECRET_KEYS:
encrypted_key = f"{key}_encrypted"
if encrypted_key in item:
item[key] = self._decrypt(item.pop(encrypted_key), context)
return item
def load(self):
"""Return ``(profiles, active_profile, settings)``."""
self.decrypt_failures = []
settings = dict(DEFAULT_SETTINGS)
if not self.path.exists():
return {}, "", settings
with self.path.open("r", encoding="utf-8") as stream:
data = json.load(stream)
settings.update({key: value for key, value in data.get("settings", {}).items() if key in DEFAULT_SETTINGS})
profiles = {}
for record in data.get("profiles", []):
name = record.get("name", "").strip()
if not name:
continue
profile = empty_profile(name)
profile.update({
"netbox_url": record.get("netbox_url", ""),
"netbox_token": self._decrypt(record.get("netbox_token_encrypted", ""), f"{name}: NetBox-Token"),
"netbox_ignore_ssl": bool(record.get("netbox_ignore_ssl", record.get("ignore_ssl_errors", False))),
})
for source in record.get("sources", []):
profile["sources"].append(self._decrypt_record(source, f"{name}: {source.get('name', 'Quelle')}"))
for switch in record.get("switches", []):
profile["switches"].append(self._decrypt_record(switch, f"{name}: {switch.get('name', 'Switch')}"))
# Migration from v2: one VMware source embedded in each profile.
if not profile["sources"] and record.get("esxi_host"):
profile["sources"].append({
"id": "vmware-legacy",
"type": "vmware",
"name": "VMware",
"enabled": True,
"host": record.get("esxi_host", ""),
"username": record.get("esxi_user", ""),
"password": self._decrypt(record.get("esxi_password_encrypted", ""), f"{name}: VMware"),
"ignore_ssl": bool(record.get("ignore_ssl_errors", False)),
})
profiles[name] = profile
# Migration from the first plaintext single-profile format.
if not profiles and any(key in data for key in ("esxi_host", "netbox_url")):
profile = empty_profile("Standard")
profile.update({
"netbox_url": data.get("netbox_url", ""),
"netbox_token": data.get("netbox_token", ""),
"netbox_ignore_ssl": bool(data.get("ignore_ssl_errors", False)),
"sources": [{
"id": "vmware-legacy",
"type": "vmware",
"name": "VMware",
"enabled": True,
"host": data.get("esxi_host", ""),
"username": data.get("esxi_user", ""),
"password": data.get("esxi_password", ""),
"ignore_ssl": bool(data.get("ignore_ssl_errors", False)),
}],
})
profiles["Standard"] = profile
return profiles, data.get("active_profile", ""), settings
@staticmethod
def _encrypt_record(record):
item = {key: value for key, value in record.items() if key not in SECRET_KEYS and not key.startswith("_")}
for key in SECRET_KEYS:
if key in record:
item[f"{key}_encrypted"] = protect(record.get(key, ""))
return item
def save(self, profiles, active_profile, settings=None):
records = []
for name in sorted(profiles, key=str.casefold):
profile = profiles[name]
records.append({
"name": name,
"netbox_url": profile.get("netbox_url", ""),
"netbox_token_encrypted": protect(profile.get("netbox_token", "")),
"netbox_ignore_ssl": bool(profile.get("netbox_ignore_ssl", False)),
"sources": [self._encrypt_record(source) for source in profile.get("sources", [])],
"switches": [self._encrypt_record(switch) for switch in profile.get("switches", [])],
})
payload = {
"version": CONFIG_VERSION,
"active_profile": active_profile,
"settings": dict(settings or DEFAULT_SETTINGS),
"profiles": records,
}
self.path.parent.mkdir(parents=True, exist_ok=True)
temp_path = self.path.with_suffix(".tmp")
with temp_path.open("w", encoding="utf-8") as stream:
json.dump(payload, stream, indent=2, ensure_ascii=False)
temp_path.replace(self.path)
+128
View File
@@ -0,0 +1,128 @@
"""Small helpers around pynetbox that both sync engines share."""
import re
import pynetbox
import requests
import urllib3
class NetBoxError(RuntimeError):
pass
class _TimeoutSession(requests.Session):
"""pynetbox issues requests without a timeout; never hang the UI forever."""
def __init__(self, timeout):
super().__init__()
self.default_timeout = timeout
def request(self, method, url, **kwargs):
kwargs.setdefault("timeout", self.default_timeout)
return super().request(method, url, **kwargs)
def connect(url, token, ignore_ssl=False, timeout=60):
"""Create a pynetbox API object and verify that URL and token work."""
url = (url or "").strip().rstrip("/")
if not url or not token:
raise NetBoxError("Bitte NetBox-URL und API-Token im Bereich „Verbindungen“ eintragen.")
if not url.startswith(("http://", "https://")):
url = f"https://{url}"
nb = pynetbox.api(url, token=token)
session = _TimeoutSession(timeout)
session.verify = not ignore_ssl
if ignore_ssl:
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
nb.http_session = session
try:
status = nb.status()
except requests.exceptions.SSLError as error:
raise NetBoxError(
"TLS-Zertifikat von NetBox ist nicht vertrauenswürdig. "
"Bei selbstsignierten Zertifikaten „Zertifikatsprüfung deaktivieren“ aktivieren."
) from error
except requests.exceptions.ConnectionError as error:
raise NetBoxError(f"NetBox unter {url} ist nicht erreichbar.") from error
except pynetbox.RequestError as error:
if getattr(error.req, "status_code", None) in (401, 403):
raise NetBoxError("NetBox hat den API-Token abgelehnt (fehlende Berechtigung oder ungültig).") from error
raise NetBoxError(f"NetBox-Anfrage fehlgeschlagen: {error}") from error
nb.netbox_version = str(status.get("netbox-version", "") or nb.version or "")
return nb
def version_tuple(nb):
text = getattr(nb, "netbox_version", "") or getattr(nb, "version", "") or ""
numbers = re.findall(r"\d+", text)
return tuple(int(value) for value in numbers[:2]) or (0, 0)
def uses_mac_objects(nb):
"""NetBox 4.2 moved MAC addresses into their own model."""
return version_tuple(nb) >= (4, 2)
def related_id(record, attribute):
value = getattr(record, attribute, None)
if value is None:
return None
if isinstance(value, dict):
return value.get("id")
if isinstance(value, int):
return value
return getattr(value, "id", None)
def related_name(record, attribute):
value = getattr(record, attribute, None)
if value is None:
return ""
if isinstance(value, dict):
return value.get("name") or value.get("display") or ""
return getattr(value, "name", None) or getattr(value, "display", None) or ""
def choice_value(record, attribute):
value = getattr(record, attribute, None)
if value is None:
return None
if isinstance(value, dict):
return value.get("value")
return getattr(value, "value", value)
def normalize_mac(value):
if not value:
return None
compact = re.sub(r"[^0-9a-fA-F]", "", str(value)).upper()
if len(compact) != 12:
return None
return ":".join(compact[index:index + 2] for index in range(0, 12, 2))
def assign_mac(nb, interface, mac, object_type):
"""Attach a MAC address to an interface for old and new NetBox versions."""
mac = normalize_mac(mac)
if not mac:
return False
if not uses_mac_objects(nb):
current = normalize_mac(getattr(interface, "mac_address", None))
if current == mac:
return False
interface.update({"mac_address": mac})
return True
matches = list(nb.dcim.mac_addresses.filter(
mac_address=mac, assigned_object_type=object_type, assigned_object_id=interface.id,
))
record = matches[0] if matches else nb.dcim.mac_addresses.create({
"mac_address": mac,
"assigned_object_type": object_type,
"assigned_object_id": interface.id,
})
if related_id(interface, "primary_mac_address") != record.id:
interface.update({"primary_mac_address": record.id})
return True
return not matches
+903
View File
@@ -0,0 +1,903 @@
"""SSH discovery and NetBox synchronization for HPE and Aruba switches."""
import ipaddress
import re
import threading
import time
from pathlib import Path
import paramiko
from netbox_sync.core.netbox import assign_mac, related_id
PLATFORMS = {
"auto": "Automatisch erkennen",
"aruba_cx": "Aruba CX (AOS-CX)",
"aruba_aos": "ArubaOS-Switch / ProCurve",
"hpe_comware": "HPE Comware",
}
COMMANDS = {
"aruba_cx": ("no page", "show interface brief", "show lldp neighbor-info detail"),
"aruba_aos": ("no page", "show interfaces brief", "show lldp info remote-device detail"),
"hpe_comware": ("screen-length disable", "display interface brief", "display lldp neighbor-information verbose"),
}
IP_COMMANDS = {
"aruba_cx": ("show ip interface brief", "show ipv6 interface brief"),
"aruba_aos": ("show ip", "show ipv6"),
"hpe_comware": ("display ip interface brief", "display ipv6 interface brief"),
}
LLDP_CONTROL = {
"aruba_cx": {
"status": "show lldp configuration",
"disabled": r"LLDP Enabled\s*:\s*No",
"enable": ("configure terminal", "lldp", "end"),
},
"aruba_aos": {
"status": "show lldp config",
"disabled": r"LLDP (?:Enabled|Run)\s*:\s*(?:No|False)|LLDP operation.*disabled",
"enable": ("configure terminal", "lldp run", "exit"),
},
"hpe_comware": {
"status": "display lldp status",
"disabled": r"Global status of LLDP\s*:\s*Disable",
"enable": ("system-view", "lldp global enable", "return"),
},
}
ANSI_ESCAPE = re.compile(r"\x1b(?:\][^\x07]*(?:\x07|\x1b\\)|\[[0-?]*[ -/]*[@-~]|[@-_]|[=>])")
TERMINAL_CONTROL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
MAC_PATTERN = re.compile(r"(?i)\b(?:[0-9a-f]{2}[:-]){5}[0-9a-f]{2}\b|\b[0-9a-f]{4}(?:-[0-9a-f]{4}){2}\b")
# "host#", "host>", Comware "<host>" and Comware system-view "[host]".
CLI_PROMPT = re.compile(r"(?:^|\n)(?:[^\r\n]*[>#]|\s*\[[^\[\]\r\n]+\])[ \t]*(?:\n)?\Z")
COMWARE_PROMPT = re.compile(r"(?:^|\n)\s*[<\[][^<>\[\]\r\n]+[>\]][ \t]*\Z")
CLI_ERROR = re.compile(r"(?i)invalid input|unknown command|unrecognized command|% ?wrong parameter|incomplete command")
_HOSTKEY_LOCK = threading.Lock()
def _noop(*_args, **_kwargs):
return None
class HostKeyChangedError(RuntimeError):
pass
# --------------------------------------------------------------------------
# Interface names
# --------------------------------------------------------------------------
# Every spelling maps to one short token so that e.g. Comware "GE1/0/1",
# NetBox "GigabitEthernet1/0/1" and a Cisco neighbor "Gi1/0/1" compare equal.
_NAME_ALIASES = {
"ge": "ge", "gi": "ge", "gigabitethernet": "ge", "gigethernet": "ge",
"xge": "xge", "te": "xge", "tengigabitethernet": "xge", "tengige": "xge",
"wge": "wge", "twe": "wge", "twentyfivegige": "wge", "twentyfivegigabitethernet": "wge",
"fge": "fge", "fo": "fge", "fortygige": "fge", "fortygigabitethernet": "fge",
"hge": "hge", "hu": "hge", "hundredgige": "hge", "hundredgigabitethernet": "hge",
"fa": "fe", "fastethernet": "fe",
"mge": "mge", "mgigabitethernet": "mge",
"bagg": "bagg", "bridgeaggregation": "bagg",
"ragg": "ragg", "routeaggregation": "ragg",
"po": "po", "portchannel": "po",
"vlan": "vlan", "vl": "vlan", "vlaninterface": "vlan", "vlanif": "vlan",
"loop": "lo", "lo": "lo", "loopback": "lo",
"eth": "eth", "et": "eth", "ethernet": "eth",
}
_COMWARE_EXPANSION = {
"GE": "GigabitEthernet", "XGE": "Ten-GigabitEthernet", "FGE": "FortyGigE", "HGE": "HundredGigE",
"WGE": "Twenty-FiveGigE", "MGE": "M-GigabitEthernet", "BAGG": "Bridge-Aggregation",
"RAGG": "Route-Aggregation", "VLAN": "Vlan-interface", "LOOP": "LoopBack",
}
_NAME_SPLIT = re.compile(r"^([A-Za-z][A-Za-z\- ]*?)\s*(\d[\d/:.]*)$")
def interface_key(value):
"""Normalized comparison key for interface names across vendors."""
value = (value or "").strip()
match = _NAME_SPLIT.match(value)
if match:
prefix = re.sub(r"[\s\-_]", "", match.group(1)).casefold()
return _NAME_ALIASES.get(prefix, prefix) + match.group(2)
return re.sub(r"[\s\-_]", "", value).casefold()
def expand_comware_name(name):
match = _NAME_SPLIT.match(name)
if not match:
return name
full = _COMWARE_EXPANSION.get(match.group(1).upper())
return f"{full}{match.group(2)}" if full else name
def _interface_name(token):
token = token.strip(" |:")
return bool(re.match(
r"(?i)^(?:\d+(?:/\d+){0,3}|[A-Z]{1,2}\d{1,2}|"
r"(?:GE|XGE|HGE|FGE|WGE|MGE|FortyGigE|HundredGigE|Ten-GigabitEthernet|GigabitEthernet|M-GigabitEthernet)\S+|"
r"Bridge-Aggregation\d+|BAGG\d+|RAGG\d+|Trk\d+|lag\d+|Vlan-interface\d+|vlan\s*\d+|Loop(?:Back)?\d+|"
r"loopback\s*\d*|lo\d+|mgmt)$",
token,
))
# --------------------------------------------------------------------------
# SSH session handling
# --------------------------------------------------------------------------
def clean_output(value):
value = ANSI_ESCAPE.sub("", value).replace("\r", "")
value = TERMINAL_CONTROL.sub("", value)
return re.sub(r"--\s*MORE\s*--|Press any key to continue.*", "", value, flags=re.I)
def _read_available(channel, timeout=20, initialize_session=False):
chunks = []
started = time.monotonic()
next_nudge = started + 0.5
nudges = 0
while time.monotonic() - started < timeout:
if channel.recv_ready():
chunks.append(channel.recv(65535).decode("utf-8", errors="replace"))
# The command is complete when the device prompt returns. This
# avoids truncating output at a short pause and fixed delays.
if CLI_PROMPT.search(clean_output("".join(chunks))):
break
now = time.monotonic()
if initialize_session and nudges < 3 and now >= next_nudge:
# ArubaOS-S may stop at the login banner until a key is pressed.
channel.send("\r")
nudges += 1
next_nudge = now + 1.5
time.sleep(0.05)
output = clean_output("".join(chunks))
if not CLI_PROMPT.search(output):
tail = " | ".join(line.strip() for line in output.splitlines()[-3:] if line.strip())
detail = f" Letzte Ausgabe: {tail[-300:]}" if tail else " Keine Ausgabe vom Switch empfangen."
raise TimeoutError("Der Switch hat die CLI-Ausgabe nicht mit einem vollständigen Prompt abgeschlossen." + detail)
return output
def _run_cli_command(channel, command, timeout=20):
channel.send(command + "\n")
try:
return _read_available(channel, timeout=timeout)
except TimeoutError as error:
raise TimeoutError(f"CLI-Befehl nicht vollständig abgeschlossen: {command}. {error}") from error
class _TrustOnFirstUse(paramiko.MissingHostKeyPolicy):
"""Remember unknown host keys; paramiko rejects changed keys afterwards."""
def __init__(self, path, log):
self.path = Path(path)
self.log = log
def missing_host_key(self, client, hostname, key):
with _HOSTKEY_LOCK:
keys = paramiko.HostKeys()
if self.path.exists():
keys.load(str(self.path))
keys.add(hostname, key.get_name(), key)
self.path.parent.mkdir(parents=True, exist_ok=True)
keys.save(str(self.path))
fingerprint = key.fingerprint if hasattr(key, "fingerprint") else key.get_base64()[:24]
self.log(f"{hostname}: neuer SSH-Hostschlüssel gespeichert ({key.get_name()} {fingerprint})")
def _host_entry(host, port):
return host if int(port) == 22 else f"[{host}]:{port}"
def forget_host_key(known_hosts, host, port=22):
path = Path(known_hosts)
if not path.exists():
return False
with _HOSTKEY_LOCK:
keys = paramiko.HostKeys(str(path))
entry = _host_entry(host, port)
if entry not in keys:
return False
del keys[entry]
keys.save(str(path))
return True
def _open_client(config, known_hosts, log):
client = paramiko.SSHClient()
if known_hosts:
if Path(known_hosts).exists():
with _HOSTKEY_LOCK:
client.load_host_keys(str(known_hosts))
client.set_missing_host_key_policy(_TrustOnFirstUse(known_hosts, log))
else:
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(
hostname=config["host"],
port=int(config.get("port", 22)),
username=config["username"],
password=config["password"],
look_for_keys=False,
allow_agent=False,
timeout=12,
auth_timeout=12,
banner_timeout=12,
)
except paramiko.BadHostKeyException as error:
client.close()
raise HostKeyChangedError(
f"Der SSH-Hostschlüssel von {config['host']} hat sich geändert! Mögliche Ursache: Austausch des "
"Geräts – oder ein Angriff. Falls der Wechsel erwartet ist, im Switch-Dialog "
"„Gespeicherten Hostschlüssel vergessen“ wählen."
) from error
except paramiko.AuthenticationException as error:
client.close()
raise PermissionError("SSH-Anmeldung abgelehnt – Benutzername oder Passwort prüfen.") from error
except Exception:
client.close()
raise
return client
def detect_platform(channel, banner):
"""Identify the switch OS from prompt and ``show version`` output."""
if COMWARE_PROMPT.search(banner):
return "hpe_comware"
_run_cli_command(channel, "no page")
version = _run_cli_command(channel, "show version", timeout=30)
if re.search(r"(?i)ArubaOS-CX|AOS-CX|\b[A-Z]{2}\.10\.\d+", version):
return "aruba_cx"
if re.search(r"(?i)Image stamp|ProCurve|\b[A-Z]{1,2}\.1[456]\.\d+", version):
return "aruba_aos"
display = _run_cli_command(channel, "display version", timeout=30)
if re.search(r"(?i)Comware", display):
return "hpe_comware"
raise RuntimeError("Plattform konnte nicht automatisch erkannt werden – bitte im Switch-Dialog manuell wählen.")
def run_switch_commands(config, enable_lldp=False, known_hosts=None, log=_noop):
platform = config.get("platform", "auto")
if platform not in PLATFORMS:
raise ValueError(f"Nicht unterstützte Switch-Plattform: {platform}")
client = _open_client(config, known_hosts, log)
try:
channel = client.invoke_shell(width=240, height=1000)
try:
banner = _read_available(channel, timeout=45, initialize_session=True)
except TimeoutError as error:
raise TimeoutError(f"SSH-Anmeldung nicht mit einem vollständigen CLI-Prompt abgeschlossen. {error}") from error
if platform == "auto":
platform = detect_platform(channel, banner)
log(f"{config.get('name', config['host'])}: Plattform erkannt – {PLATFORMS[platform]}")
pager_command, interface_command, neighbor_command = COMMANDS[platform]
_run_cli_command(channel, pager_command)
control = LLDP_CONTROL[platform]
lldp_status = _run_cli_command(channel, control["status"])
lldp_disabled = bool(re.search(control["disabled"], lldp_status, flags=re.I))
lldp_enabled_automatically = False
if lldp_disabled and enable_lldp:
enable_output = [_run_cli_command(channel, command) for command in control["enable"]]
combined = "\n".join(enable_output)
if platform == "hpe_comware" and CLI_ERROR.search(combined):
_run_cli_command(channel, "system-view")
combined = _run_cli_command(channel, "lldp enable")
combined += "\n" + _run_cli_command(channel, "return")
if re.search(r"(?i)permission denied|authorization failed|access denied", combined):
raise PermissionError("LLDP konnte mangels Konfigurationsrechten nicht aktiviert werden.")
if CLI_ERROR.search(combined):
raise RuntimeError("Der LLDP-Aktivierungsbefehl wird von diesem Switch nicht unterstützt.")
lldp_enabled_automatically = True
time.sleep(2)
interfaces = _run_cli_command(channel, interface_command, timeout=45)
ip_outputs = [_run_cli_command(channel, command, timeout=35) for command in IP_COMMANDS[platform]]
neighbors = _run_cli_command(channel, neighbor_command, timeout=60)
if platform == "aruba_cx" and CLI_ERROR.search(neighbors):
neighbors = _run_cli_command(channel, "show lldp neighbor-info", timeout=60)
cdp_neighbors = ""
if platform == "aruba_cx":
cdp_summary = _run_cli_command(channel, "show cdp neighbor-info", timeout=35)
cdp_ports = []
for line in cdp_summary.splitlines():
match = re.match(r"^\s*(\d+/\d+/\d+)\s+\S+", line)
if match and match.group(1) not in cdp_ports:
cdp_ports.append(match.group(1))
details = [_run_cli_command(channel, f"show cdp neighbor-info {port}", timeout=30) for port in cdp_ports]
cdp_neighbors = "\n".join([cdp_summary, *details])
return {
"platform": platform,
"interfaces": interfaces,
"ipv4_interfaces": ip_outputs[0],
"ipv6_interfaces": ip_outputs[1],
"neighbors": neighbors,
"cdp_neighbors": cdp_neighbors,
"lldp_status": lldp_status,
"lldp_disabled": lldp_disabled and not lldp_enabled_automatically,
"lldp_enabled_automatically": lldp_enabled_automatically,
}
finally:
client.close()
# --------------------------------------------------------------------------
# Parsers
# --------------------------------------------------------------------------
def speed_mbps(text):
gig = re.search(r"(?i)\b(\d+(?:\.\d+)?)\s*Gig", text)
if gig:
return int(float(gig.group(1)) * 1000)
matches = re.findall(r"(?i)\b(\d+(?:\.\d+)?)\s*(T|G|M)(?:b(?:it)?|bps)?(?:T|X|SR|LR|CR)?\b", text)
if not matches:
duplex = re.search(r"(?i)\b(\d+)(?:FDx|HDx)\b", text)
if duplex:
return int(duplex.group(1))
trailing = re.search(r"\b(\d{2,6})\s*$", text)
return int(trailing.group(1)) if trailing else None
value, unit = matches[-1]
return int(float(value) * {"M": 1, "G": 1000, "T": 1_000_000}[unit.upper()])
def _interface(name, **values):
record = {
"name": name, "enabled": True, "connected": False, "speed_mbps": None, "media": "",
"mac_address": None, "description": "", "neighbor": None, "ip_addresses": [], "virtual": False,
}
record.update(values)
return record
def _parse_aos_interfaces(output):
"""ArubaOS-S: ``Port Type | Alert Enabled Status Mode ...``."""
interfaces = []
seen = set()
for raw_line in clean_output(output).splitlines():
if "|" not in raw_line:
continue
left, right = raw_line.split("|", 1)
left_tokens = left.split()
right_tokens = right.split()
if not left_tokens or not _interface_name(left_tokens[0]) or len(right_tokens) < 3:
continue
name = left_tokens[0]
if name in seen:
continue
enabled_value, status_value = right_tokens[1].lower(), right_tokens[2].lower()
if enabled_value not in ("yes", "no") or status_value not in ("up", "down"):
continue
mode = right_tokens[3] if len(right_tokens) > 3 else ""
interfaces.append(_interface(
name,
enabled=enabled_value == "yes",
connected=status_value == "up",
speed_mbps=speed_mbps(mode) if status_value == "up" else None,
media=left_tokens[1] if len(left_tokens) > 1 else "",
))
seen.add(name)
return interfaces
def parse_interfaces(output, platform):
if platform == "aruba_aos":
return _parse_aos_interfaces(output)
interfaces = []
seen = set()
for raw_line in clean_output(output).splitlines():
line = raw_line.strip()
if not line or set(line) <= {"-", "=", " "}:
continue
tokens = re.split(r"\s+", line)
name_index = next((index for index, token in enumerate(tokens[:3]) if _interface_name(token)), None)
if name_index is None:
continue
name = tokens[name_index].strip(" |:")
if platform == "hpe_comware":
name = expand_comware_name(name)
if name in seen:
continue
lower = line.lower()
if not re.search(r"\b(up|down|adm|administratively down|disabled|enabled)\b", lower):
continue
enabled = not re.search(r"administratively down|admin.*down|\badm\b|disabled|\bno\s+(?:up|down)\b", lower)
connected = bool(re.search(r"\bup\b", lower)) and not re.search(r"\bdown\b", lower)
mac_match = MAC_PATTERN.search(line)
media = tokens[name_index + 3] if platform == "aruba_cx" and len(tokens) > name_index + 3 else ""
interfaces.append(_interface(
name,
enabled=bool(enabled),
connected=connected,
speed_mbps=speed_mbps(line),
media=media,
mac_address=mac_match.group(0) if mac_match else None,
))
seen.add(name)
return interfaces
def _address_with_mask(address, mask=None):
try:
if "/" in address:
return str(ipaddress.ip_interface(address))
if mask:
return str(ipaddress.ip_interface(f"{address}/{mask}"))
except ValueError:
return None
return None
def parse_interface_ips(ipv4_output, ipv6_output, platform):
entries = []
if platform == "aruba_aos":
current_interface = ""
for line in clean_output(ipv4_output).splitlines():
if "|" not in line:
continue
interface_column, values = line.split("|", 1)
candidate = interface_column.strip()
if candidate and not re.search(r"(?i)^VLAN$", candidate) and not set(candidate) <= {"-", "+", " "}:
current_interface = candidate
addresses = re.findall(r"\b\d{1,3}(?:\.\d{1,3}){3}\b", values)
if current_interface and len(addresses) >= 2:
address = _address_with_mask(addresses[0], addresses[1])
if address and not address.startswith("0.0.0.0/"):
entries.append({"interface": current_interface, "address": address})
current_interface = ""
for line in clean_output(ipv6_output).splitlines():
vlan_match = re.match(r"^\s*Vlan Name\s*:\s*(.+)$", line, flags=re.I)
if vlan_match:
current_interface = vlan_match.group(1).strip()
address_match = re.search(r"([0-9a-fA-F:]+/\d{1,3})", line)
if address_match and current_interface:
address = _address_with_mask(address_match.group(1))
if address and not address.lower().startswith("fe80:"):
entries.append({"interface": current_interface, "address": address})
else:
for output, version in ((ipv4_output, 4), (ipv6_output, 6)):
pattern = r"\b(\d+(?:\.\d+){3}/\d{1,2})\b" if version == 4 else r"\b([0-9a-fA-F]*:[0-9a-fA-F:]+/\d{1,3})\b"
for line in clean_output(output).splitlines():
tokens = re.split(r"\s+", line.strip())
if len(tokens) < 2 or not _interface_name(tokens[0]):
continue
match = re.search(pattern, line)
if not match:
continue
address = _address_with_mask(match.group(1))
if not address or address.startswith("0.0.0.0/") or address.lower().startswith("fe80:"):
continue
name = expand_comware_name(tokens[0]) if platform == "hpe_comware" else tokens[0]
entries.append({"interface": name, "address": address})
unique = {}
for entry in entries:
unique[(interface_key(entry["interface"]), entry["address"])] = entry
return list(unique.values())
def _field(block, patterns):
for pattern in patterns:
match = re.search(pattern, block, flags=re.I | re.M)
if match:
return match.group(1).strip()
return ""
def parse_neighbors(output):
clean = clean_output(output)
# "Port : 1/1/1" (CX) starts a record, but "Port ID : …" or
# "Port description : …" inside a Comware record must not.
starts = list(re.finditer(
r"(?im)^\s*(?:Port\s*:|Local (?:Port|Interface|Intf)\s*[: ]|LLDP neighbor-information of port\s).*$",
clean,
))
if not starts:
return _parse_neighbor_table(clean)
neighbors = []
for index, start in enumerate(starts):
end = starts[index + 1].start() if index + 1 < len(starts) else len(clean)
block = clean[start.start():end]
local_port = _field(block, (
r"^\s*Port\s*:\s*(\S+)",
r"^\s*Local (?:Port|Interface|Intf)\s*[: ]\s*(\S+)",
r"^\s*LLDP neighbor-information of port\s+(?:\d+\[)?([^\]\s:]+)\]?",
))
system_name = _field(block, (
r"^\s*Neighbor Chassis-Name\s*:\s*(.+)$",
r"^[ \t]*Neighbor System-Name[ \t]*:[ \t]*(.*)$",
r"^[ \t]*(?:System Name|SysName)[ \t]*:[ \t]*(.*)$",
r"^\s*Neighbor name\s*[: ]\s*(.+)$",
))
if not system_name:
system_name = _field(block, (r"^[ \t]*Neighbor Chassis-ID[ \t]*:[ \t]*(.+)$", r"^[ \t]*ChassisId[ \t]*:[ \t]*(.+)$"))
remote_port = _field(block, (
r"^\s*Neighbor Port-ID\s*:\s*(.+)$",
r"^[ \t]*(?:Port ID|PortId)[ \t]*:[ \t]*(.*)$",
r"^\s*Port ID subtype.*\n\s*Port ID\s*[: ]\s*(.+)$",
r"^\s*Neighbor Port-Desc\s*:\s*(.+)$",
r"^\s*(?:Port Description|PortDesc|PortDescr)\s*[: ]\s*(.+)$",
))
port_description = _field(block, (
r"^\s*Neighbor Port-Desc\s*:\s*(.+)$",
r"^\s*(?:Port Description|PortDesc|PortDescr)\s*[: ]\s*(.+)$",
))
management_ip = _field(block, (
r"^\s*Neighbor Management-Address\s*:\s*([0-9a-fA-F:.]+)",
r"^\s*(?:Management Address|Management address|Management IP)\s*[: ]\s*([0-9a-fA-F:.]+)",
r"^[ \t]*Address[ \t]*:[ \t]*([0-9a-fA-F:.]+)[ \t]*$",
))
if local_port and (system_name or remote_port):
neighbors.append({
"local_port": local_port,
"system_name": system_name,
"remote_port": remote_port,
"port_description": port_description,
"management_ip": management_ip,
"protocol": "LLDP",
})
return neighbors
def parse_cdp_neighbors(output):
"""Parse detailed AOS-CX CDP records into the common neighbor shape."""
clean = clean_output(output)
starts = list(re.finditer(r"(?im)^\s*Local Port\s*:\s*\S+", clean))
neighbors = []
for index, start in enumerate(starts):
end = starts[index + 1].start() if index + 1 < len(starts) else len(clean)
block = clean[start.start():end]
local_port = _field(block, (r"^\s*Local Port\s*:\s*(\S+)",))
system_name = _field(block, (r"^\s*Device ID\s*:\s*(.+)$", r"^\s*System Name\s*:\s*(.+)$"))
remote_port = _field(block, (r"^\s*Neighbor Port-ID\s*:\s*(.+)$", r"^\s*Port ID\s*:\s*(.+)$"))
management_ip = _field(block, (r"^\s*Address\s*:\s*([0-9a-fA-F:.]+)", r"^\s*Management Address\s*:\s*([0-9a-fA-F:.]+)"))
if local_port and (system_name or remote_port or management_ip):
neighbors.append({
"local_port": local_port,
"system_name": system_name,
"remote_port": remote_port,
"port_description": "",
"management_ip": management_ip,
"protocol": "CDP",
})
return neighbors
def _parse_neighbor_table(output):
neighbors = []
for raw_line in output.splitlines():
line = raw_line.strip()
if not line or set(line) <= {"-", "=", " "}:
continue
tokens = re.split(r"\s+", line.replace("|", " | "))
if not tokens or not _interface_name(tokens[0]):
continue
if "|" in tokens:
remaining = tokens[tokens.index("|") + 1:]
if len(remaining) < 3:
continue
remote_port, system_name = remaining[1], remaining[-1]
else:
if len(tokens) < 5:
continue
remote_port, system_name = tokens[2], tokens[-1]
neighbors.append({
"local_port": tokens[0], "system_name": system_name, "remote_port": remote_port,
"port_description": "", "management_ip": "", "protocol": "LLDP",
})
return neighbors
def build_snapshot(outputs, platform):
interfaces = parse_interfaces(outputs["interfaces"], platform)
interface_ips = parse_interface_ips(outputs.get("ipv4_interfaces", ""), outputs.get("ipv6_interfaces", ""), platform)
lldp_neighbors = parse_neighbors(outputs["neighbors"])
cdp_neighbors = parse_cdp_neighbors(outputs.get("cdp_neighbors", ""))
# LLDP normally contains richer data. CDP fills ports for which CX did not
# return an LLDP record, without duplicating a physical local interface.
neighbors = list(lldp_neighbors)
occupied = {interface_key(item["local_port"]) for item in neighbors}
for neighbor in cdp_neighbors:
key = interface_key(neighbor["local_port"])
if key not in occupied:
neighbors.append(neighbor)
occupied.add(key)
interface_map = {interface_key(interface["name"]): interface for interface in interfaces}
for item in interface_ips:
key = interface_key(item["interface"])
interface = interface_map.get(key)
if not interface:
interface = _interface(item["interface"], connected=True, description="Logisches Layer-3-Interface", virtual=True)
interfaces.append(interface)
interface_map[key] = interface
interface["ip_addresses"].append(item["address"])
for neighbor in neighbors:
local = interface_map.get(interface_key(neighbor["local_port"]))
if local:
local["neighbor"] = neighbor
return {
"platform": platform,
"interfaces": interfaces,
"ip_addresses": interface_ips,
"neighbors": neighbors,
"lldp_neighbors": lldp_neighbors,
"cdp_neighbors": cdp_neighbors,
"raw": outputs,
"lldp_disabled": outputs.get("lldp_disabled", False),
"lldp_enabled_automatically": outputs.get("lldp_enabled_automatically", False),
"discovered_at": time.time(),
}
def discover_switch(config, enable_lldp=False, known_hosts=None, log=_noop):
outputs = run_switch_commands(config, enable_lldp=enable_lldp, known_hosts=known_hosts, log=log)
return build_snapshot(outputs, outputs["platform"])
# --------------------------------------------------------------------------
# Platform suggestion from NetBox data
# --------------------------------------------------------------------------
def suggest_platform(*texts):
"""Guess the switch OS from NetBox platform, manufacturer and model names."""
text = " ".join(str(value or "") for value in texts).casefold()
if not text.strip():
return "auto"
if re.search(r"comware|h3c|\b(?:19[0-9]0|51[234]0|55[01]0|57[01]0|59[0-9]0|75\d\d|10500|12500|12900)\b", text):
return "hpe_comware"
if re.search(r"aos-?cx|arubaos-?cx|\bcx\b|\b(?:4100i|6000|6100|6200[fm]?|6300[fm]?|6400|8100|8320|8325|8360|8400|9300|10000)\b", text):
return "aruba_cx"
if re.search(r"procurve|aos-?s\b|arubaos-?switch|provision|\b(?:2530|2540|2620|2920|2930[fm]?|3800|3810m?|5400r?l?|5406|5412)\b", text):
return "aruba_aos"
return "auto"
# --------------------------------------------------------------------------
# NetBox synchronization
# --------------------------------------------------------------------------
def netbox_interface_type(interface):
if interface.get("virtual"):
return "virtual"
key = interface_key(interface["name"])
if re.match(r"^(?:lag|trk|bagg|ragg|po)\d", key):
return "lag"
if re.match(r"^(?:vlan|lo)\d", key):
return "virtual"
media = (interface.get("media") or "").casefold()
if media and media != "--":
if "qsfp28" in media or "100g" in media:
return "100gbase-x-qsfp28"
if "qsfp" in media or "40g" in media:
return "40gbase-x-qsfpp"
if "sfp28" in media or "25g" in media:
return "25gbase-x-sfp28"
if "smartrate" in media or "2.5g" in media or "mgig" in media:
return "2.5gbase-t"
if re.search(r"10gbe?-?t\b|10gbaset", media):
return "10gbase-t"
if "sfp+" in media or "10g" in media:
return "10gbase-x-sfpp"
if "sfp" in media or "1000sx" in media or "1000lx" in media or "gbic" in media:
return "1000base-x-sfp"
if re.search(r"1000t|1gbt|1gbaset", media):
return "1000base-t"
if "100tx" in media or "100/" in media:
return "100base-tx"
prefix = re.match(r"^[a-z]+", key)
by_prefix = {"xge": "10gbase-x-sfpp", "wge": "25gbase-x-sfp28", "fge": "40gbase-x-qsfpp",
"hge": "100gbase-x-qsfp28", "ge": "1000base-t", "fe": "100base-tx", "mge": "1000base-t"}
if prefix and prefix.group(0) in by_prefix:
return by_prefix[prefix.group(0)]
speed = interface.get("speed_mbps")
if not speed:
return "other"
for threshold, value in ((100_000, "100gbase-x-qsfp28"), (40_000, "40gbase-x-qsfpp"),
(25_000, "25gbase-x-sfp28"), (10_000, "10gbase-x-sfpp"), (1000, "1000base-t")):
if speed >= threshold:
return value
return "100base-tx"
def _device_interfaces(nb, device_id):
records = {}
for record in nb.dcim.interfaces.filter(device_id=device_id):
key = interface_key(record.name)
# Prefer a template-created full name over a stray short duplicate.
if key not in records or len(record.name) > len(records[key].name):
records[key] = record
return records
class _RemoteLookup:
"""Find neighbor devices and interfaces in NetBox, cached per sync run."""
def __init__(self, nb):
self.nb = nb
self.devices = {}
self.interfaces = {}
def device(self, neighbor):
name = (neighbor.get("system_name") or "").strip()
cache_key = (name.casefold(), neighbor.get("management_ip"))
if cache_key in self.devices:
return self.devices[cache_key]
found = None
for candidate in dict.fromkeys(filter(None, (name, name.split(".")[0]))):
matches = list(self.nb.dcim.devices.filter(name__ie=candidate))
if len(matches) == 1:
found = matches[0]
break
if not found and neighbor.get("management_ip"):
for ip in self.nb.ipam.ip_addresses.filter(address=neighbor["management_ip"]):
if getattr(ip, "assigned_object_type", "") == "dcim.interface":
device_id = related_id(ip.assigned_object, "device")
if device_id:
found = self.nb.dcim.devices.get(device_id)
break
self.devices[cache_key] = found
return found
def interface(self, device, neighbor):
if device.id not in self.interfaces:
self.interfaces[device.id] = _device_interfaces(self.nb, device.id)
records = self.interfaces[device.id]
candidates = [neighbor.get("remote_port"), neighbor.get("port_description")]
if neighbor.get("port_description"):
candidates.append(neighbor["port_description"].split()[0])
for candidate in filter(None, candidates):
record = records.get(interface_key(candidate))
if record:
return record
return None
def _new_report():
return {
"interfaces_created": 0, "interfaces_updated": 0, "interfaces_unchanged": 0,
"ips_created": 0, "ips_updated": 0, "ips_unchanged": 0,
"cables_created": 0, "cables_skipped": 0,
"changes": [], "errors": [],
}
def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=False, log=_noop):
"""Write a discovery snapshot to NetBox.
With ``dry_run`` nothing is written; the returned report lists what would
change. Interface types are only set when an interface is created, so
device-type templates and manual corrections in NetBox are preserved.
"""
report = _new_report()
device_id = int(config["device_id"])
device = nb.dcim.devices.get(device_id)
if not device:
report["errors"].append(f"NetBox-Gerät #{device_id} existiert nicht mehr")
return report
tenant_id = related_id(device, "tenant")
existing = _device_interfaces(nb, device_id)
records = {}
for interface in snapshot["interfaces"]:
key = interface_key(interface["name"])
record = existing.get(key)
try:
if record:
changes = {}
if bool(getattr(record, "enabled", True)) != bool(interface.get("enabled", True)):
changes["enabled"] = bool(interface.get("enabled", True))
if changes:
report["interfaces_updated"] += 1
state = "aktivieren" if changes["enabled"] else "deaktivieren"
report["changes"].append(f"Interface {record.name}: {state}")
if not dry_run:
record.update(changes)
else:
report["interfaces_unchanged"] += 1
else:
payload = {
"device": device_id,
"name": interface["name"],
"type": netbox_interface_type(interface),
"enabled": bool(interface.get("enabled", True)),
}
if interface.get("description"):
payload["description"] = interface["description"][:200]
report["interfaces_created"] += 1
report["changes"].append(f"Interface {interface['name']} neu ({payload['type']})")
if not dry_run:
record = nb.dcim.interfaces.create(payload)
existing[key] = record
if record and not dry_run and interface.get("mac_address"):
assign_mac(nb, record, interface["mac_address"], "dcim.interface")
records[key] = record
except Exception as error: # noqa: BLE001
report["errors"].append(f"Interface {interface['name']}: {error}")
for interface in snapshot["interfaces"]:
key = interface_key(interface["name"])
if key not in records:
continue
record = records[key]
for address in interface.get("ip_addresses", []):
try:
host = str(ipaddress.ip_interface(address).ip)
candidates = [
item for item in nb.ipam.ip_addresses.filter(address=host)
if related_id(item, "vrf") is None
]
if len(candidates) > 1:
raise ValueError("mehrere globale IP-Adressen mit diesem Host gefunden")
payload = {"address": address, "status": "active", "assigned_object_type": "dcim.interface"}
if record:
payload["assigned_object_id"] = record.id
if tenant_id:
payload["tenant"] = tenant_id
if candidates:
current = candidates[0]
differs = (
str(current.address) != address
or getattr(current, "assigned_object_type", None) != "dcim.interface"
or getattr(current, "assigned_object_id", None) != payload.get("assigned_object_id")
or (tenant_id and related_id(current, "tenant") != tenant_id)
)
if differs:
report["ips_updated"] += 1
report["changes"].append(f"IP {address} → {interface['name']}")
if not dry_run:
current.update(payload)
else:
report["ips_unchanged"] += 1
else:
report["ips_created"] += 1
report["changes"].append(f"IP {address} neu auf {interface['name']}")
if not dry_run:
nb.ipam.ip_addresses.create(payload)
except Exception as error: # noqa: BLE001
report["errors"].append(f"IP-Adresse {address} auf {interface['name']}: {error}")
if create_cables:
lookup = _RemoteLookup(nb)
for neighbor in snapshot["neighbors"]:
label = f"{neighbor.get('local_port')} → {neighbor.get('system_name')} {neighbor.get('remote_port')}"
try:
key = interface_key(neighbor["local_port"])
if key not in records:
continue
local = records[key]
if local is not None and getattr(local, "cable", None):
report["cables_skipped"] += 1
continue
remote_device = lookup.device(neighbor)
if not remote_device:
report["cables_skipped"] += 1
continue
if remote_device.id == device_id:
continue
remote = lookup.interface(remote_device, neighbor)
if not remote or getattr(remote, "cable", None):
report["cables_skipped"] += 1
continue
report["cables_created"] += 1
report["changes"].append(f"Kabel {device.name} {label}")
if not dry_run:
nb.dcim.cables.create({
"a_terminations": [{"object_type": "dcim.interface", "object_id": local.id}],
"b_terminations": [{"object_type": "dcim.interface", "object_id": remote.id}],
"status": "connected",
})
remote.cable = True # avoid a second cable from the reverse direction
except Exception as error: # noqa: BLE001
report["errors"].append(f"Nachbar {label}: {error}")
return report
def describe_snapshot(snapshot):
return (
f"{len(snapshot['interfaces'])} Schnittstellen, {len(snapshot.get('ip_addresses', []))} IP-Adressen, "
f"{len(snapshot.get('lldp_neighbors', []))} LLDP- und {len(snapshot.get('cdp_neighbors', []))} CDP-Nachbarn"
)
+326
View File
@@ -0,0 +1,326 @@
"""Read virtual machines from VMware vSphere and Proxmox VE."""
import ipaddress
import re
import ssl
import requests
import urllib3
SOURCE_TYPES = {"vmware": "VMware vSphere", "proxmox": "Proxmox VE"}
def _noop(*_args, **_kwargs):
return None
# --------------------------------------------------------------------------
# IP helpers
# --------------------------------------------------------------------------
def valid_guest_ip(value):
try:
address = ipaddress.ip_interface(value).ip if "/" in value else ipaddress.ip_address(value)
return not (address.is_loopback or address.is_link_local or address.is_unspecified)
except ValueError:
return False
def ip_with_prefix(value):
"""Return ``address/prefix``; guess /24 or /64 if the hypervisor omits it."""
try:
if "/" in value:
return str(ipaddress.ip_interface(value))
address = ipaddress.ip_address(value)
return f"{address}/24" if address.version == 4 else f"{address}/64"
except ValueError:
return None
def source_endpoint(source):
return source.get("host") or source.get("url") or ""
# --------------------------------------------------------------------------
# VMware
# --------------------------------------------------------------------------
def load_vmware_source(source, log=_noop):
from pyVim.connect import Disconnect, SmartConnect
from pyVmomi import vim
log(f"Verbinde zu VMware: {source['name']} …")
context = ssl._create_unverified_context() if source.get("ignore_ssl") else None
service_instance = SmartConnect(
host=source["host"], user=source["username"], pwd=source["password"], sslContext=context
)
try:
content = service_instance.RetrieveContent()
view = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True)
try:
# Fetch every required VM property in one PropertyCollector call.
# Accessing properties on each ManagedObject separately is extremely
# slow on vCenter because every access may cause another SOAP request.
traversal = vim.PropertyCollector.TraversalSpec(
name="vmViewTraversal", type=vim.view.ContainerView, path="view", skip=False,
)
object_spec = vim.PropertyCollector.ObjectSpec(obj=view, skip=True, selectSet=[traversal])
property_spec = vim.PropertyCollector.PropertySpec(
type=vim.VirtualMachine, all=False, pathSet=[
"name", "config.hardware.memoryMB", "config.hardware.numCPU",
"config.hardware.device", "config.guestFullName", "config.template",
"runtime.powerState", "guest.net",
],
)
filter_spec = vim.PropertyCollector.FilterSpec(objectSet=[object_spec], propSet=[property_spec])
result = content.propertyCollector.RetrievePropertiesEx(
[filter_spec], vim.PropertyCollector.RetrieveOptions()
)
objects = list(result.objects or []) if result else []
while result and result.token:
result = content.propertyCollector.ContinueRetrievePropertiesEx(result.token)
objects.extend(result.objects or [])
normalized = []
for item in objects:
properties = {prop.name: prop.val for prop in (item.propSet or [])}
if properties.get("name") and not properties.get("config.template"):
normalized.append(_normalize_vmware_vm(properties, source, vim))
return normalized
finally:
view.Destroy()
finally:
Disconnect(service_instance)
def _normalize_vmware_vm(properties, source, vim):
disks = sum(
round(device.capacityInKB / 1024)
for device in properties.get("config.hardware.device", []) or []
if isinstance(device, vim.vm.device.VirtualDisk)
)
interfaces = []
for index, net in enumerate(properties.get("guest.net", []) or []):
mac = getattr(net, "macAddress", None)
if not mac:
continue
interfaces.append({
"name": getattr(net, "device", None) or f"NIC-{index}",
"mac": mac,
"ips": _vmware_guest_ips(net),
})
return {
"name": properties["name"],
"source": source["name"],
"source_type": "VMware",
"kind": "VM",
"status": "active" if "poweredOn" in str(properties.get("runtime.powerState", "")) else "offline",
"vcpus": int(properties.get("config.hardware.numCPU", 0) or 0),
"memory": int(properties.get("config.hardware.memoryMB", 0) or 0),
"disk": disks,
"guest_os": properties.get("config.guestFullName", "") or "",
"interfaces": interfaces,
}
def _vmware_guest_ips(net):
"""Prefer VMware-reported prefix lengths and retain legacy IP fallback."""
ips = []
ip_config = getattr(net, "ipConfig", None)
for entry in (getattr(ip_config, "ipAddress", None) or []):
value = getattr(entry, "ipAddress", None)
prefix = getattr(entry, "prefixLength", None)
if value and valid_guest_ip(value):
ips.append(f"{value}/{prefix}" if prefix is not None else value)
known = {str(ipaddress.ip_interface(value).ip if "/" in value else ipaddress.ip_address(value)) for value in ips}
for value in (getattr(net, "ipAddress", None) or []):
if not valid_guest_ip(value):
continue
normalized = str(ipaddress.ip_address(value))
if normalized not in known:
ips.append(value)
known.add(normalized)
return ips
# --------------------------------------------------------------------------
# Proxmox
# --------------------------------------------------------------------------
def _proxmox_session(source):
session = requests.Session()
session.verify = not source.get("ignore_ssl")
if source.get("ignore_ssl"):
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
session.headers["Authorization"] = f"PVEAPIToken={source['token_id']}={source['token_secret']}"
return session
def _proxmox_get(session, base_url, path):
response = session.get(f"{base_url}/api2/json{path}", timeout=30)
if response.status_code == 401:
raise PermissionError("Proxmox hat Token-ID oder Token-Secret abgelehnt.")
response.raise_for_status()
return response.json().get("data")
def load_proxmox_source(source, log=_noop):
log(f"Verbinde zu Proxmox: {source['name']} …")
session = _proxmox_session(source)
resources = _proxmox_get(session, source["url"], "/cluster/resources?type=vm") or []
log(f"{source['name']}: Cluster-API meldet {len(resources)} Ressourcen")
# Some restricted API tokens may not see the cluster-wide resource
# endpoint. Try the per-node endpoints as a compatible fallback.
if not resources:
resources = _proxmox_resources_by_node(session, source)
log(f"{source['name']}: Node-Abfrage meldet {len(resources)} Ressourcen")
result = []
for resource in resources:
kind = resource.get("type")
if kind not in ("qemu", "lxc") or _is_template(resource.get("template")):
continue
if kind == "lxc" and not source.get("include_lxc", True):
continue
try:
result.append(_normalize_proxmox_guest(session, source, resource))
except Exception as error: # noqa: BLE001 - one broken guest must not stop the source
log(f"{source['name']} / VMID {resource.get('vmid')}: {error}", "warning")
if not result:
raise RuntimeError(
"API erreichbar, aber keine sichtbaren VMs/LXCs gefunden. "
"Dem Benutzer und dem API-Token mindestens PVEAuditor auf /vms zuweisen."
)
return result
def _proxmox_resources_by_node(session, source):
resources = []
kinds = ["qemu"] + (["lxc"] if source.get("include_lxc", True) else [])
for node_data in _proxmox_get(session, source["url"], "/nodes") or []:
node = node_data.get("node")
if not node:
continue
for kind in kinds:
for guest in _proxmox_get(session, source["url"], f"/nodes/{node}/{kind}") or []:
resources.append({**guest, "node": node, "type": kind})
return resources
def _is_template(value):
return str(value).strip().lower() in ("1", "true", "yes")
def _normalize_proxmox_guest(session, source, resource):
kind = resource["type"]
node = resource["node"]
vmid = resource["vmid"]
config = _proxmox_get(session, source["url"], f"/nodes/{node}/{kind}/{vmid}/config") or {}
interfaces = proxmox_interfaces(config, kind)
if kind == "qemu" and resource.get("status") == "running":
_add_qemu_agent_ips(session, source, node, vmid, interfaces)
return {
"name": resource.get("name") or f"{kind}-{vmid}",
"source": source["name"],
"source_type": "Proxmox",
"kind": "LXC" if kind == "lxc" else "VM",
"status": "active" if resource.get("status") == "running" else "offline",
"vcpus": int(resource.get("maxcpu") or config.get("cores") or 0),
"memory": round(int(resource.get("maxmem") or 0) / 1024 / 1024) or int(config.get("memory") or 0),
"disk": round(int(resource.get("maxdisk") or 0) / 1024 / 1024),
"guest_os": proxmox_os_name(config.get("ostype", ""), kind),
"interfaces": interfaces,
}
def proxmox_interfaces(config, kind):
interfaces = []
for key in sorted(config):
if not re.fullmatch(r"net\d+", key):
continue
values = parse_proxmox_options(str(config[key]))
if kind == "qemu":
mac = next(
(value for name, value in values.items() if name in ("virtio", "e1000", "e1000e", "vmxnet3", "rtl8139")),
None,
)
name = key
ips = []
else:
mac = values.get("hwaddr")
name = values.get("name", key)
ip_value = values.get("ip", "")
ips = [ip_value] if ip_value and ip_value not in ("dhcp", "manual") else []
ip6_value = values.get("ip6", "")
if ip6_value and ip6_value not in ("dhcp", "auto", "manual"):
ips.append(ip6_value)
if mac:
interfaces.append({"name": name, "mac": mac, "ips": ips})
return interfaces
def parse_proxmox_options(value):
result = {}
for part in value.split(","):
if "=" in part:
key, item = part.split("=", 1)
result[key.strip().lower()] = item.strip()
return result
def _add_qemu_agent_ips(session, source, node, vmid, interfaces):
try:
payload = _proxmox_get(session, source["url"], f"/nodes/{node}/qemu/{vmid}/agent/network-get-interfaces") or {}
except (requests.RequestException, ValueError, KeyError):
# The guest agent is optional; configured MAC addresses are still useful.
return
agent_interfaces = payload.get("result", []) if isinstance(payload, dict) else payload
by_mac = {interface["mac"].lower(): interface for interface in interfaces}
for agent_interface in agent_interfaces or []:
target = by_mac.get((agent_interface.get("hardware-address") or "").lower())
if not target:
continue
for address in agent_interface.get("ip-addresses", []):
ip = address.get("ip-address")
prefix = address.get("prefix")
if ip and valid_guest_ip(ip):
target["ips"].append(f"{ip}/{prefix}" if prefix is not None else ip)
def proxmox_os_name(ostype, kind):
names = {
"win11": "Microsoft Windows 11", "win10": "Microsoft Windows 10/2016/2019",
"win8": "Microsoft Windows 8/2012", "win7": "Microsoft Windows 7/2008 R2",
"winxp": "Microsoft Windows XP", "l26": "Linux 2.6+", "l24": "Linux 2.4",
"solaris": "Solaris", "other": "Other",
}
return names.get(ostype, "Linux Container" if kind == "lxc" else ostype)
# --------------------------------------------------------------------------
# Common entry points
# --------------------------------------------------------------------------
def load_source(source, log=_noop):
if source.get("type") == "proxmox":
return load_proxmox_source(source, log)
return load_vmware_source(source, log)
def test_source(source):
"""Check credentials quickly and return a short human readable result."""
if source.get("type") == "proxmox":
session = _proxmox_session(source)
version = _proxmox_get(session, source["url"], "/version") or {}
return f"Proxmox VE {version.get('version', '?')} erreichbar"
from pyVim.connect import Disconnect, SmartConnect
context = ssl._create_unverified_context() if source.get("ignore_ssl") else None
instance = SmartConnect(host=source["host"], user=source["username"], pwd=source["password"], sslContext=context)
try:
about = instance.RetrieveContent().about
return f"{about.fullName} erreichbar"
finally:
Disconnect(instance)
+431
View File
@@ -0,0 +1,431 @@
"""Import virtual machines, interfaces, IP addresses and prefixes into NetBox."""
import ipaddress
from netbox_sync.core.netbox import assign_mac, related_id, related_name
from netbox_sync.core.virtualization import ip_with_prefix, valid_guest_ip
GLOBAL_VRF = None # NetBox "global" routing table
def _noop(*_args, **_kwargs):
return None
def vrf_label(vrf):
rd = getattr(vrf, "rd", None)
return f"{vrf.name} (RD: {rd})" if rd else vrf.name
def suggested_prefixlen(interface):
"""IPv4 defaults to /24 because guests often report host masks; IPv6 keeps its prefix."""
return 24 if interface.version == 4 else interface.network.prefixlen
def prefix_choices(host_address, detected_prefixlen):
host = ipaddress.ip_address(host_address)
if host.version == 4:
return list(range(8, 31))
return sorted({32, 40, 48, 52, 56, 60, 64, 80, 96, 112, 120, 124, 126, 127, 128, detected_prefixlen})
class VMSyncEngine:
"""Holds NetBox lookup data and performs the VM import.
The engine is used from worker threads. It never touches UI objects; all
feedback goes through the ``log`` callback ``log(text, level="info")``.
"""
def __init__(self, nb, log=_noop):
self.nb = nb
self.log = log
self.clusters = {}
self.cluster_tenants = {}
self.tenants = {}
self.vrfs = []
self.platforms = []
self.existing_vms = {}
self._reset_run_state()
def _reset_run_state(self):
self.synced_prefixes = set()
self.prefix_plans = []
self.preexisting_prefixes = []
# ------------------------------------------------------------------
# NetBox lookup data
# ------------------------------------------------------------------
def load_targets(self):
self.log("Lade Cluster, Mandanten, VRFs und Plattformen aus NetBox …")
clusters = list(self.nb.virtualization.clusters.all())
self.clusters = {item.name: item.id for item in clusters}
self.tenants = {item.name: item.id for item in self.nb.tenancy.tenants.all()}
self.vrfs = list(self.nb.ipam.vrfs.all())
self.platforms = list(self.nb.dcim.platforms.all())
self.cluster_tenants = {}
for cluster in clusters:
tenant_id = related_id(cluster, "tenant")
tenant_name = related_name(cluster, "tenant")
if tenant_id and tenant_name:
self.cluster_tenants[cluster.name] = {"id": tenant_id, "name": tenant_name}
self.tenants.setdefault(tenant_name, tenant_id)
self.existing_vms = {}
for vm in self.nb.virtualization.virtual_machines.filter(brief=True):
self.existing_vms.setdefault(vm.name, []).append(vm.id)
self.log(
f"NetBox: {len(self.clusters)} Cluster, {len(self.tenants)} Mandanten, "
f"{len(self.vrfs)} VRFs, {sum(map(len, self.existing_vms.values()))} VMs"
)
def tenant_vrfs(self, tenant_id):
return sorted(
(vrf for vrf in self.vrfs if related_id(vrf, "tenant") == tenant_id),
key=lambda item: item.name.casefold(),
)
def vrf_name(self, vrf_id):
if vrf_id is None:
return "Global"
return next((vrf.name for vrf in self.vrfs if vrf.id == vrf_id), f"VRF #{vrf_id}")
def get_or_create_tenant_vrf(self, vrf_name, tenant_id):
existing = next(
(vrf for vrf in self.vrfs if vrf.name == vrf_name and related_id(vrf, "tenant") == tenant_id),
None,
)
if existing:
self.log(f"Vorhandene VRF verwendet: {vrf_name}")
return existing.id
vrf = self.nb.ipam.vrfs.create({
"name": vrf_name,
"tenant": tenant_id,
"enforce_unique": True,
"description": "Automatisch erstellt durch NetBox Synchronizer",
})
self.vrfs.append(vrf)
self.log(f"VRF erstellt: {vrf_name}", "success")
return vrf.id
def get_platform_id(self, guest_os):
guest_os = (guest_os or "").lower()
if not guest_os:
return None
for platform in self.platforms:
name = platform.name.lower()
if name in guest_os or guest_os in name:
return platform.id
return None
# ------------------------------------------------------------------
# Prefix lookups
# ------------------------------------------------------------------
def find_prefixes_in_vrf(self, network, vrf_id):
return [
prefix for prefix in self.nb.ipam.prefixes.filter(prefix=str(network))
if related_id(prefix, "vrf") == vrf_id
]
def find_covering_prefixes(self, host_address, allowed_vrf_ids):
host = ipaddress.ip_address(host_address)
try:
candidates = list(self.nb.ipam.prefixes.filter(contains=str(host)))
except Exception as error: # noqa: BLE001
self.log(f"Präfixsuche für {host} nicht möglich: {error}", "warning")
return []
matches = []
for prefix in candidates:
prefix_vrf_id = related_id(prefix, "vrf")
if prefix_vrf_id not in allowed_vrf_ids:
continue
try:
parsed = ipaddress.ip_network(str(prefix.prefix))
except ValueError:
continue
if host in parsed:
matches.append((parsed.prefixlen, prefix, str(parsed), prefix_vrf_id))
return matches
def _allowed_vrfs(self, tenant_id, default_vrf_id):
return {vrf.id for vrf in self.tenant_vrfs(tenant_id)} | {default_vrf_id}
@staticmethod
def _reusable_prefix(covering, default_vrf_id):
default_matches = [match for match in covering if match[3] == default_vrf_id]
if default_matches:
return max(default_matches, key=lambda match: match[0])
if len({match[3] for match in covering}) == 1:
return max(covering, key=lambda match: match[0])
return None
# ------------------------------------------------------------------
# Import plan
# ------------------------------------------------------------------
def detect_missing_networks(self, vms, tenant_id, default_vrf_id):
"""Return networks of the selected VMs that NetBox does not know yet."""
self._reset_run_state()
detected = {}
for vm in vms:
for interface in vm.get("interfaces", []):
for ip_value in dict.fromkeys(interface.get("ips", [])):
address = ip_with_prefix(ip_value) if valid_guest_ip(ip_value) else None
if not address:
continue
parsed = ipaddress.ip_interface(address)
length = suggested_prefixlen(parsed)
network = ipaddress.ip_network(f"{parsed.ip}/{length}", strict=False)
entry = detected.setdefault(str(network), {
"host_address": parsed.ip,
"host_addresses": set(),
"detected_prefixlen": parsed.network.prefixlen,
"suggested_prefixlen": length,
"suggested_network": network,
"vms": set(),
})
entry["host_addresses"].add(parsed.ip)
entry["vms"].add(vm["name"])
allowed = self._allowed_vrfs(tenant_id, default_vrf_id)
missing = []
for item in detected.values():
group_is_missing = False
for host in item["host_addresses"]:
reusable = self._reusable_prefix(self.find_covering_prefixes(host, allowed), default_vrf_id)
if reusable:
cached = reusable[1:]
if cached not in self.preexisting_prefixes:
self.preexisting_prefixes.append(cached)
else:
group_is_missing = True
if group_is_missing:
missing.append(item)
self.log(
f"Netzwerkprüfung: {len(detected)} Netz(e) erkannt, {len(missing)} davon fehlen in NetBox"
)
return missing
def apply_network_plan(self, decisions, tenant_id):
"""Create VRFs requested in the plan and remember the confirmed networks."""
for decision in decisions:
if decision.get("create_vrf"):
decision["vrf_id"] = self.get_or_create_tenant_vrf(decision["vrf_name"], tenant_id)
decision["create_vrf"] = False
self.prefix_plans = list(decisions)
def classify_vms(self, vms):
"""Return how many selected VMs are new or already exist in NetBox."""
new = sum(1 for vm in vms if vm["name"] not in self.existing_vms)
return new, len(vms) - new
# ------------------------------------------------------------------
# VM synchronization
# ------------------------------------------------------------------
def _find_vm(self, name, cluster_id):
in_cluster = list(self.nb.virtualization.virtual_machines.filter(name=name, cluster_id=cluster_id))
if in_cluster:
return in_cluster[0]
anywhere = list(self.nb.virtualization.virtual_machines.filter(name=name))
if len(anywhere) == 1:
self.log(f"{name}: in anderem Cluster gefunden – wird in den Zielcluster verschoben", "warning")
return anywhere[0]
if len(anywhere) > 1:
raise RuntimeError("mehrere gleichnamige VMs in anderen Clustern – Zuordnung nicht eindeutig")
return None
def _find_ip(self, host_address, vrf_id):
candidates = list(self.nb.ipam.ip_addresses.filter(
address=host_address, vrf_id=vrf_id if vrf_id is not None else "null",
))
if len(candidates) > 1:
raise RuntimeError(f"IP-Adresse {host_address} ist in dieser VRF mehrfach vorhanden")
return candidates[0] if candidates else None
def sync_vm(self, source_vm, cluster_id, tenant_id, vrf_id):
"""Create or update one VM. Returns ``"created"`` or ``"updated"``."""
payload = {
"name": source_vm["name"], "cluster": cluster_id, "status": source_vm["status"],
"vcpus": source_vm["vcpus"], "memory": source_vm["memory"], "disk": source_vm["disk"],
"tenant": tenant_id,
}
platform_id = self.get_platform_id(source_vm.get("guest_os"))
if platform_id:
payload["platform"] = platform_id
netbox_vm = self._find_vm(source_vm["name"], cluster_id)
if netbox_vm:
netbox_vm.update(payload)
outcome = "updated"
self.log(f"VM aktualisiert: {source_vm['name']}")
else:
netbox_vm = self.nb.virtualization.virtual_machines.create(payload)
outcome = "created"
self.existing_vms.setdefault(source_vm["name"], []).append(netbox_vm.id)
self.log(f"VM erstellt: {source_vm['name']}", "success")
primary_ipv4 = None
primary_ipv6 = None
for interface in source_vm.get("interfaces", []):
netbox_interface = self.nb.virtualization.interfaces.get(
virtual_machine_id=netbox_vm.id, name=interface["name"]
)
interface_payload = {"virtual_machine": netbox_vm.id, "name": interface["name"], "enabled": True}
if netbox_interface:
netbox_interface.update(interface_payload)
else:
netbox_interface = self.nb.virtualization.interfaces.create(interface_payload)
try:
assign_mac(self.nb, netbox_interface, interface.get("mac"), "virtualization.vminterface")
except Exception as error: # noqa: BLE001 - MAC is optional metadata
self.log(f"{source_vm['name']}/{interface['name']}: MAC-Adresse nicht gesetzt ({error})", "warning")
for ip_value in dict.fromkeys(interface.get("ips", [])):
address = ip_with_prefix(ip_value) if valid_guest_ip(ip_value) else None
if not address:
continue
effective_vrf_id = self.sync_prefix_tenant(address, tenant_id, vrf_id)
ip_payload = {
"address": address, "status": "active", "tenant": tenant_id, "vrf": effective_vrf_id,
"assigned_object_type": "virtualization.vminterface",
"assigned_object_id": netbox_interface.id,
}
try:
host_address = str(ipaddress.ip_interface(address).ip)
ip_object = self._find_ip(host_address, effective_vrf_id)
if ip_object:
ip_object.update(ip_payload)
else:
ip_object = self.nb.ipam.ip_addresses.create(ip_payload)
except Exception as error:
raise RuntimeError(f"IP-Adresse {address}: {error}") from error
version = ipaddress.ip_interface(address).version
if version == 4 and not primary_ipv4:
primary_ipv4 = ip_object.id
elif version == 6 and not primary_ipv6:
primary_ipv6 = ip_object.id
primary = {}
if primary_ipv4:
primary["primary_ip4"] = primary_ipv4
if primary_ipv6:
primary["primary_ip6"] = primary_ipv6
if primary:
netbox_vm.update(primary)
return outcome
def sync_prefix_tenant(self, address, tenant_id, default_vrf_id):
"""Assign the tenant to the matching prefix and apply the confirmed network plan."""
parsed_interface = ipaddress.ip_interface(address)
host_address = parsed_interface.ip
network = str(parsed_interface.network)
vrf_id = default_vrf_id
for existing_prefix, existing_network, existing_vrf_id in self.preexisting_prefixes:
if host_address in ipaddress.ip_network(existing_network):
if (existing_network, existing_vrf_id) not in self.synced_prefixes:
existing_prefix.update({"tenant": tenant_id})
self.synced_prefixes.add((existing_network, existing_vrf_id))
self.log(f"Vorhandenes Netzwerk übernommen: {existing_network}")
return existing_vrf_id
for cached_network, cached_vrf in self.synced_prefixes:
if host_address in ipaddress.ip_network(cached_network):
return cached_vrf
cache_key = (network, vrf_id)
candidates = self.find_prefixes_in_vrf(network, vrf_id)
if len(candidates) > 1:
self.log(f"Präfix {network} nicht geändert: mehrere passende Präfixe gefunden", "warning")
return vrf_id
try:
if candidates:
candidates[0].update({"tenant": tenant_id})
self.log(f"Mandant am Präfix aktualisiert: {network}")
else:
covering = self.find_covering_prefixes(host_address, self._allowed_vrfs(tenant_id, vrf_id))
reusable = self._reusable_prefix(covering, vrf_id)
if reusable:
_, existing_prefix, existing_network, existing_vrf_id = reusable
existing_prefix.update({"tenant": tenant_id})
self.synced_prefixes.add((existing_network, existing_vrf_id))
self.log(f"Vorhandenes Netzwerk übernommen: {existing_network}")
return existing_vrf_id
matching_plans = [
decision for decision in self.prefix_plans
if host_address in ipaddress.ip_network(decision["network"])
]
if not matching_plans:
self.log(f"Kein Präfix für {host_address} angelegt (nicht im Netzwerkplan)")
return vrf_id
decision = max(matching_plans, key=lambda item: ipaddress.ip_network(item["network"]).prefixlen)
network = decision["network"]
vrf_id = decision["vrf_id"]
cache_key = (network, vrf_id)
selected = self.find_prefixes_in_vrf(network, vrf_id)
if len(selected) > 1:
self.log(f"Präfix {network} nicht geändert: mehrere passende Präfixe gefunden", "warning")
return vrf_id
if selected:
selected[0].update({"tenant": tenant_id})
self.log(f"Mandant am Präfix aktualisiert: {network}")
else:
payload = {"prefix": network, "status": "active", "tenant": tenant_id}
if vrf_id is not None:
payload["vrf"] = vrf_id
self.nb.ipam.prefixes.create(payload)
self.log(f"Präfix erstellt: {network}", "success")
except Exception as error:
raise RuntimeError(f"Präfix {network}: {error}") from error
self.synced_prefixes.add(cache_key)
return vrf_id
# ------------------------------------------------------------------
# IPAM batch tools
# ------------------------------------------------------------------
def create_vrfs_batch(self, tenant_name, names):
tenant_id = self.tenants[tenant_name]
created = reused = 0
errors = []
for name in names:
exists = any(vrf.name == name for vrf in self.tenant_vrfs(tenant_id))
try:
self.get_or_create_tenant_vrf(name, tenant_id)
reused += exists
created += not exists
except Exception as error: # noqa: BLE001
errors.append(f"{name}: {error}")
self.log(f"VRF {name}: {error}", "error")
return created, reused, errors
def create_prefixes_batch(self, tenant_name, vrf_id, values):
tenant_id = self.tenants[tenant_name]
created = reused = 0
canonical = []
errors = []
for value in values:
try:
network = ipaddress.ip_network(value, strict=False)
network_text = str(network)
candidates = self.find_prefixes_in_vrf(network_text, vrf_id)
if len(candidates) > 1:
raise ValueError("mehrere identische Präfixe in dieser VRF gefunden")
if candidates:
candidates[0].update({"tenant": tenant_id})
reused += 1
else:
payload = {"prefix": network_text, "status": "active", "tenant": tenant_id}
if vrf_id is not None:
payload["vrf"] = vrf_id
self.nb.ipam.prefixes.create(payload)
created += 1
canonical.append(network_text)
self.log(f"Netzwerk verarbeitet: {network_text}")
except Exception as error: # noqa: BLE001
errors.append(f"{value}: {error}")
self.log(f"Netzwerk {value}: {error}", "error")
return created, reused, canonical, errors