Compare commits

..
3 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 773b3527db chore: release 4.2.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 12:35:23 +01:00
MrBlakeandClaude Opus 5.5 02f2d19e55 feat: map hypervisor hosts to NetBox devices during VM import
The import wizard asks for every ESXi host / Proxmox node which NetBox
device it corresponds to (names rarely match); the choice is remembered
per profile and set as the VM's device.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 12:35:17 +01:00
MrBlakeandClaude Opus 5.5 25dfa5e231 feat: export ESXi host / Proxmox node per VM in offline JSON
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 12:29:43 +01:00
10 changed files with 117 additions and 874 deletions

No files matched your search

-1
View File
@@ -10,4 +10,3 @@ output/
# Lokale Konfigurationen und Zugangsdaten
config.json
*.tmp
.gitea-token
+83 -127
View File
@@ -1,153 +1,109 @@
# NetBox Synchronizer
Windows desktop application that documents virtual machines from VMware
vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
| | |
|---|---|
| **Type** | Desktop application (Python, PySide6) |
| **Platform** | Windows |
| **Repository** | <https://git.mrblake.cc/MrBlake/NetBox-VM-Import-Desktop> |
## Features
### General
- Customer profiles with NetBox target, virtualisation sources and switch
credentials; switch between them in the sidebar
- Automatic saving; passwords, tokens and secrets are encrypted with Windows DPAPI
- All network access runs in the background — the window stays responsive and
operations can be cancelled
- Light and dark theme (optionally following Windows)
- Log with filter, search and export, plus a rotating log file under
`%APPDATA%\NetBox VM Import\logs`
- Keyboard shortcuts: `Ctrl+1…8` navigation, `F5` reload/read, `Ctrl+F` search
### Virtual machines
- Multiple VMware and Proxmox sources per profile, read in parallel; connection
test directly in the dialog
- QEMU/KVM VMs and optionally LXC containers; IP addresses via VMware Tools or
the QEMU guest agent
- Table with search, filters (source, status, "new"/"already in NetBox") and
multi-selection
- Automatic cluster mapping: each vCenter/ESXi or Proxmox cluster is mapped to
the NetBox cluster with the same (or a uniquely similar) name; manual
mappings are remembered in the profile, and missing clusters can be created in
NetBox directly
- Four-step import wizard: **Target** (cluster mapping, tenant preselected from
the cluster, VRF or global) → **Networks** (check missing prefixes with size
and VRF, create new VRFs directly) → **Review** (summary of all changes) →
**Import** (progress, live log, cancel)
- VMs are matched uniquely per cluster; existing prefixes are reused
- MAC addresses are set correctly on NetBox ≥ 4.2 (separate MAC model)
### Switches (Aruba CX, ArubaOS-Switch/ProCurve, HPE Comware)
- Add several NetBox devices in one step — host taken from the primary IP,
platform suggested from model/manufacturer
- Platform "detect automatically" via SSH
- Parallel SSH queries; SSH host keys are stored on first contact and verified
afterwards
- Interfaces, interface IP addresses and LLDP/CDP neighbours
- **Preview before writing**: all changes are computed as a dry run and only
sent after confirmation
- Interface types from device type templates are left untouched; Comware short
names (`GE1/0/1`) are mapped to full NetBox names (`GigabitEthernet1/0/1`)
- VLAN membership per port (untagged and tagged, read from the running
configuration) is written to the interface **label**, e.g. `10` or `1,20-22`;
only VLAN-related lines of the configuration are kept in the raw data
- Automatic port mapping when NetBox names differ from the switch (e.g. `5` ↔
`1/1/5`): equal name, then equal port number, then natural order
- **Mapping review** before the preview: non-obvious port mappings and every
LLDP/CDP neighbour can be corrected; a neighbour can be assigned manually to
any device of the switch's tenant group. Choices are stored in the profile
- Cables from LLDP/CDP, also with FQDN system names or via the management IP
- The switch configuration is only changed when "Enable LLDP if needed" is
explicitly switched on
### Windows clients (agentless via WMI/CIM over WinRM)
- Targets from Active Directory (optional search OU, enabled accounts only,
last logon within N days, include/exclude servers) or as a list of host
names, IP addresses, networks (`192.0.2.0/24`) and ranges (`192.0.2.10-50`)
- Sign-in via the Windows credential dialog (domain account with local admin
rights, verified against the domain) or with the current Windows session; the
password is kept in memory only
- Reads name, manufacturer, model (for Lenovo the model name instead of the
machine type), serial number, form factor, operating system with
version/build, logged-on user, CPU/RAM and physical network adapters with MAC
and IPs
- Parallel queries; unreachable clients stay visible with their AD data, errors
come with a concrete hint
- Import as NetBox devices with site, role and tenant; manufacturers, device
types and platforms are created when needed, optionally interfaces, MAC and IP
addresses — with a preview before writing
- Built-in **setup guide**: group policy (WinRM, service, firewall),
permissions, common errors, check commands and a connection test for single
clients
### Offline mode (without NetBox)
- "Offline mode (without NetBox)" checkbox in the sidebar — global, independent
of the customer profile
- VMs and switches are read without a NetBox connection; switches can then be
added manually by name
- Selected VMs, clients or read switches are exported as a JSON file
(`*.nbsync.json`) — without passwords, tokens or user names
- On a machine with NetBox access, "Load from file …" (VMs, switches and
Windows clients pages) loads the file; the import wizard or dry-run preview
then runs as usual. Switches are matched by NetBox device ID or name
### VRFs & networks
- Create several VRFs or prefixes for one tenant at once
Windows-Desktopanwendung, die virtuelle Maschinen aus VMware vSphere und Proxmox VE, HPE-/Aruba-Switche
sowie Windows-Clients in NetBox dokumentiert.
## Installation
Run `NetBoxSynchronizer-Setup-<version>.exe`. The installer
`NetBoxSynchronizer-Setup-<version>.exe` ausführen. Der Installer
- installs for the current user **without administrator rights** by default
("for all users" can be selected in the wizard),
- creates a Start menu entry and optionally a desktop shortcut,
- updates an existing installation in place,
- asks on uninstall whether customer profiles and logs should be removed too.
- installiert standardmäßig **ohne Administratorrechte** für den aktuellen Benutzer
(im Assistenten kann „für alle Benutzer“ gewählt werden),
- legt einen Startmenü-Eintrag und optional eine Desktop-Verknüpfung an,
- aktualisiert eine vorhandene Installation direkt,
- fragt bei der Deinstallation, ob Kundenprofile und Protokolle ebenfalls gelöscht werden sollen.
Customer profiles of the predecessor ("NetBox VM Import") are migrated
automatically.
Bestehende Kundenprofile der Vorgängerversion („NetBox VM Import“) werden automatisch übernommen.
## Development
## Funktionen
**Allgemein**
- Kundenprofile mit NetBox-Ziel, Virtualisierungsquellen und Switch-Zugängen; Wechsel über die Seitenleiste
- Automatisches Speichern; Passwörter, Tokens und Secrets mit Windows DPAPI verschlüsselt
- Alle Netzwerkzugriffe laufen im Hintergrund – das Fenster bleibt bedienbar, Vorgänge lassen sich abbrechen
- Helles und dunkles Design (folgt auf Wunsch Windows)
- Protokoll mit Filter, Suche und Export; zusätzlich rotierende Logdatei unter `%APPDATA%\NetBox VM Import\logs`
- Tastenkürzel: `Strg+1…8` Navigation, `F5` neu laden/auslesen, `Strg+F` Suche
**Virtuelle Maschinen**
- Mehrere VMware- und Proxmox-Quellen pro Profil, parallel ausgelesen; Verbindungstest direkt im Dialog
- QEMU/KVM-VMs und optional LXC-Container; IP-Adressen über VMware Tools bzw. QEMU Guest Agent
- Tabelle mit Suche, Filtern (Quelle, Status, „neu“/„bereits in NetBox“) und Mehrfachauswahl
- Automatische Cluster-Zuordnung: Jeder vCenter-/ESXi- bzw. Proxmox-Cluster wird dem gleichnamigen (oder eindeutig
ähnlichen) NetBox-Cluster zugeordnet; manuelle Zuordnungen merkt sich das Kundenprofil, fehlende Cluster können
direkt in NetBox angelegt werden
- Import-Assistent in vier Schritten: **Ziel** (Cluster-Zuordnung, Mandant aus dem Cluster vorausgewählt, VRF oder global)
→ **Netzwerke** (fehlende Präfixe mit Größe und VRF prüfen, neue VRFs direkt anlegen)
→ **Prüfen** (Zusammenfassung aller Änderungen) → **Import** (Fortschritt, Live-Protokoll, Abbrechen)
- VMs werden pro Cluster eindeutig zugeordnet; vorhandene Präfixe werden wiederverwendet
- MAC-Adressen werden auch mit NetBox ≥ 4.2 (eigenes MAC-Modell) korrekt gesetzt
**Switche** (Aruba CX, ArubaOS-Switch/ProCurve, HPE Comware)
- Mehrere NetBox-Geräte in einem Schritt hinzufügen – Host aus der primären IP, Plattform aus Modell/Hersteller vorgeschlagen
- Plattform „Automatisch erkennen“ per SSH
- Parallele SSH-Abfragen; SSH-Hostschlüssel werden beim ersten Kontakt gespeichert und danach geprüft
- Schnittstellen, Interface-IP-Adressen sowie LLDP-/CDP-Nachbarn
- **Vorschau vor dem Schreiben**: alle Änderungen werden als Dry-Run berechnet und erst nach Bestätigung übertragen
- Interface-Typen aus Gerätetyp-Vorlagen bleiben unangetastet; Comware-Kurznamen (`GE1/0/1`) werden den
vollständigen NetBox-Namen (`GigabitEthernet1/0/1`) zugeordnet
- Kabel aus LLDP/CDP auch bei FQDN-Systemnamen oder über die Management-IP
- Die Switch-Konfiguration wird nur verändert, wenn „LLDP bei Bedarf aktivieren“ ausdrücklich eingeschaltet ist
**Windows-Clients** (agentlos per WMI/CIM über WinRM)
- Ziele aus dem Active Directory (optional Such-OU, nur aktivierte Konten, letzte Anmeldung innerhalb von N Tagen,
Server ein-/ausschließen) oder als Liste von Hostnamen, IP-Adressen, Netzen (`10.0.10.0/24`) und Bereichen
(`10.0.20.10-50`)
- Anmeldung über das Windows-Anmeldefenster (Domänenkonto mit lokalen Adminrechten, wird gegen die Domäne geprüft)
oder mit der aktuellen Windows-Anmeldung; das Kennwort bleibt nur im Arbeitsspeicher
- Liest Name, Hersteller, Modell (bei Lenovo der Modellname statt des Maschinentyps), Seriennummer, Bauform,
Betriebssystem mit Version/Build, angemeldeten Benutzer, CPU/RAM sowie physische Netzwerkkarten mit MAC und IPs
- Parallele Abfrage; nicht erreichbare Clients bleiben mit den AD-Daten sichtbar, Fehler mit konkretem Hinweis
- Übernahme als NetBox-Geräte mit Standort, Rolle und Mandant; Hersteller, Gerätetypen und Plattformen werden bei
Bedarf angelegt, optional Schnittstellen, MAC- und IP-Adressen – mit Vorschau vor dem Schreiben
- **Einrichtungshilfe** im Programm: Gruppenrichtlinie (WinRM, Dienst, Firewall), Berechtigungen, Fehlerbilder,
Prüfbefehle und ein Verbindungstest für einzelne Clients
**Offline-Modus (ohne NetBox)**
- Checkbox „Offline-Modus (ohne NetBox)“ in der Seitenleiste – gilt global, unabhängig vom Kundenprofil
- VMs und Switche werden ohne NetBox-Verbindung ausgelesen; Switche lassen sich dann manuell per Name anlegen
- Ausgewählte VMs, Clients bzw. ausgelesene Switche werden als JSON-Datei (`*.nbsync.json`) exportiert – ohne Passwörter,
Tokens oder Benutzernamen
- Auf einem Rechner mit NetBox-Zugang lädt „Aus Datei laden …“ (Seiten VMs, Switche und Windows-Clients) die Datei; danach laufen
Import-Assistent bzw. Dry-Run-Vorschau wie gewohnt. Switche werden über NetBox-Geräte-ID oder Namen zugeordnet
**VRFs & Netze**
- Mehrere VRFs oder Präfixe für einen Mandanten gesammelt anlegen
## Entwicklung
```powershell
py -3 -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install -r requirements-dev.txt
python main.py # start the application
python -m pytest # tests
python main.py # Anwendung starten
python -m pytest # Tests
```
Project layout:
Projektstruktur:
```
netbox_sync/
core/ UI-independent logic: configuration, NetBox, VMware/Proxmox, VM import, switches, Windows clients
ui/ Qt interface (PySide6): main window, pages, dialogs, import wizard, theme
resources/ icons
installer/ Inno Setup script
tests/ pytest (parsers, configuration, sync against an in-memory NetBox)
core/ UI-unabhängige Logik: Konfiguration, NetBox, VMware/Proxmox, VM-Import, Switche, Windows-Clients
ui/ Qt-Oberfläche (PySide6): Hauptfenster, Seiten, Dialoge, Import-Assistent, Theme
resources/ Icons
installer/ Inno-Setup-Skript
tests/ pytest (Parser, Konfiguration, Sync gegen eine In-Memory-NetBox)
```
## Build & installer
## Build & Installer
The installer requires [Inno Setup 6](https://jrsoftware.org/isinfo.php)
Voraussetzung für den Installer ist [Inno Setup 6](https://jrsoftware.org/isinfo.php)
(`winget install JRSoftware.InnoSetup`).
```powershell
.\build.ps1 # tests, PyInstaller build and installer
.\build.ps1 -SkipInstaller # only dist\NetBoxSynchronizer\
.\build.ps1 # Tests, PyInstaller-Build und Installer
.\build.ps1 -SkipInstaller # nur dist\NetBoxSynchronizer\
```
Output: `dist\installer\NetBoxSynchronizer-Setup-<version>.exe` and the
portable variant `dist\portable\NetBox VM Import.exe` (runs without
installation; `-SkipPortable` omits it). The version is set in
`netbox_sync/__init__.py`.
Ergebnis: `dist\installer\NetBoxSynchronizer-Setup-<version>.exe` sowie die portable Variante
`dist\portable\NetBox VM Import.exe` (ohne Installation lauffähig; `-SkipPortable` lässt sie weg). Die Version steht in `netbox_sync/__init__.py`.
+1 -1
View File
@@ -3,7 +3,7 @@
#define AppName "NetBox Synchronizer"
#ifndef AppVersion
#define AppVersion "4.3.0"
#define AppVersion "4.2.0"
#endif
#define AppPublisher "Louis-Alexander Kerst"
#define AppExeName "NetBoxSynchronizer.exe"
+1 -1
View File
@@ -1,7 +1,7 @@
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
APP_NAME = "NetBox Synchronizer"
APP_VERSION = "4.3.0"
APP_VERSION = "4.2.0"
APP_PUBLISHER = "Louis-Alexander Kerst"
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
+23 -396
View File
@@ -29,14 +29,6 @@ IP_COMMANDS = {
"hpe_comware": ("display ip interface brief", "display ipv6 interface brief"),
}
# The running configuration is the only output that shows untagged and tagged
# VLAN membership per port on all three platforms.
CONFIG_COMMANDS = {
"aruba_cx": "show running-config",
"aruba_aos": "show running-config",
"hpe_comware": "display current-configuration interface",
}
LLDP_CONTROL = {
"aruba_cx": {
"status": "show lldp configuration",
@@ -319,10 +311,6 @@ def run_switch_commands(config, enable_lldp=False, known_hosts=None, log=_noop):
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])
config_output = _run_cli_command(channel, CONFIG_COMMANDS[platform], timeout=90)
if CLI_ERROR.search(config_output[:500]):
log(f"{config.get('name', config['host'])}: Konfiguration nicht lesbar – VLANs werden nicht übernommen")
config_output = ""
return {
"platform": platform,
"interfaces": interfaces,
@@ -330,7 +318,6 @@ def run_switch_commands(config, enable_lldp=False, known_hosts=None, log=_noop):
"ipv6_interfaces": ip_outputs[1],
"neighbors": neighbors,
"cdp_neighbors": cdp_neighbors,
"config": config_output,
"lldp_status": lldp_status,
"lldp_disabled": lldp_disabled and not lldp_enabled_automatically,
"lldp_enabled_automatically": lldp_enabled_automatically,
@@ -604,177 +591,8 @@ def _parse_neighbor_table(output):
return neighbors
# --------------------------------------------------------------------------
# VLAN membership from the running configuration
# --------------------------------------------------------------------------
_PORT_RANGE = re.compile(r"^(\D*(?:\d+/)*)(\d+)-(?:\1)?(\d+)$")
_VLAN_CONFIG_LINE = re.compile(r"(?i)^\s*(?:interface\s|vlan\s|#|exit|\s*(?:no\s+)?routing\b)|vlan|tagged|link-type|link-mode")
def parse_vlan_list(text):
"""``10,20-22`` (Aruba) or ``10 20 to 22`` (Comware) → set of VLAN IDs."""
text = re.sub(r"\s+to\s+", "-", text.strip(), flags=re.I)
vlans = set()
for part in re.split(r"[,\s]+", text):
match = re.fullmatch(r"(\d+)(?:-(\d+))?", part)
if not match:
continue
start, end = int(match.group(1)), int(match.group(2) or match.group(1))
if 1 <= start <= end <= 4094:
vlans.update(range(start, end + 1))
return vlans
def _expand_ports(text):
"""ArubaOS-S port lists such as ``1-4,A1-A2,1/5-1/8,Trk1``."""
ports = []
for part in (item.strip() for item in text.split(",")):
match = _PORT_RANGE.match(part)
if match and int(match.group(2)) <= int(match.group(3)):
ports += [f"{match.group(1)}{number}" for number in range(int(match.group(2)), int(match.group(3)) + 1)]
elif part:
ports.append(part)
return ports
def _membership(untagged=(), tagged=(), tagged_all=False):
untagged = set(untagged)
return {"untagged": sorted(untagged), "tagged": sorted(set(tagged) - untagged), "tagged_all": bool(tagged_all)}
def _config_blocks(config, header):
"""Yield ``(header match, body lines)`` for indented configuration blocks."""
current, body = None, []
for line in clean_output(config).splitlines():
match = header.match(line)
if match:
if current:
yield current, body
current, body = match, []
elif current and line[:1] in (" ", "\t"):
body.append(line.strip())
elif current:
yield current, body
current, body = None, []
if current:
yield current, body
def _parse_aos_vlans(config):
ports = {}
for match, body in _config_blocks(config, re.compile(r"^vlan\s+(\d+)\s*$", re.I)):
vlan = int(match.group(1))
for line in body:
member = re.match(r"^(untagged|tagged)\s+(\S+)", line, flags=re.I)
if member:
for port in _expand_ports(member.group(2)):
entry = ports.setdefault(interface_key(port), {"untagged": set(), "tagged": set()})
entry[member.group(1).lower()].add(vlan)
return {key: _membership(entry["untagged"], entry["tagged"]) for key, entry in ports.items()}
def _parse_cx_vlans(config):
result = {}
for match, body in _config_blocks(config, re.compile(r"^interface\s+(.+?)\s*$", re.I)):
text = "\n".join(body)
access = re.search(r"(?im)^vlan access (\d+)", text)
native = re.search(r"(?im)^vlan trunk native (\d+)(\s+tag)?", text)
allowed = re.findall(r"(?im)^vlan trunk allowed (.+)$", text)
if access:
result[interface_key(match.group(1))] = _membership([int(access.group(1))])
elif native or allowed:
native_id = int(native.group(1)) if native else 1
tagged_native = bool(native and native.group(2))
tagged = set().union(*(parse_vlan_list(item) for item in allowed))
everything = not allowed or any(item.strip().lower() == "all" for item in allowed)
untagged = [] if tagged_native else [native_id]
result[interface_key(match.group(1))] = _membership(untagged, tagged | ({native_id} if tagged_native else set()),
everything)
elif re.search(r"(?im)^no routing\b", text):
result[interface_key(match.group(1))] = _membership([1])
return result
def _parse_comware_vlans(config):
result = {}
for match, body in _config_blocks(config, re.compile(r"^interface\s+(\S+)\s*$", re.I)):
name = match.group(1)
prefix = re.match(r"^[a-z]+", interface_key(name))
if not prefix or prefix.group(0) not in ("ge", "xge", "wge", "fge", "hge", "fe", "bagg"):
continue
text = "\n".join(body)
if re.search(r"(?im)^port link-mode route", text):
continue
link_type = re.search(r"(?im)^port link-type (\w+)", text)
link_type = link_type.group(1).lower() if link_type else "access"
if link_type == "trunk":
pvid = re.search(r"(?im)^port trunk pvid vlan (\d+)", text)
pvid = int(pvid.group(1)) if pvid else 1
permitted, everything = {1}, False
for undo, vlans in re.findall(r"(?im)^(undo )?port trunk permit vlan (.+)$", text):
if vlans.strip().lower() == "all":
everything = not undo
elif undo:
permitted -= parse_vlan_list(vlans)
else:
permitted |= parse_vlan_list(vlans)
untagged = [pvid] if everything or pvid in permitted else []
result[interface_key(name)] = _membership(untagged, permitted, everything)
elif link_type == "hybrid":
untagged, tagged = set(), set()
for vlans, mode in re.findall(r"(?im)^port hybrid vlan (.+?) (untagged|tagged)\s*$", text):
(untagged if mode.lower() == "untagged" else tagged).update(parse_vlan_list(vlans))
result[interface_key(name)] = _membership(untagged or {1}, tagged)
else:
access = re.search(r"(?im)^port access vlan (\d+)", text)
result[interface_key(name)] = _membership([int(access.group(1)) if access else 1])
return result
def parse_vlans(config, platform):
"""VLAN membership per port, keyed by :func:`interface_key`."""
if not config:
return {}
parser = {"aruba_aos": _parse_aos_vlans, "aruba_cx": _parse_cx_vlans, "hpe_comware": _parse_comware_vlans}
return parser[platform](config) if platform in parser else {}
def _compress_vlans(vlans):
parts, values = [], sorted(vlans)
start = previous = None
for value in values + [None]:
if start is not None and value == previous + 1:
previous = value
continue
if start is not None:
parts.append(str(start) if start == previous else f"{start}-{previous}")
start = previous = value
return ",".join(parts)
def vlan_label(vlans, limit=64):
"""All VLANs of a port (untagged and tagged) as short NetBox label."""
if not vlans:
return ""
if vlans.get("tagged_all"):
return "all"
text = _compress_vlans(set(vlans.get("untagged", [])) | set(vlans.get("tagged", [])))
if len(text) > limit:
text = text[:limit - 1].rsplit(",", 1)[0] + "…"
return text
def _vlan_config_excerpt(config):
"""Keep only VLAN-related lines – the full configuration may contain secrets."""
return "\n".join(line for line in clean_output(config).splitlines() if _VLAN_CONFIG_LINE.search(line))
def build_snapshot(outputs, platform):
interfaces = parse_interfaces(outputs["interfaces"], platform)
vlans = parse_vlans(outputs.get("config", ""), platform)
for interface in interfaces:
interface["vlans"] = vlans.get(interface_key(interface["name"]))
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", ""))
@@ -807,9 +625,7 @@ def build_snapshot(outputs, platform):
"neighbors": neighbors,
"lldp_neighbors": lldp_neighbors,
"cdp_neighbors": cdp_neighbors,
"raw": {**{key: value for key, value in outputs.items() if key != "config"},
**({"vlan_config": _vlan_config_excerpt(outputs["config"])} if outputs.get("config") else {})},
"vlans_read": bool(outputs.get("config")),
"raw": outputs,
"lldp_disabled": outputs.get("lldp_disabled", False),
"lldp_enabled_automatically": outputs.get("lldp_enabled_automatically", False),
"discovered_at": time.time(),
@@ -896,179 +712,6 @@ def _device_interfaces(nb, device_id):
return records
MATCH_METHODS = {
"name": "gleicher Name",
"number": "gleiche Portnummer",
"order": "Reihenfolge",
"manual": "manuell",
"new": "neu anlegen",
}
_PORT_NAME = re.compile(r"^[A-Za-z\- ]*\d+(?:/\d+)*$")
def _natural_key(name):
return [int(part) if part.isdigit() else part.casefold() for part in re.split(r"(\d+)", name)]
def _port_number(name):
"""Last number of a port-like name: ``1/1/5`` → 5, ``GE1/0/5`` → 5, ``5`` → 5."""
name = (name or "").strip()
return int(re.search(r"(\d+)$", name).group(1)) if _PORT_NAME.match(name) else None
def _record_type(record):
value = getattr(record, "type", None)
return getattr(value, "value", value if isinstance(value, str) else None) or ""
def _physical_record(record):
return (_record_type(record) not in ("virtual", "lag", "bridge")
and not re.match(r"^(?:vlan|lo|mgmt|oobm)", interface_key(record.name)))
def _physical_interface(interface):
return netbox_interface_type(interface) not in ("virtual", "lag")
def match_interfaces(interfaces, records, manual=None):
"""Assign NetBox interfaces to discovered switch interfaces.
Order of precedence: stored manual choices (``{switch name: NetBox name}``,
an empty NetBox name means "create new"), equal names across vendor
spellings, an equal last port number (``1/1/5`` ↔ ``5``) and finally the
natural order of the remaining physical ports when both sides have the
same number left. Returns ``{switch name: (record or None, method)}``.
"""
manual = manual or {}
by_name = {record.name: record for record in records}
by_key = {}
for record in records:
key = interface_key(record.name)
if key not in by_key or len(record.name) > len(by_key[key].name):
by_key[key] = record
result, used = {}, set()
def assign(interface, record, method):
result[interface["name"]] = (record, method)
if record is not None:
used.add(record.id)
for interface in interfaces:
if interface["name"] not in manual:
continue
target = manual[interface["name"]]
record = by_name.get(target) if target else None
if target and (record is None or record.id in used):
continue # stale choice – fall back to the automatic match
assign(interface, record, "manual" if record else "new")
for interface in interfaces:
if interface["name"] not in result:
record = by_key.get(interface_key(interface["name"]))
if record and record.id not in used:
assign(interface, record, "name")
open_ports = [item for item in interfaces if item["name"] not in result and _physical_interface(item)]
open_records = [record for record in records if record.id not in used and _physical_record(record)]
ports_by_number, records_by_number = {}, {}
for item in open_ports:
ports_by_number.setdefault(_port_number(item["name"]), []).append(item)
for record in open_records:
records_by_number.setdefault(_port_number(record.name), []).append(record)
for number, ports in ports_by_number.items():
candidates = records_by_number.get(number, [])
if number is not None and len(ports) == 1 and len(candidates) == 1:
assign(ports[0], candidates[0], "number")
open_ports = [item for item in open_ports if item["name"] not in result]
open_records = [record for record in open_records if record.id not in used]
if open_ports and len(open_ports) == len(open_records):
open_ports.sort(key=lambda item: _natural_key(item["name"]))
open_records.sort(key=lambda record: _natural_key(record.name))
for interface, record in zip(open_ports, open_records):
assign(interface, record, "order")
for interface in interfaces:
result.setdefault(interface["name"], (None, "new"))
return result
def _resolve_device(nb, config):
"""The NetBox device of a switch config, or an error text."""
if config.get("device_id"):
device = nb.dcim.devices.get(int(config["device_id"]))
return (device, None) if device else (None, f"NetBox-Gerät #{config['device_id']} existiert nicht mehr")
# Switches captured in offline mode are only known by name.
matches = list(nb.dcim.devices.filter(name=config["name"]))
if len(matches) != 1:
return None, f"NetBox-Gerät „{config['name']}“ " + ("nicht gefunden" if not matches else "ist nicht eindeutig")
return matches[0], None
def candidate_devices(nb, device):
"""Devices a neighbor may be assigned to: the tenant group of the switch.
Falls back to the switch's tenant and, without a tenant, to all devices.
Returns ``(scope description, [{"id", "name"}])``.
"""
tenant_id = related_id(device, "tenant")
scope, devices = "alle Geräte", None
if tenant_id:
tenant = nb.tenancy.tenants.get(tenant_id)
group_id = related_id(tenant, "group") if tenant else None
if group_id:
group = getattr(tenant, "group", None)
scope = f"Mandantengruppe {getattr(group, 'name', None) or group_id}"
devices = nb.dcim.devices.filter(tenant_group_id=group_id)
else:
scope = f"Mandant {getattr(tenant, 'name', None) or tenant_id}"
devices = nb.dcim.devices.filter(tenant_id=tenant_id)
if devices is None:
devices = nb.dcim.devices.all()
rows = [{"id": item.id, "name": item.name} for item in devices if getattr(item, "name", None) and item.id != device.id]
return scope, sorted(rows, key=lambda row: row["name"].casefold())
def plan_switch_sync(nb, config, snapshot):
"""Proposed interface mapping and neighbor devices for the review dialog."""
device, error = _resolve_device(nb, config)
if error:
return {"error": error}
records = list(nb.dcim.interfaces.filter(device_id=device.id))
matches = match_interfaces(snapshot["interfaces"], records, config.get("interface_map"))
scope, devices = candidate_devices(nb, device)
known = {row["id"] for row in devices}
lookup = _RemoteLookup(nb)
manual = config.get("neighbor_devices") or {}
neighbors = []
for neighbor in snapshot["neighbors"]:
local = neighbor.get("local_port")
if local in manual:
device_id, method = int(manual[local]) or None, "manual"
remote = nb.dcim.devices.get(device_id) if device_id else None
else:
remote = lookup.device(neighbor)
device_id, method = (remote.id if remote else None), "auto"
if remote and remote.id not in known and remote.id != device.id:
devices.append({"id": remote.id, "name": remote.name})
known.add(remote.id)
neighbors.append(dict(neighbor, device_id=device_id, method=method))
devices.sort(key=lambda row: row["name"].casefold())
return {
"error": None,
"device": {"id": device.id, "name": device.name},
"interfaces": [
{"name": item["name"], "netbox_name": record.name if record else "", "method": method,
"physical": _physical_interface(item), "vlan_label": vlan_label(item.get("vlans"))}
for item in snapshot["interfaces"]
for record, method in [matches[item["name"]]]
],
"netbox_interfaces": sorted((record.name for record in records), key=_natural_key),
"neighbors": neighbors,
"device_scope": scope,
"devices": devices,
}
class _RemoteLookup:
"""Find neighbor devices and interfaces in NetBox, cached per sync run."""
@@ -1109,13 +752,6 @@ class _RemoteLookup:
record = records.get(interface_key(candidate))
if record:
return record
# Device types often name ports "1", "2", … while LLDP reports "1/1/1".
number = _port_number(neighbor.get("remote_port"))
if number is not None:
found = [record for record in records.values()
if _physical_record(record) and _port_number(record.name) == number]
if len(found) == 1:
return found[0]
return None
@@ -1136,38 +772,37 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
device-type templates and manual corrections in NetBox are preserved.
"""
report = _new_report()
device, error = _resolve_device(nb, config)
if error:
report["errors"].append(error)
return report
device_id = device.id
if config.get("device_id"):
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
else:
# Switches captured in offline mode are only known by name.
matches = list(nb.dcim.devices.filter(name=config["name"]))
if len(matches) != 1:
report["errors"].append(f"NetBox-Gerät „{config['name']}“ " +
("nicht gefunden" if not matches else "ist nicht eindeutig"))
return report
device = matches[0]
device_id = device.id
tenant_id = related_id(device, "tenant")
matches = match_interfaces(snapshot["interfaces"], list(nb.dcim.interfaces.filter(device_id=device_id)),
config.get("interface_map"))
existing = _device_interfaces(nb, device_id)
records = {}
for interface in snapshot["interfaces"]:
key = interface_key(interface["name"])
record, method = matches[interface["name"]]
label = vlan_label(interface.get("vlans"))
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))
# Only written when VLANs are known, so manual labels survive
# routed ports and snapshots without configuration.
if label and (getattr(record, "label", "") or "") != label:
changes["label"] = label
if changes:
report["interfaces_updated"] += 1
texts = []
if "enabled" in changes:
texts.append("aktivieren" if changes["enabled"] else "deaktivieren")
if "label" in changes:
texts.append(f"Label „{label}“")
target = record.name if method == "name" else f"{record.name} ({interface['name']})"
report["changes"].append(f"Interface {target}: {', '.join(texts)}")
state = "aktivieren" if changes["enabled"] else "deaktivieren"
report["changes"].append(f"Interface {record.name}: {state}")
if not dry_run:
record.update(changes)
else:
@@ -1179,15 +814,13 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
"type": netbox_interface_type(interface),
"enabled": bool(interface.get("enabled", True)),
}
if label:
payload["label"] = label
if interface.get("description"):
payload["description"] = interface["description"][:200]
report["interfaces_created"] += 1
report["changes"].append(f"Interface {interface['name']} neu ({payload['type']})"
+ (f", Label „{label}“" if label else ""))
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
@@ -1238,7 +871,6 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
if create_cables:
lookup = _RemoteLookup(nb)
manual_devices = config.get("neighbor_devices") or {}
for neighbor in snapshot["neighbors"]:
label = f"{neighbor.get('local_port')} → {neighbor.get('system_name')} {neighbor.get('remote_port')}"
try:
@@ -1249,12 +881,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
if local is not None and getattr(local, "cable", None):
report["cables_skipped"] += 1
continue
if neighbor["local_port"] in manual_devices:
# 0 means "no device" was chosen in the review dialog.
chosen = int(manual_devices[neighbor["local_port"]] or 0)
remote_device = nb.dcim.devices.get(chosen) if chosen else None
else:
remote_device = lookup.device(neighbor)
remote_device = lookup.device(neighbor)
if not remote_device:
report["cables_skipped"] += 1
continue
+4 -40
View File
@@ -17,7 +17,6 @@ from netbox_sync.core.switches import (
PLATFORMS,
describe_snapshot,
discover_switch,
plan_switch_sync,
suggest_platform,
sync_snapshot_to_netbox,
)
@@ -25,7 +24,7 @@ from netbox_sync.core.virtualization import load_source
from netbox_sync.core.vm_sync import VMSyncEngine
from netbox_sync.ui import widgets
from netbox_sync.ui.client_dialogs import ClientPreviewDialog, ClientTargetDialog
from netbox_sync.ui.dialogs import SwitchMappingDialog, SyncPreviewDialog
from netbox_sync.ui.dialogs import SyncPreviewDialog
from netbox_sync.ui.tasks import area_log, logger
@@ -413,44 +412,8 @@ class Actions:
connect = self._connector()
log = area_log("switch")
def plan(ctx):
def preview(ctx):
nb = connect(ctx)
plans = []
for index, (switch, snapshot) in enumerate(items):
ctx.progress(index, len(items), switch["name"])
ctx.log(f"{switch['name']}: ordne Schnittstellen und Nachbarn zu …")
plans.append((switch, plan_switch_sync(nb, switch, snapshot)))
return nb, plans
def review(result):
nb, plans = result
self.state.set_netbox(nb, "ok", f"Verbunden · NetBox {nb.netbox_version}")
reviewable = [(switch, item) for switch, item in plans if not item["error"]]
needs_review = any(
any(entry["method"] not in ("name", "new") or (entry["method"] == "new" and entry["physical"])
for entry in item["interfaces"]) or (create_cables and item["neighbors"])
for _switch, item in reviewable)
def ask():
# Started after the planning task has finished, so the next
# task is not rejected as "still busy".
if needs_review:
dialog = SwitchMappingDialog(self.window, reviewable, create_cables)
if not dialog.exec():
return
stored = {switch["id"]: switch for switch in self.state.switches}
for switch, _snapshot in items:
choices = dialog.result.get(switch["id"])
if choices:
switch.update(choices)
if switch["id"] in stored:
stored[switch["id"]].update(choices)
self.state.touch()
self.tasks.run(lambda ctx: preview(ctx, nb), title="Änderungen berechnen", area="switch",
on_success=show_preview, on_error=self._netbox_failed)
QTimer.singleShot(0, ask)
def preview(ctx, nb):
reports = []
for index, (switch, snapshot) in enumerate(items):
ctx.progress(index, len(items), switch["name"])
@@ -460,6 +423,7 @@ class Actions:
def show_preview(result):
nb, reports = result
self.state.set_netbox(nb, "ok", f"Verbunden · NetBox {nb.netbox_version}")
def ask():
# Opened after the preview task has fully finished, so the
@@ -469,7 +433,7 @@ class Actions:
self._apply_switch_sync(nb, items, create_cables, log)
QTimer.singleShot(0, ask)
self.tasks.run(plan, title="Zuordnung ermitteln", area="switch", on_success=review,
self.tasks.run(preview, title="Änderungen berechnen", area="switch", on_success=show_preview,
on_error=self._netbox_failed)
def _apply_switch_sync(self, nb, items, create_cables, log):
+3 -144
View File
@@ -3,7 +3,7 @@
import uuid
from PySide6.QtCore import QThreadPool, Qt
from PySide6.QtGui import QColor, QGuiApplication
from PySide6.QtGui import QGuiApplication
from PySide6.QtWidgets import (
QButtonGroup,
QComboBox,
@@ -16,8 +16,6 @@ from PySide6.QtWidgets import (
QPlainTextEdit,
QPushButton,
QSpinBox,
QTableWidget,
QTableWidgetItem,
QTabWidget,
QTreeWidget,
QTreeWidgetItem,
@@ -26,7 +24,7 @@ from PySide6.QtWidgets import (
)
from netbox_sync.core.config import known_hosts_path
from netbox_sync.core.switches import MATCH_METHODS, PLATFORMS, forget_host_key
from netbox_sync.core.switches import PLATFORMS, forget_host_key
from netbox_sync.core.virtualization import test_source
from netbox_sync.ui.icons import icon
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
@@ -568,149 +566,10 @@ class SyncPreviewDialog(_Dialog):
self.root.addWidget(buttons)
class SwitchMappingDialog(_Dialog):
"""Review interface mapping and neighbor devices before computing changes.
``plans`` is a list of ``(switch, plan)`` from ``plan_switch_sync``. After
acceptance ``result`` maps switch IDs to ``interface_map`` and
``neighbor_devices`` to be stored in the profile.
"""
NEW = "\x00new"
def __init__(self, parent, plans, create_cables):
super().__init__(parent, "Zuordnung prüfen",
"Schnittstellen, deren Name auf dem Switch anders lautet als in NetBox, wurden automatisch "
"zugeordnet. Bitte prüfen und bei Bedarf korrigieren – die Auswahl wird im Profil gespeichert.",
width=820)
self.resize(980, 660)
self.plans = plans
self.result = None
tabs = QTabWidget()
# Interfaces --------------------------------------------------------
interface_page = QWidget()
interface_layout = QVBoxLayout(interface_page)
interface_layout.setContentsMargins(0, 12, 0, 0)
self.only_unclear = checkbox("Nur Schnittstellen ohne Namensgleichheit anzeigen", True)
interface_layout.addWidget(self.only_unclear)
self.interface_table = QTableWidget(0, 5)
self.interface_table.setHorizontalHeaderLabels(["Switch", "Schnittstelle (Switch)", "VLANs",
"NetBox-Schnittstelle", "Zuordnung"])
self.interface_rows = []
for switch, plan in plans:
vlans = {item["name"]: item["vlan_label"] for item in plan["interfaces"]}
choices = [("+ neu anlegen", self.NEW)] + [(name, name) for name in plan["netbox_interfaces"]]
for item in plan["interfaces"]:
if not item["physical"] and item["method"] in ("name", "new"):
continue
row = self.interface_table.rowCount()
self.interface_table.insertRow(row)
combo = QComboBox()
for text, data in choices:
combo.addItem(text, data)
combo.setCurrentIndex(max(0, combo.findData(item["netbox_name"] or self.NEW)))
for column, text in enumerate((switch["name"], item["name"], vlans.get(item["name"], ""))):
self.interface_table.setItem(row, column, QTableWidgetItem(text))
self.interface_table.setCellWidget(row, 3, combo)
method = QTableWidgetItem(MATCH_METHODS.get(item["method"], item["method"]))
if item["method"] in ("number", "order"):
method.setForeground(QColor(theme.color("warning")))
self.interface_table.setItem(row, 4, method)
self.interface_rows.append((row, switch, item, combo))
self._prepare_table(self.interface_table, (140, 170, 110, 220, 150))
interface_layout.addWidget(self.interface_table, 1)
unclear = sum(1 for _row, _switch, item, _combo in self.interface_rows if item["method"] != "name")
tabs.addTab(interface_page, f"Schnittstellen ({unclear} zu prüfen)")
self.only_unclear.toggled.connect(self._filter_interfaces)
self._filter_interfaces(True)
# Neighbors -----------------------------------------------------------
self.neighbor_rows = []
if create_cables:
neighbor_page = QWidget()
neighbor_layout = QVBoxLayout(neighbor_page)
neighbor_layout.setContentsMargins(0, 12, 0, 0)
scopes = sorted({plan["device_scope"] for _switch, plan in plans})
neighbor_layout.addWidget(label(
"Für jeden Nachbarn kann ein bestehendes NetBox-Gerät gewählt werden (Auswahl aus: "
f"{', '.join(scopes)}). Die Gegenstelle wird über den Portnamen gesucht; „kein Kabel“ "
"überspringt den Nachbarn.", muted=True, wrap=True))
self.neighbor_table = QTableWidget(0, 5)
self.neighbor_table.setHorizontalHeaderLabels(["Switch", "Lokaler Port", "Nachbar (LLDP/CDP)",
"Nachbar-Port", "NetBox-Gerät"])
for switch, plan in plans:
for neighbor in plan["neighbors"]:
row = self.neighbor_table.rowCount()
self.neighbor_table.insertRow(row)
combo = SearchableComboBox("Gerät suchen …")
combo.set_items([("– kein Kabel –", 0)] + [(device["name"], device["id"]) for device in plan["devices"]],
neighbor.get("device_id") or 0)
texts = (switch["name"], neighbor["local_port"], neighbor.get("system_name") or
neighbor.get("management_ip") or "", neighbor.get("remote_port") or "")
for column, text in enumerate(texts):
self.neighbor_table.setItem(row, column, QTableWidgetItem(text))
self.neighbor_table.setCellWidget(row, 4, combo)
self.neighbor_rows.append((switch, neighbor, combo))
self._prepare_table(self.neighbor_table, (140, 110, 220, 150, 260))
neighbor_layout.addWidget(self.neighbor_table, 1)
found = sum(1 for _switch, neighbor, _combo in self.neighbor_rows if neighbor.get("device_id"))
tabs.addTab(neighbor_page, f"Nachbarn ({found} von {len(self.neighbor_rows)} zugeordnet)")
self.root.addWidget(tabs, 1)
self.root.addWidget(self.error_banner)
buttons, _ok = form_dialog_buttons(self, "Weiter zur Vorschau")
self.root.addWidget(buttons)
@staticmethod
def _prepare_table(table, widths):
table.verticalHeader().hide()
table.setEditTriggers(QTableWidget.NoEditTriggers)
table.setSelectionMode(QTableWidget.NoSelection)
table.horizontalHeader().setStretchLastSection(True)
for column, width in enumerate(widths):
table.setColumnWidth(column, width)
def _filter_interfaces(self, only_unclear):
for row, _switch, item, _combo in self.interface_rows:
self.interface_table.setRowHidden(row, only_unclear and item["method"] == "name")
def accept(self):
result = {switch["id"]: {"interface_map": dict(switch.get("interface_map") or {}),
"neighbor_devices": dict(switch.get("neighbor_devices") or {})}
for switch, _plan in self.plans}
used = {}
for _row, switch, item, combo in self.interface_rows:
chosen = combo.currentData()
target = "" if chosen == self.NEW else chosen
mapping = result[switch["id"]]["interface_map"]
if target and (switch["id"], target) in used:
self.show_error(f"{switch['name']}: „{target}“ ist mehreren Schnittstellen zugeordnet "
f"({used[(switch['id'], target)]}, {item['name']}).")
return
if target:
used[(switch["id"], target)] = item["name"]
# Plain name matches stay automatic; everything else is remembered.
if item["method"] == "name" and target == item["netbox_name"]:
mapping.pop(item["name"], None)
else:
mapping[item["name"]] = target
for switch, neighbor, combo in self.neighbor_rows:
chosen = combo.valid_data()
chosen = int(chosen or 0)
stored = result[switch["id"]]["neighbor_devices"]
if neighbor["method"] == "auto" and chosen == (neighbor.get("device_id") or 0):
stored.pop(neighbor["local_port"], None)
else:
stored[neighbor["local_port"]] = chosen
self.result = result
super().accept()
class RawDataDialog(_Dialog):
SECTIONS = {
"interfaces": "Schnittstellen", "ipv4_interfaces": "IPv4", "ipv6_interfaces": "IPv6",
"neighbors": "LLDP", "cdp_neighbors": "CDP", "vlan_config": "VLAN-Konfiguration", "lldp_status": "LLDP-Status",
"neighbors": "LLDP", "cdp_neighbors": "CDP", "lldp_status": "LLDP-Status",
}
def __init__(self, parent, items, selected_id=None):
+1 -2
View File
@@ -4,7 +4,7 @@ import uuid
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QComboBox, QHBoxLayout, QMenu, QSplitter, QStackedWidget
from netbox_sync.core.switches import PLATFORMS, vlan_label
from netbox_sync.core.switches import PLATFORMS
from netbox_sync.ui import widgets
from netbox_sync.ui.dialogs import AddSwitchesDialog, RawDataDialog, SwitchDialog
from netbox_sync.ui.icons import icon
@@ -108,7 +108,6 @@ class SwitchesPage(Page):
dot=lambda row: "success" if row["connected"] else ("text_faint" if row["enabled"] else "danger")),
Column("speed", "Geschwindigkeit", 115, value=lambda row: _speed(row.get("speed_mbps")),
sort=lambda row: row.get("speed_mbps") or 0),
Column("vlans", "VLANs", 110, value=lambda row: vlan_label(row.get("vlans"))),
Column("ips", "IP-Adressen", 160, value=lambda row: ", ".join(row.get("ip_addresses", []))),
Column("neighbor", "Nachbar", 170, value=lambda row: (row.get("neighbor") or {}).get("system_name", "")),
Column("remote_port", "Nachbar-Port", 110, value=lambda row: (row.get("neighbor") or {}).get("remote_port", "")),
+1 -62
View File
@@ -2,7 +2,7 @@ from types import SimpleNamespace
from fake_netbox import FakeNetBox, Record
from netbox_sync.core.switches import build_snapshot, match_interfaces, plan_switch_sync, sync_snapshot_to_netbox
from netbox_sync.core.switches import build_snapshot, sync_snapshot_to_netbox
from test_switches import COMWARE_BRIEF, COMWARE_LLDP
@@ -63,64 +63,3 @@ def test_offline_switch_is_resolved_by_name():
missing = sync_snapshot_to_netbox(nb, {"id": "s", "name": "unbekannt"}, snapshot, dry_run=True)
assert missing["errors"] == ["NetBox-Gerät „unbekannt“ nicht gefunden"]
def _numbered_setup():
"""NetBox device type with ports "1" … "3", switch reports "1/1/x"."""
nb = FakeNetBox()
group = SimpleNamespace(id=3, name="Kunde")
nb.tenancy.tenants.records.append(Record(nb.tenancy.tenants, id=7, name="Muster", group=group))
nb.dcim.devices.records += [
Record(nb.dcim.devices, id=1, name="access-01", tenant=SimpleNamespace(id=7), tenant_group=group),
Record(nb.dcim.devices, id=2, name="server-01", tenant=SimpleNamespace(id=7), tenant_group=group),
Record(nb.dcim.devices, id=3, name="fremd", tenant=None, tenant_group=None),
]
for index, name in enumerate(("1", "2", "3"), start=1):
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=index, name=name, device=SimpleNamespace(id=1),
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None,
label=""))
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=20, name="eth0", device=SimpleNamespace(id=2),
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None))
interfaces = [
{"name": f"1/1/{number}", "enabled": True, "connected": True, "media": "1GbT", "speed_mbps": 1000,
"ip_addresses": [], "vlans": {"untagged": [10 * number], "tagged": [], "tagged_all": False}}
for number in (1, 2, 3)
]
neighbor = {"local_port": "1/1/2", "system_name": "unbekannt", "remote_port": "eth0", "port_description": "",
"management_ip": "", "protocol": "LLDP"}
snapshot = {"interfaces": interfaces, "neighbors": [neighbor]}
return nb, {"id": "s", "name": "access-01", "device_id": 1}, snapshot
def test_ports_are_mapped_by_number_and_labelled_with_vlans():
nb, switch, snapshot = _numbered_setup()
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert report["errors"] == [] and report["interfaces_created"] == 0
assert sorted(nb.dcim.interfaces.updates) == [(1, {"label": "10"}), (2, {"label": "20"}), (3, {"label": "30"})]
def test_ports_are_mapped_by_order_and_manual_choice_wins():
nb, switch, snapshot = _numbered_setup()
for item, name in zip(snapshot["interfaces"], ("1/0/1", "1/0/2", "2/0/1")):
item["name"] = name # "2/0/1" breaks the unique port numbers
matches = match_interfaces(snapshot["interfaces"], nb.dcim.interfaces.filter(device_id=1))
assert {name: (record.name, method) for name, (record, method) in matches.items()} == {
"1/0/1": ("1", "order"), "1/0/2": ("2", "number"), "2/0/1": ("3", "order")}
manual = match_interfaces(snapshot["interfaces"], nb.dcim.interfaces.filter(device_id=1), {"2/0/1": ""})
assert manual["2/0/1"] == (None, "new")
def test_plan_offers_tenant_group_devices_and_manual_neighbor_creates_cable():
nb, switch, snapshot = _numbered_setup()
plan = plan_switch_sync(nb, switch, snapshot)
assert plan["device_scope"] == "Mandantengruppe Kunde"
assert [device["name"] for device in plan["devices"]] == ["server-01"]
assert plan["neighbors"][0]["device_id"] is None
assert {item["name"]: item["method"] for item in plan["interfaces"]}["1/1/1"] == "number"
report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True)
assert report["cables_created"] == 0
switch["neighbor_devices"] = {"1/1/2": 2}
report = sync_snapshot_to_netbox(nb, switch, snapshot)
cable = nb.dcim.cables.created[0]
assert cable["a_terminations"][0]["object_id"] == 2 and cable["b_terminations"][0]["object_id"] == 20
-100
View File
@@ -201,103 +201,3 @@ def test_speed_parsing():
assert switches.speed_mbps("1000FDx") == 1000
assert switches.speed_mbps("10GigFD") == 10000
assert switches.speed_mbps("UP 1G(a) F(a)") == 1000
AOS_CONFIG = """
vlan 1
name "DEFAULT_VLAN"
untagged 1,3-4,Trk1
no untagged 2
exit
vlan 10
name "Server"
untagged 2
tagged 49,Trk1
exit
vlan 20
tagged 1/1-1/2,49
exit
"""
CX_CONFIG = """
interface 1/1/1
no shutdown
no routing
vlan access 10
interface 1/1/2
no routing
vlan trunk native 1
vlan trunk allowed 1,20-22
interface 1/1/3
no routing
interface 1/1/49
ip address 10.0.0.1/24
interface lag 1
no routing
vlan trunk native 5 tag
vlan trunk allowed all
"""
COMWARE_CONFIG = """
#
interface GigabitEthernet1/0/1
port link-mode bridge
port access vlan 10
#
interface GigabitEthernet1/0/2
port link-mode bridge
#
interface GigabitEthernet1/0/3
port link-type hybrid
port hybrid vlan 30 40 tagged
port hybrid vlan 1 untagged
#
interface Ten-GigabitEthernet1/0/49
port link-mode bridge
port link-type trunk
undo port trunk permit vlan 1
port trunk permit vlan 10 20 to 22
port trunk pvid vlan 10
#
interface Vlan-interface10
ip address 10.0.0.1 255.255.255.0
#
"""
def test_parse_vlans_aruba_aos():
vlans = switches.parse_vlans(AOS_CONFIG, "aruba_aos")
assert vlans[interface_key("1")] == {"untagged": [1], "tagged": [], "tagged_all": False}
assert vlans[interface_key("2")]["untagged"] == [10]
assert vlans[interface_key("49")] == {"untagged": [], "tagged": [10, 20], "tagged_all": False}
assert vlans[interface_key("Trk1")] == {"untagged": [1], "tagged": [10], "tagged_all": False}
assert vlans[interface_key("1/2")]["tagged"] == [20]
def test_parse_vlans_aruba_cx():
vlans = switches.parse_vlans(CX_CONFIG, "aruba_cx")
assert switches.vlan_label(vlans[interface_key("1/1/1")]) == "10"
assert switches.vlan_label(vlans[interface_key("1/1/2")]) == "1,20-22"
assert switches.vlan_label(vlans[interface_key("1/1/3")]) == "1"
assert interface_key("1/1/49") not in vlans
assert switches.vlan_label(vlans[interface_key("lag1")]) == "all"
def test_parse_vlans_comware():
vlans = switches.parse_vlans(COMWARE_CONFIG, "hpe_comware")
assert switches.vlan_label(vlans[interface_key("GE1/0/1")]) == "10"
assert switches.vlan_label(vlans[interface_key("GE1/0/2")]) == "1"
assert vlans[interface_key("GE1/0/3")] == {"untagged": [1], "tagged": [30, 40], "tagged_all": False}
assert vlans[interface_key("XGE1/0/49")] == {"untagged": [10], "tagged": [20, 21, 22], "tagged_all": False}
assert interface_key("Vlan-interface10") not in vlans
def test_vlan_label_is_short_and_snapshot_hides_config():
many = {"untagged": [], "tagged": list(range(100, 400, 2)), "tagged_all": False}
assert len(switches.vlan_label(many)) <= 64 and switches.vlan_label(many).endswith("…")
snapshot = build_snapshot({"interfaces": COMWARE_BRIEF, "neighbors": "",
"config": COMWARE_CONFIG + "\n local-user admin\n password hash $h$secret\n"},
"hpe_comware")
by_name = {item["name"]: item for item in snapshot["interfaces"]}
assert by_name["GigabitEthernet1/0/1"]["vlans"]["untagged"] == [10]
assert "config" not in snapshot["raw"] and "secret" not in snapshot["raw"]["vlan_config"]