Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
535a5e9699 | ||
|
|
83787142d3 | ||
|
|
7b5dd4bc9b | ||
|
|
39a29b9230 | ||
|
|
f249c3e1c9 | ||
|
|
22ba46fca3 | ||
|
|
dc39c8f4ec | ||
|
|
28c6654f6b | ||
|
|
799a5aa007 | ||
|
|
d10190b7bc | ||
|
|
c42cedd655 |
No files matched your search
@@ -10,3 +10,4 @@ output/
|
||||
# Lokale Konfigurationen und Zugangsdaten
|
||||
config.json
|
||||
*.tmp
|
||||
.gitea-token
|
||||
+21
-15
@@ -2,10 +2,16 @@
|
||||
# Build: python -m PyInstaller --noconfirm --clean NetBoxSynchronizer.spec
|
||||
# Produces a one-folder build in dist/NetBoxSynchronizer that the Inno Setup
|
||||
# installer (installer/NetBoxSynchronizer.iss) packages.
|
||||
#
|
||||
# Portable: python -m PyInstaller --noconfirm --clean NetBoxSynchronizer.spec -- --portable
|
||||
# Produces a single self-extracting "NetBox VM Import.exe".
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
PORTABLE = "--portable" in sys.argv
|
||||
|
||||
from PyInstaller.utils.win32.versioninfo import (
|
||||
FixedFileInfo,
|
||||
StringFileInfo,
|
||||
@@ -66,12 +72,7 @@ a.datas = [
|
||||
|
||||
pyz = PYZ(a.pure)
|
||||
|
||||
exe = EXE(
|
||||
pyz,
|
||||
a.scripts,
|
||||
[],
|
||||
exclude_binaries=True,
|
||||
name="NetBoxSynchronizer",
|
||||
EXE_OPTIONS = dict(
|
||||
debug=False,
|
||||
bootloader_ignore_signals=False,
|
||||
strip=False,
|
||||
@@ -86,12 +87,17 @@ exe = EXE(
|
||||
version=version_info,
|
||||
)
|
||||
|
||||
coll = COLLECT(
|
||||
exe,
|
||||
a.binaries,
|
||||
a.datas,
|
||||
strip=False,
|
||||
upx=False,
|
||||
upx_exclude=[],
|
||||
name="NetBoxSynchronizer",
|
||||
)
|
||||
if PORTABLE:
|
||||
exe = EXE(pyz, a.scripts, a.binaries, a.datas, [], name="NetBox VM Import", upx_exclude=[],
|
||||
runtime_tmpdir=None, **EXE_OPTIONS)
|
||||
else:
|
||||
exe = EXE(pyz, a.scripts, [], exclude_binaries=True, name="NetBoxSynchronizer", **EXE_OPTIONS)
|
||||
coll = COLLECT(
|
||||
exe,
|
||||
a.binaries,
|
||||
a.datas,
|
||||
strip=False,
|
||||
upx=False,
|
||||
upx_exclude=[],
|
||||
name="NetBoxSynchronizer",
|
||||
)
|
||||
@@ -1,108 +1,159 @@
|
||||
# NetBox Synchronizer
|
||||
|
||||
Windows-Desktopanwendung, die virtuelle Maschinen aus VMware vSphere und Proxmox VE, HPE-/Aruba-Switche
|
||||
sowie Windows-Clients in NetBox dokumentiert.
|
||||
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
|
||||
- Networks and VLANs in the same review: per network the VRF (global, a tenant
|
||||
VRF or a new one) and whether a missing prefix is created; missing VLANs
|
||||
(named from the switch configuration) are only created when ticked. Existing
|
||||
VLANs are assigned to the ports (802.1Q mode, untagged/tagged)
|
||||
- Tenant required: a switch without tenant in NetBox is refused; every created
|
||||
IP address, prefix, VRF, VLAN and cable gets the switch's tenant
|
||||
- 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
|
||||
|
||||
## Installation
|
||||
|
||||
`NetBoxSynchronizer-Setup-<version>.exe` ausführen. Der Installer
|
||||
Run `NetBoxSynchronizer-Setup-<version>.exe`. The installer
|
||||
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
Bestehende Kundenprofile der Vorgängerversion („NetBox VM Import“) werden automatisch übernommen.
|
||||
Customer profiles of the predecessor ("NetBox VM Import") are migrated
|
||||
automatically.
|
||||
|
||||
## 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
|
||||
## Development
|
||||
|
||||
```powershell
|
||||
py -3 -m venv .venv
|
||||
.\.venv\Scripts\Activate.ps1
|
||||
pip install -r requirements-dev.txt
|
||||
python main.py # Anwendung starten
|
||||
python -m pytest # Tests
|
||||
python main.py # start the application
|
||||
python -m pytest # tests
|
||||
```
|
||||
|
||||
Projektstruktur:
|
||||
Project layout:
|
||||
|
||||
```
|
||||
netbox_sync/
|
||||
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)
|
||||
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)
|
||||
```
|
||||
|
||||
## Build & Installer
|
||||
## Build & installer
|
||||
|
||||
Voraussetzung für den Installer ist [Inno Setup 6](https://jrsoftware.org/isinfo.php)
|
||||
The installer requires [Inno Setup 6](https://jrsoftware.org/isinfo.php)
|
||||
(`winget install JRSoftware.InnoSetup`).
|
||||
|
||||
```powershell
|
||||
.\build.ps1 # Tests, PyInstaller-Build und Installer
|
||||
.\build.ps1 -SkipInstaller # nur dist\NetBoxSynchronizer\
|
||||
.\build.ps1 # tests, PyInstaller build and installer
|
||||
.\build.ps1 -SkipInstaller # only dist\NetBoxSynchronizer\
|
||||
```
|
||||
|
||||
Ergebnis: `dist\installer\NetBoxSynchronizer-Setup-<version>.exe`. Die Version steht in `netbox_sync/__init__.py`.
|
||||
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`.
|
||||
@@ -1,15 +1,17 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Baut NetBox Synchronizer: Tests, PyInstaller-Build und Inno-Setup-Installer.
|
||||
Baut NetBox Synchronizer: Tests, PyInstaller-Build, Inno-Setup-Installer und portable EXE.
|
||||
|
||||
.EXAMPLE
|
||||
.\build.ps1 # alles
|
||||
.\build.ps1 -SkipInstaller # nur dist\NetBoxSynchronizer\
|
||||
.\build.ps1 -SkipInstaller # nur dist\NetBoxSynchronizer\ (und portable EXE)
|
||||
.\build.ps1 -SkipPortable # ohne dist\portable\NetBox VM Import.exe
|
||||
.\build.ps1 -SkipTests
|
||||
#>
|
||||
param(
|
||||
[switch]$SkipTests,
|
||||
[switch]$SkipInstaller,
|
||||
[switch]$SkipPortable,
|
||||
[string]$InnoSetupCompiler
|
||||
)
|
||||
|
||||
@@ -38,6 +40,13 @@ Write-Host "Baue NetBox Synchronizer $version …" -ForegroundColor Cyan
|
||||
& $python -m PyInstaller --noconfirm --clean --log-level WARN NetBoxSynchronizer.spec
|
||||
if ($LASTEXITCODE) { throw "PyInstaller fehlgeschlagen." }
|
||||
|
||||
if (-not $SkipPortable) {
|
||||
Write-Host "Baue portable EXE …" -ForegroundColor Cyan
|
||||
& $python -m PyInstaller --noconfirm --clean --log-level WARN --distpath dist\portable --workpath build\portable NetBoxSynchronizer.spec -- --portable
|
||||
if ($LASTEXITCODE) { throw "PyInstaller (portabel) fehlgeschlagen." }
|
||||
Write-Host "Fertig: dist\portable\NetBox VM Import.exe" -ForegroundColor Green
|
||||
}
|
||||
|
||||
if ($SkipInstaller) {
|
||||
Write-Host "Fertig: dist\NetBoxSynchronizer\NetBoxSynchronizer.exe" -ForegroundColor Green
|
||||
return
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
; Inno Setup 6 script for NetBox Synchronizer.
|
||||
; Built by build.ps1, which passes the version: ISCC /DAppVersion=4.1.0 NetBoxSynchronizer.iss
|
||||
; Built by build.ps1, which passes the version: ISCC /DAppVersion=4.1.1 NetBoxSynchronizer.iss
|
||||
|
||||
#define AppName "NetBox Synchronizer"
|
||||
#ifndef AppVersion
|
||||
#define AppVersion "4.1.0"
|
||||
#define AppVersion "4.4.0"
|
||||
#endif
|
||||
#define AppPublisher "Louis-Alexander Kerst"
|
||||
#define AppExeName "NetBoxSynchronizer.exe"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
|
||||
|
||||
APP_NAME = "NetBox Synchronizer"
|
||||
APP_VERSION = "4.1.0"
|
||||
APP_VERSION = "4.4.0"
|
||||
APP_PUBLISHER = "Louis-Alexander Kerst"
|
||||
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
|
||||
|
||||
|
||||
@@ -231,12 +231,12 @@ class ClientSyncEngine:
|
||||
if not dry_run:
|
||||
device.update(updates)
|
||||
if interfaces:
|
||||
changes.extend(self._sync_interfaces(device, client, dry_run, report))
|
||||
changes.extend(self._sync_interfaces(device, client, tenant_id, dry_run, report))
|
||||
if not changes:
|
||||
report["devices_unchanged"] += 1
|
||||
return changes
|
||||
|
||||
def _sync_interfaces(self, device, client, dry_run, report):
|
||||
def _sync_interfaces(self, device, client, tenant_id, dry_run, report):
|
||||
changes = []
|
||||
existing = {str(item.name).casefold(): item for item in self.nb.dcim.interfaces.filter(device_id=device.id)}
|
||||
primary = None
|
||||
@@ -257,7 +257,7 @@ class ClientSyncEngine:
|
||||
if record is not None and mac and not dry_run:
|
||||
assign_mac(self.nb, record, mac, "dcim.interface")
|
||||
for address in interface.get("ips", []):
|
||||
ip, change = self._sync_ip(address, record, interface.get("dhcp"), dry_run, report)
|
||||
ip, change = self._sync_ip(address, record, interface.get("dhcp"), tenant_id, dry_run, report)
|
||||
if change:
|
||||
changes.append(change)
|
||||
if ip is not None and primary is None and ":" not in address and interface.get("gateway"):
|
||||
@@ -266,7 +266,7 @@ class ClientSyncEngine:
|
||||
device.update({"primary_ip4": primary.id})
|
||||
return changes
|
||||
|
||||
def _sync_ip(self, address, interface, dhcp, dry_run, report):
|
||||
def _sync_ip(self, address, interface, dhcp, tenant_id, dry_run, report):
|
||||
matches = [ip for ip in self.nb.ipam.ip_addresses.filter(address=address.split("/")[0])
|
||||
if related_id(ip, "vrf") is None]
|
||||
if not matches:
|
||||
@@ -276,6 +276,7 @@ class ClientSyncEngine:
|
||||
ip = self.nb.ipam.ip_addresses.create({
|
||||
"address": address, "status": "dhcp" if dhcp else "active",
|
||||
"assigned_object_type": "dcim.interface", "assigned_object_id": interface.id,
|
||||
**({"tenant": tenant_id} if tenant_id else {}),
|
||||
})
|
||||
return ip, f"IP-Adresse {address} anlegen"
|
||||
ip = matches[0]
|
||||
|
||||
+61
-264
@@ -1,21 +1,16 @@
|
||||
"""Agentless inventory of Windows clients via WMI/CIM over WinRM.
|
||||
|
||||
Targets come from Active Directory (computer objects) or from a list of host
|
||||
names, IP addresses and ranges. Each reachable client is queried with
|
||||
``Get-CimInstance`` through Windows PowerShell, so authentication uses the
|
||||
Windows stack (Kerberos/Negotiate) – either the signed-in user or credentials
|
||||
from the Windows logon prompt. Passwords are handed to PowerShell via stdin and
|
||||
never appear on a command line or on disk.
|
||||
names, IP addresses and ranges. Each reachable client is queried in-process
|
||||
through the Windows WSMan COM API (see :mod:`netbox_sync.core.wsman`), so
|
||||
authentication uses Kerberos/Negotiate with either the signed-in user or
|
||||
credentials from the Windows logon prompt. No helper processes are started.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
@@ -134,193 +129,6 @@ def resolves(host):
|
||||
return False
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# PowerShell
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def powershell_path():
|
||||
root = os.environ.get("SystemRoot", r"C:\Windows")
|
||||
candidate = os.path.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
|
||||
return candidate if os.path.exists(candidate) else (shutil.which("powershell") or "powershell.exe")
|
||||
|
||||
|
||||
def _start_powershell(script, payload):
|
||||
if sys.platform != "win32":
|
||||
raise ClientScanError("Die Abfrage von Windows-Clients ist nur unter Windows verfügbar.")
|
||||
encoded = base64.b64encode(script.encode("utf-16-le")).decode("ascii")
|
||||
process = subprocess.Popen( # noqa: S603 - fixed executable, script passed encoded
|
||||
[powershell_path(), "-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",
|
||||
"-EncodedCommand", encoded],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
||||
)
|
||||
process.stdin.write(json.dumps(payload).encode("utf-8"))
|
||||
process.stdin.close()
|
||||
return process
|
||||
|
||||
|
||||
def _credential_payload(credential):
|
||||
if credential is None:
|
||||
return {"user": "", "password": ""}
|
||||
return {"user": credential.username, "password": credential.password}
|
||||
|
||||
|
||||
_PS_PROLOG = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false
|
||||
$job = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
||||
$cred = $null
|
||||
if ($job.user) {
|
||||
$secure = ConvertTo-SecureString $job.password -AsPlainText -Force
|
||||
$cred = New-Object System.Management.Automation.PSCredential($job.user, $secure)
|
||||
}
|
||||
function Emit($value) { [Console]::Out.WriteLine(($value | ConvertTo-Json -Compress -Depth 6)); [Console]::Out.Flush() }
|
||||
function Text($value) { if ($null -eq $value) { '' } else { ([string]$value).Trim() } }
|
||||
function Stamp($value) { if ($value -is [datetime]) { $value.ToString('s') } else { '' } }
|
||||
"""
|
||||
|
||||
_SCAN_SCRIPT = _PS_PROLOG + r"""
|
||||
if ($job.ssl) { $option = New-CimSessionOption -UseSsl } else { $option = New-CimSessionOption -Protocol Wsman }
|
||||
foreach ($target in $job.hosts) {
|
||||
$result = [ordered]@{ host = $target; ok = $false }
|
||||
$session = $null
|
||||
try {
|
||||
$params = @{ ComputerName = $target; SessionOption = $option; OperationTimeoutSec = [int]$job.timeout }
|
||||
if ($job.port) { $params.Port = [int]$job.port }
|
||||
if ($cred) { $params.Credential = $cred; $params.Authentication = 'Negotiate' }
|
||||
$session = New-CimSession @params
|
||||
$cs = Get-CimInstance -CimSession $session -ClassName Win32_ComputerSystem
|
||||
$os = Get-CimInstance -CimSession $session -ClassName Win32_OperatingSystem
|
||||
$bios = Get-CimInstance -CimSession $session -ClassName Win32_BIOS
|
||||
$product = Get-CimInstance -CimSession $session -ClassName Win32_ComputerSystemProduct
|
||||
$enclosure = @(Get-CimInstance -CimSession $session -ClassName Win32_SystemEnclosure) | Select-Object -First 1
|
||||
$cpu = @(Get-CimInstance -CimSession $session -ClassName Win32_Processor)
|
||||
$adapters = @{}
|
||||
foreach ($adapter in @(Get-CimInstance -CimSession $session -ClassName Win32_NetworkAdapter -Filter 'PhysicalAdapter = TRUE')) {
|
||||
$adapters[[int]$adapter.InterfaceIndex] = $adapter
|
||||
}
|
||||
$nics = @()
|
||||
foreach ($config in @(Get-CimInstance -CimSession $session -ClassName Win32_NetworkAdapterConfiguration -Filter 'IPEnabled = TRUE')) {
|
||||
$adapter = $adapters[[int]$config.InterfaceIndex]
|
||||
$nics += [ordered]@{
|
||||
name = Text $adapter.NetConnectionID
|
||||
description = Text $config.Description
|
||||
mac = Text $config.MACAddress
|
||||
ips = @($config.IPAddress | ForEach-Object { Text $_ })
|
||||
masks = @($config.IPSubnet | ForEach-Object { Text $_ })
|
||||
gateway = @($config.DefaultIPGateway | ForEach-Object { Text $_ })
|
||||
dhcp = [bool]$config.DHCPEnabled
|
||||
physical = [bool]($null -ne $adapter)
|
||||
speed = [int64]$adapter.Speed
|
||||
}
|
||||
}
|
||||
$displayVersion = ''
|
||||
try {
|
||||
$reg = Invoke-CimMethod -CimSession $session -Namespace root/default -ClassName StdRegProv -MethodName GetStringValue -Arguments @{ hDefKey = [uint32]2147483650; sSubKeyName = 'SOFTWARE\Microsoft\Windows NT\CurrentVersion'; sValueName = 'DisplayVersion' }
|
||||
$displayVersion = Text $reg.sValue
|
||||
} catch { }
|
||||
$result.ok = $true
|
||||
$result.name = Text $cs.Name
|
||||
$result.domain = Text $cs.Domain
|
||||
$result.part_of_domain = [bool]$cs.PartOfDomain
|
||||
$result.manufacturer = Text $cs.Manufacturer
|
||||
$result.model = Text $cs.Model
|
||||
$result.product_name = Text $product.Name
|
||||
$result.product_version = Text $product.Version
|
||||
$result.serial = Text $bios.SerialNumber
|
||||
$result.bios_version = Text $bios.SMBIOSBIOSVersion
|
||||
$result.chassis = @($enclosure.ChassisTypes | ForEach-Object { [int]$_ })
|
||||
$result.user = Text $cs.UserName
|
||||
$result.memory = [int64]$cs.TotalPhysicalMemory
|
||||
$result.cpu = Text ($cpu | Select-Object -First 1).Name
|
||||
$result.cores = [int](($cpu | Measure-Object -Property NumberOfCores -Sum).Sum)
|
||||
$result.os = Text $os.Caption
|
||||
$result.os_version = Text $os.Version
|
||||
$result.os_build = Text $os.BuildNumber
|
||||
$result.os_display_version = $displayVersion
|
||||
$result.os_architecture = Text $os.OSArchitecture
|
||||
$result.installed = Stamp $os.InstallDate
|
||||
$result.last_boot = Stamp $os.LastBootUpTime
|
||||
$result.nics = $nics
|
||||
} catch {
|
||||
$result.error = Text $_.Exception.Message
|
||||
} finally {
|
||||
if ($session) { Remove-CimSession $session -ErrorAction SilentlyContinue }
|
||||
}
|
||||
Emit $result
|
||||
}
|
||||
"""
|
||||
|
||||
_AD_SCRIPT = _PS_PROLOG + r"""
|
||||
try {
|
||||
if ($cred) {
|
||||
$plain = $cred.GetNetworkCredential()
|
||||
$root = New-Object System.DirectoryServices.DirectoryEntry($job.path, $cred.UserName, $plain.Password)
|
||||
} elseif ($job.path) {
|
||||
$root = New-Object System.DirectoryServices.DirectoryEntry($job.path)
|
||||
} else {
|
||||
$root = New-Object System.DirectoryServices.DirectoryEntry
|
||||
}
|
||||
$searcher = New-Object System.DirectoryServices.DirectorySearcher($root)
|
||||
$searcher.Filter = $job.filter
|
||||
$searcher.PageSize = 1000
|
||||
foreach ($name in 'name', 'dnshostname', 'operatingsystem', 'operatingsystemversion', 'lastlogontimestamp',
|
||||
'distinguishedname', 'description', 'useraccountcontrol') {
|
||||
[void]$searcher.PropertiesToLoad.Add($name)
|
||||
}
|
||||
foreach ($item in $searcher.FindAll()) {
|
||||
$p = $item.Properties
|
||||
Emit ([ordered]@{
|
||||
name = Text ($p['name'] | Select-Object -First 1)
|
||||
dns = Text ($p['dnshostname'] | Select-Object -First 1)
|
||||
os = Text ($p['operatingsystem'] | Select-Object -First 1)
|
||||
os_version = Text ($p['operatingsystemversion'] | Select-Object -First 1)
|
||||
last_logon = [int64]($p['lastlogontimestamp'] | Select-Object -First 1)
|
||||
dn = Text ($p['distinguishedname'] | Select-Object -First 1)
|
||||
description = Text ($p['description'] | Select-Object -First 1)
|
||||
disabled = [bool](([int]($p['useraccountcontrol'] | Select-Object -First 1)) -band 2)
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
Emit ([ordered]@{ fatal = Text $_.Exception.Message })
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def _read_lines(process, cancelled):
|
||||
"""Yield parsed JSON lines from a PowerShell process, killing it on cancel."""
|
||||
try:
|
||||
for raw in process.stdout:
|
||||
if cancelled():
|
||||
process.kill()
|
||||
return
|
||||
line = raw.decode("utf-8", errors="replace").strip()
|
||||
if line.startswith("{"):
|
||||
try:
|
||||
yield json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
try:
|
||||
process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
|
||||
|
||||
def _stderr(process):
|
||||
try:
|
||||
text = process.stderr.read().decode("utf-8", errors="replace").strip()
|
||||
except (OSError, ValueError):
|
||||
return ""
|
||||
if text.startswith("#< CLIXML"):
|
||||
parts = re.findall(r'<S S="Error">(.*?)</S>', text, re.S)
|
||||
text = "".join(parts).replace("_x000D__x000A_", "\n").replace("<", "<").replace(">", ">")
|
||||
text = text.replace(""", '"').replace("&", "&")
|
||||
return text.strip()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Active Directory
|
||||
# --------------------------------------------------------------------------
|
||||
@@ -334,17 +142,24 @@ def ad_filter(options):
|
||||
return "(&" + "".join(parts) + ")"
|
||||
|
||||
|
||||
def ad_path(options, credential):
|
||||
def domain_base(domain):
|
||||
return ",".join(f"DC={part}" for part in domain.strip(".").split(".") if part)
|
||||
|
||||
|
||||
def ad_location(options):
|
||||
"""``server/base`` for the LDAP query; defaults to the domain of the signed-in user."""
|
||||
server = (options.get("ad_server") or "").strip().strip("/")
|
||||
base = (options.get("ad_base") or "").strip()
|
||||
if not server and not base and credential is None:
|
||||
return ""
|
||||
if not server and credential is not None:
|
||||
server = os.environ.get("USERDNSDOMAIN", "")
|
||||
if not server and not base:
|
||||
raise ClientScanError("Dieser Rechner ist keiner Domäne beigetreten. Bitte unter „Domäne / DC“ die Domäne "
|
||||
"angeben, z. B. firma.local.")
|
||||
return "LDAP://" + "/".join(part for part in (server, base) if part)
|
||||
if server and not base:
|
||||
# LDAP://server binds to the default naming context of that domain or DC.
|
||||
return server
|
||||
if not base:
|
||||
domain = os.environ.get("USERDNSDOMAIN", "")
|
||||
if not domain:
|
||||
raise ClientScanError("Dieser Rechner ist keiner Domäne beigetreten. Bitte unter „Domäne / DC“ die "
|
||||
"Domäne angeben, z. B. firma.local.")
|
||||
base = domain_base(domain)
|
||||
return "/".join(part for part in (server, base) if part)
|
||||
|
||||
|
||||
def filetime_to_unix(value):
|
||||
@@ -355,15 +170,21 @@ def filetime_to_unix(value):
|
||||
|
||||
def query_ad(options, credential=None, log=lambda *_args: None, cancelled=lambda: False, now=None):
|
||||
"""Return computer objects from Active Directory as client rows (not yet scanned)."""
|
||||
payload = dict(_credential_payload(credential), path=ad_path(options, credential), filter=ad_filter(options))
|
||||
log(f"Suche Computerkonten im Active Directory{' unter ' + payload['path'] if payload['path'] else ''} …")
|
||||
process = _start_powershell(_AD_SCRIPT, payload)
|
||||
from netbox_sync.core import wsman
|
||||
|
||||
location = ad_location(options)
|
||||
log(f"Suche Computerkonten im Active Directory (LDAP://{location}) …")
|
||||
try:
|
||||
with wsman.com_thread():
|
||||
items = wsman.search_ad(location, ad_filter(options), credential)
|
||||
except wsman.WSManError as error:
|
||||
raise ClientScanError(f"Active-Directory-Abfrage fehlgeschlagen: {friendly_error(str(error))}") from error
|
||||
max_age = int(options.get("max_age_days") or 0)
|
||||
limit = ((now or time.time()) - max_age * 86400) if max_age else None
|
||||
rows, stale = [], 0
|
||||
for item in _read_lines(process, cancelled):
|
||||
if "fatal" in item:
|
||||
raise ClientScanError(f"Active-Directory-Abfrage fehlgeschlagen: {friendly_error(item['fatal'])}")
|
||||
for item in items:
|
||||
if cancelled():
|
||||
break
|
||||
if not item.get("name"):
|
||||
continue
|
||||
last_logon = filetime_to_unix(item.get("last_logon"))
|
||||
@@ -375,10 +196,6 @@ def query_ad(options, credential=None, log=lambda *_args: None, cancelled=lambda
|
||||
"os_version": item.get("os_version", ""), "last_logon": last_logon, "dn": item.get("dn", ""),
|
||||
"description": item.get("description", ""), "disabled": bool(item.get("disabled")),
|
||||
}))
|
||||
if process.returncode not in (0, None) and not rows:
|
||||
problem = _stderr(process)
|
||||
if problem:
|
||||
raise ClientScanError(f"Active-Directory-Abfrage fehlgeschlagen: {problem}")
|
||||
log(f"Active Directory: {len(rows)} Computer" + (f" ({stale} ohne Anmeldung seit {max_age} Tagen ausgelassen)"
|
||||
if stale else ""), "success")
|
||||
return rows
|
||||
@@ -420,7 +237,7 @@ def chassis_name(types):
|
||||
|
||||
|
||||
def apply_scan(row, raw, now=None):
|
||||
"""Merge the raw PowerShell result into a result row."""
|
||||
"""Merge the raw WinRM result into a result row."""
|
||||
row = dict(row)
|
||||
row["scanned_at"] = now or time.time()
|
||||
if not raw.get("ok"):
|
||||
@@ -540,65 +357,45 @@ def friendly_error(text):
|
||||
# Scan
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def _chunks(items, count):
|
||||
count = max(1, min(count, len(items)))
|
||||
return [items[index::count] for index in range(count)]
|
||||
|
||||
|
||||
def scan_clients(rows, credential=None, use_ssl=False, parallel=8, timeout=30, log=lambda *_args: None,
|
||||
on_result=lambda _row: None, cancelled=lambda: False):
|
||||
on_result=lambda _row: None, cancelled=lambda: False, query=None):
|
||||
"""Query every row's host. ``on_result`` is called for each finished row (any thread)."""
|
||||
if sys.platform != "win32" and query is None:
|
||||
raise ClientScanError("Die Abfrage von Windows-Clients ist nur unter Windows verfügbar.")
|
||||
port = WINRM_HTTPS_PORT if use_ssl else WINRM_HTTP_PORT
|
||||
by_host = {row["host"]: row for row in rows}
|
||||
results = []
|
||||
|
||||
def reachable(row):
|
||||
def scan(row):
|
||||
if cancelled():
|
||||
return None
|
||||
host = row["host"]
|
||||
if not is_ip(host) and not resolves(host):
|
||||
return row, "Rechnername kann nicht aufgelöst werden (DNS)."
|
||||
return dict(row, status="offline", message="Rechnername kann nicht aufgelöst werden (DNS).",
|
||||
scanned_at=time.time())
|
||||
if not port_open(host, port):
|
||||
return row, f"Nicht erreichbar – ausgeschaltet oder WinRM-Port {port} geschlossen."
|
||||
return row, None
|
||||
return dict(row, status="offline", scanned_at=time.time(),
|
||||
message=f"Nicht erreichbar – ausgeschaltet oder WinRM-Port {port} geschlossen.")
|
||||
if cancelled():
|
||||
return None
|
||||
if query is not None:
|
||||
raw = query(host)
|
||||
else:
|
||||
from netbox_sync.core import wsman
|
||||
|
||||
log(f"Prüfe Erreichbarkeit von {len(rows)} Client(s) auf Port {port} …")
|
||||
online = []
|
||||
with ThreadPoolExecutor(max_workers=min(64, max(1, len(rows)))) as pool:
|
||||
for future in as_completed([pool.submit(reachable, row) for row in rows]):
|
||||
if cancelled():
|
||||
break
|
||||
row, problem = future.result()
|
||||
if problem:
|
||||
finished = dict(row, status="offline", message=problem, scanned_at=time.time())
|
||||
results.append(finished)
|
||||
on_result(finished)
|
||||
else:
|
||||
online.append(row["host"])
|
||||
if cancelled() or not online:
|
||||
return results
|
||||
log(f"{len(online)} Client(s) erreichbar, frage WMI ab …")
|
||||
with wsman.com_thread():
|
||||
raw = wsman.query_client(host, credential, use_ssl, port, timeout)
|
||||
return apply_scan(row, raw)
|
||||
|
||||
def run_chunk(hosts):
|
||||
payload = dict(_credential_payload(credential), hosts=hosts, ssl=use_ssl, port=port, timeout=timeout)
|
||||
process = _start_powershell(_SCAN_SCRIPT, payload)
|
||||
done = set()
|
||||
for raw in _read_lines(process, cancelled):
|
||||
row = by_host.get(raw.get("host"))
|
||||
if row is None:
|
||||
log(f"Frage {len(rows)} Client(s) über WinRM (Port {port}) ab …")
|
||||
with ThreadPoolExecutor(max_workers=max(1, min(parallel, len(rows) or 1))) as pool:
|
||||
futures = [pool.submit(scan, row) for row in rows]
|
||||
for future in as_completed(futures):
|
||||
finished = future.result()
|
||||
if finished is None:
|
||||
continue
|
||||
done.add(raw["host"])
|
||||
finished = apply_scan(row, raw)
|
||||
results.append(finished)
|
||||
on_result(finished)
|
||||
if not cancelled():
|
||||
problem = _stderr(process) or "PowerShell wurde unerwartet beendet."
|
||||
for host in hosts:
|
||||
if host not in done:
|
||||
finished = dict(by_host[host], status="error", message=friendly_error(problem),
|
||||
scanned_at=time.time())
|
||||
results.append(finished)
|
||||
on_result(finished)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=max(1, parallel)) as pool:
|
||||
for future in as_completed([pool.submit(run_chunk, hosts) for hosts in _chunks(online, parallel)]):
|
||||
future.result()
|
||||
if cancelled():
|
||||
for pending in futures:
|
||||
pending.cancel()
|
||||
return results
|
||||
@@ -20,7 +20,7 @@ DEFAULT_SETTINGS = {
|
||||
"enable_lldp": False, # allow configuration changes on switches
|
||||
"create_cables": True,
|
||||
"offline_mode": False, # collect and export to JSON without NetBox
|
||||
"parallel_wmi": 8, # concurrent PowerShell sessions for client scans
|
||||
"parallel_wmi": 8, # concurrent WinRM sessions for client scans
|
||||
}
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -115,6 +115,7 @@ def empty_profile(name):
|
||||
"switches": [],
|
||||
# Remembered assignment "<source id>:<hypervisor cluster>" -> NetBox cluster name.
|
||||
"cluster_map": {},
|
||||
"host_map": {},
|
||||
# Windows client scan: targets and options, never a password.
|
||||
"clients": dict(DEFAULT_CLIENT_OPTIONS),
|
||||
}
|
||||
@@ -162,6 +163,7 @@ class ProfileStore:
|
||||
"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))),
|
||||
"cluster_map": dict(record.get("cluster_map", {})),
|
||||
"host_map": dict(record.get("host_map", {})),
|
||||
"clients": {**DEFAULT_CLIENT_OPTIONS, **{key: value for key, value in record.get("clients", {}).items()
|
||||
if key in DEFAULT_CLIENT_OPTIONS}},
|
||||
})
|
||||
@@ -225,6 +227,7 @@ class ProfileStore:
|
||||
"sources": [self._encrypt_record(source) for source in profile.get("sources", [])],
|
||||
"switches": [self._encrypt_record(switch) for switch in profile.get("switches", [])],
|
||||
"cluster_map": dict(profile.get("cluster_map", {})),
|
||||
"host_map": dict(profile.get("host_map", {})),
|
||||
"clients": dict(profile.get("clients", DEFAULT_CLIENT_OPTIONS)),
|
||||
})
|
||||
|
||||
|
||||
@@ -75,6 +75,7 @@ def validate(data):
|
||||
raise ExchangeError("Die Datei enthält eine VM ohne Name oder Quelle.")
|
||||
vm.setdefault("interfaces", [])
|
||||
vm.setdefault("cluster", "")
|
||||
vm.setdefault("host", "")
|
||||
vm.setdefault("status", "offline")
|
||||
for key in ("vcpus", "memory", "disk"):
|
||||
vm[key] = int(vm.get(key) or 0)
|
||||
|
||||
+591
-34
@@ -29,6 +29,14 @@ 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",
|
||||
}
|
||||
|
||||
LLDP_CONTROL = {
|
||||
"aruba_cx": {
|
||||
"status": "show lldp configuration",
|
||||
@@ -311,6 +319,10 @@ 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,
|
||||
@@ -318,6 +330,7 @@ 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,
|
||||
@@ -591,8 +604,188 @@ 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_vlan_names(config):
|
||||
"""``{VLAN ID: name}`` from ``vlan <id>`` blocks (same syntax on all platforms)."""
|
||||
names = {}
|
||||
for match, body in _config_blocks(config or "", re.compile(r"^vlan\s+(\d+)\s*$", re.I)):
|
||||
for line in body:
|
||||
name = re.match(r'^name\s+"?(.*?)"?\s*$', line, flags=re.I)
|
||||
if name and name.group(1):
|
||||
names[int(match.group(1))] = name.group(1)
|
||||
return names
|
||||
|
||||
|
||||
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", ""))
|
||||
@@ -625,7 +818,10 @@ def build_snapshot(outputs, platform):
|
||||
"neighbors": neighbors,
|
||||
"lldp_neighbors": lldp_neighbors,
|
||||
"cdp_neighbors": cdp_neighbors,
|
||||
"raw": outputs,
|
||||
"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")),
|
||||
"vlan_names": parse_vlan_names(outputs.get("config", "")),
|
||||
"lldp_disabled": outputs.get("lldp_disabled", False),
|
||||
"lldp_enabled_automatically": outputs.get("lldp_enabled_automatically", False),
|
||||
"discovered_at": time.time(),
|
||||
@@ -712,6 +908,251 @@ 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 _require_tenant(device):
|
||||
tenant_id = related_id(device, "tenant")
|
||||
if tenant_id:
|
||||
return tenant_id, None
|
||||
return None, (f"NetBox-Gerät „{device.name}“ hat keinen Mandanten – bitte zuerst in NetBox einen Mandanten "
|
||||
"zuweisen. Ohne Mandant werden keine Objekte angelegt.")
|
||||
|
||||
|
||||
def snapshot_networks(snapshot):
|
||||
"""Networks of all interface IP addresses (host routes are left out)."""
|
||||
networks = set()
|
||||
for interface in snapshot["interfaces"]:
|
||||
for address in interface.get("ip_addresses", []):
|
||||
network = ipaddress.ip_interface(address).network
|
||||
if network.prefixlen < network.max_prefixlen:
|
||||
networks.add(network)
|
||||
return [str(network) for network in sorted(networks, key=lambda item: (item.version, item))]
|
||||
|
||||
|
||||
def snapshot_vlan_ids(snapshot):
|
||||
vids = set()
|
||||
for interface in snapshot["interfaces"]:
|
||||
vlans = interface.get("vlans") or {}
|
||||
vids.update(vlans.get("untagged", []))
|
||||
vids.update(vlans.get("tagged", []))
|
||||
return sorted(vids)
|
||||
|
||||
|
||||
def _tenant_vlans(nb, tenant_id, site_id):
|
||||
"""``{VLAN ID: record}`` of the tenant; a VLAN of the switch's site wins."""
|
||||
found = {}
|
||||
for vlan in nb.ipam.vlans.filter(tenant_id=tenant_id):
|
||||
current = found.get(vlan.vid)
|
||||
if current is None or (related_id(vlan, "site") == site_id and related_id(current, "site") != site_id):
|
||||
found[vlan.vid] = vlan
|
||||
return found
|
||||
|
||||
|
||||
def plan_switch_sync(nb, config, snapshot):
|
||||
"""Proposals for the review dialog: interface mapping, neighbor devices,
|
||||
networks (VRF and missing prefixes) and missing VLANs."""
|
||||
device, error = _resolve_device(nb, config)
|
||||
if not error:
|
||||
tenant_id, error = _require_tenant(device)
|
||||
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())
|
||||
|
||||
tenant_vrfs = {vrf.id: vrf.name for vrf in nb.ipam.vrfs.filter(tenant_id=tenant_id)}
|
||||
vrfs = sorted(tenant_vrfs.values(), key=str.casefold)
|
||||
stored_vrfs = config.get("network_vrfs") or {}
|
||||
create_prefixes = config.get("create_prefixes")
|
||||
networks = []
|
||||
for network in snapshot_networks(snapshot):
|
||||
# Where the prefix already exists: "" = global, otherwise a tenant VRF.
|
||||
existing = set()
|
||||
for prefix in nb.ipam.prefixes.filter(prefix=network):
|
||||
vrf_id = related_id(prefix, "vrf")
|
||||
if vrf_id is None or vrf_id in tenant_vrfs:
|
||||
existing.add(tenant_vrfs.get(vrf_id, ""))
|
||||
existing = sorted(existing)
|
||||
vrf = stored_vrfs[network] if network in stored_vrfs else (existing[0] if existing else "")
|
||||
if vrf and vrf not in vrfs:
|
||||
vrfs.append(vrf) # chosen earlier as new VRF, not created yet
|
||||
networks.append({"network": network, "vrf": vrf, "existing_vrfs": existing,
|
||||
"create": create_prefixes is None or network in create_prefixes})
|
||||
|
||||
names = {int(key): value for key, value in (snapshot.get("vlan_names") or {}).items()}
|
||||
present = _tenant_vlans(nb, tenant_id, related_id(device, "site"))
|
||||
create_vlans = config.get("create_vlans")
|
||||
vlans = [{"vid": vid, "name": names.get(vid) or f"VLAN{vid}",
|
||||
"netbox_name": present[vid].name if vid in present else None,
|
||||
"create": create_vlans is None or vid in create_vlans}
|
||||
for vid in snapshot_vlan_ids(snapshot)]
|
||||
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,
|
||||
"tenant": getattr(getattr(device, "tenant", None), "name", None) or str(tenant_id),
|
||||
"vrfs": vrfs,
|
||||
"networks": networks,
|
||||
"vlans": vlans,
|
||||
}
|
||||
|
||||
|
||||
class _RemoteLookup:
|
||||
"""Find neighbor devices and interfaces in NetBox, cached per sync run."""
|
||||
|
||||
@@ -752,14 +1193,112 @@ 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
|
||||
|
||||
|
||||
_NEW = "new" # placeholder ID of objects a dry run would create
|
||||
|
||||
|
||||
def _sync_vrfs(nb, config, snapshot, tenant_id, dry_run, report):
|
||||
"""``{network: VRF ID or None}``; VRFs chosen by name are created for the tenant."""
|
||||
by_name = {vrf.name: vrf.id for vrf in nb.ipam.vrfs.filter(tenant_id=tenant_id)}
|
||||
chosen = config.get("network_vrfs") or {}
|
||||
result = {}
|
||||
for network in snapshot_networks(snapshot):
|
||||
name = chosen.get(network) or ""
|
||||
if name and name not in by_name:
|
||||
report["vrfs_created"] += 1
|
||||
report["changes"].append(f"VRF {name} neu")
|
||||
by_name[name] = _NEW if dry_run else nb.ipam.vrfs.create({"name": name, "tenant": tenant_id}).id
|
||||
result[network] = by_name[name] if name else None
|
||||
return result
|
||||
|
||||
|
||||
def _sync_prefixes(nb, config, snapshot, tenant_id, vrf_ids, dry_run, report):
|
||||
"""Create missing prefixes that were approved; existing ones stay untouched."""
|
||||
approved = set(config.get("create_prefixes") or [])
|
||||
for network in snapshot_networks(snapshot):
|
||||
vrf_id = vrf_ids.get(network)
|
||||
if network not in approved:
|
||||
continue
|
||||
if vrf_id != _NEW and list(nb.ipam.prefixes.filter(prefix=network, vrf_id=vrf_id or "null")):
|
||||
continue
|
||||
try:
|
||||
report["prefixes_created"] += 1
|
||||
vrf_name = (config.get("network_vrfs") or {}).get(network) or "global"
|
||||
report["changes"].append(f"Prefix {network} neu ({vrf_name})")
|
||||
if not dry_run:
|
||||
nb.ipam.prefixes.create({"prefix": network, "status": "active", "tenant": tenant_id, "vrf": vrf_id})
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"Prefix {network}: {error}")
|
||||
|
||||
|
||||
def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report):
|
||||
"""``{VLAN ID: NetBox ID}``; missing VLANs are only created when approved."""
|
||||
present = {vid: vlan.id for vid, vlan in _tenant_vlans(nb, tenant_id, site_id).items()}
|
||||
approved = {int(vid) for vid in config.get("create_vlans") or []}
|
||||
names = {int(key): value for key, value in (snapshot.get("vlan_names") or {}).items()}
|
||||
for vid in snapshot_vlan_ids(snapshot):
|
||||
if vid in present or vid not in approved:
|
||||
continue
|
||||
name = (names.get(vid) or f"VLAN{vid}")[:64]
|
||||
try:
|
||||
report["vlans_created"] += 1
|
||||
report["changes"].append(f"VLAN {vid} „{name}“ neu")
|
||||
payload = {"vid": vid, "name": name, "status": "active", "tenant": tenant_id}
|
||||
if site_id:
|
||||
payload["site"] = site_id
|
||||
present[vid] = _NEW if dry_run else nb.ipam.vlans.create(payload).id
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"VLAN {vid}: {error}")
|
||||
return present
|
||||
|
||||
|
||||
def _record_mode(record):
|
||||
mode = getattr(record, "mode", None)
|
||||
return getattr(mode, "value", mode) or ""
|
||||
|
||||
|
||||
def _vlan_assignment(interface, vlan_ids, record=None):
|
||||
"""802.1Q mode and VLANs of an interface; empty when ``record`` already matches."""
|
||||
vlans = interface.get("vlans")
|
||||
if not vlans or netbox_interface_type(interface) == "virtual":
|
||||
return {}
|
||||
untagged = next((vlan_ids[vid] for vid in vlans.get("untagged", []) if vid in vlan_ids), None)
|
||||
tagged = sorted((vlan_ids[vid] for vid in vlans.get("tagged", []) if vid in vlan_ids), key=str)
|
||||
if untagged is None and not tagged and not vlans.get("tagged_all"):
|
||||
return {} # none of its VLANs exists in NetBox – leave the port alone
|
||||
if vlans.get("tagged_all"):
|
||||
wanted = {"mode": "tagged-all", "untagged_vlan": untagged, "tagged_vlans": []}
|
||||
elif vlans.get("tagged"):
|
||||
wanted = {"mode": "tagged", "untagged_vlan": untagged, "tagged_vlans": tagged}
|
||||
else:
|
||||
wanted = {"mode": "access", "untagged_vlan": untagged, "tagged_vlans": []}
|
||||
if record is None:
|
||||
return wanted
|
||||
current = {
|
||||
"mode": _record_mode(record),
|
||||
"untagged_vlan": related_id(record, "untagged_vlan"),
|
||||
"tagged_vlans": sorted((getattr(item, "id", item) for item in getattr(record, "tagged_vlans", None) or []),
|
||||
key=str),
|
||||
}
|
||||
# NetBox validates the VLANs against the mode, so all three are sent together.
|
||||
return {} if current == wanted else wanted
|
||||
|
||||
|
||||
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,
|
||||
"vrfs_created": 0, "prefixes_created": 0, "vlans_created": 0,
|
||||
"changes": [], "errors": [],
|
||||
}
|
||||
|
||||
@@ -772,37 +1311,45 @@ 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()
|
||||
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")
|
||||
existing = _device_interfaces(nb, device_id)
|
||||
device, error = _resolve_device(nb, config)
|
||||
if not error:
|
||||
tenant_id, error = _require_tenant(device)
|
||||
if error:
|
||||
report["errors"].append(error)
|
||||
return report
|
||||
device_id = device.id
|
||||
vrf_ids = _sync_vrfs(nb, config, snapshot, tenant_id, dry_run, report)
|
||||
_sync_prefixes(nb, config, snapshot, tenant_id, vrf_ids, dry_run, report)
|
||||
vlan_ids = _sync_vlans(nb, config, snapshot, tenant_id, related_id(device, "site"), dry_run, report)
|
||||
matches = match_interfaces(snapshot["interfaces"], list(nb.dcim.interfaces.filter(device_id=device_id)),
|
||||
config.get("interface_map"))
|
||||
records = {}
|
||||
|
||||
for interface in snapshot["interfaces"]:
|
||||
key = interface_key(interface["name"])
|
||||
record = existing.get(key)
|
||||
record, method = matches[interface["name"]]
|
||||
label = vlan_label(interface.get("vlans"))
|
||||
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
|
||||
changes.update(_vlan_assignment(interface, vlan_ids, record))
|
||||
if changes:
|
||||
report["interfaces_updated"] += 1
|
||||
state = "aktivieren" if changes["enabled"] else "deaktivieren"
|
||||
report["changes"].append(f"Interface {record.name}: {state}")
|
||||
texts = []
|
||||
if "enabled" in changes:
|
||||
texts.append("aktivieren" if changes["enabled"] else "deaktivieren")
|
||||
if "label" in changes:
|
||||
texts.append(f"Label „{label}“")
|
||||
if "mode" in changes:
|
||||
texts.append(f"VLAN-Modus {changes['mode']}")
|
||||
target = record.name if method == "name" else f"{record.name} ({interface['name']})"
|
||||
report["changes"].append(f"Interface {target}: {', '.join(texts)}")
|
||||
if not dry_run:
|
||||
record.update(changes)
|
||||
else:
|
||||
@@ -814,13 +1361,16 @@ 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
|
||||
payload.update(_vlan_assignment(interface, vlan_ids))
|
||||
if interface.get("description"):
|
||||
payload["description"] = interface["description"][:200]
|
||||
report["interfaces_created"] += 1
|
||||
report["changes"].append(f"Interface {interface['name']} neu ({payload['type']})")
|
||||
report["changes"].append(f"Interface {interface['name']} neu ({payload['type']})"
|
||||
+ (f", Label „{label}“" if label else ""))
|
||||
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
|
||||
@@ -834,25 +1384,25 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
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
|
||||
]
|
||||
parsed = ipaddress.ip_interface(address)
|
||||
vrf_id = vrf_ids.get(str(parsed.network))
|
||||
if vrf_id == _NEW:
|
||||
candidates = [] # the VRF only exists after the real run
|
||||
else:
|
||||
candidates = list(nb.ipam.ip_addresses.filter(address=str(parsed.ip), vrf_id=vrf_id or "null"))
|
||||
if len(candidates) > 1:
|
||||
raise ValueError("mehrere globale IP-Adressen mit diesem Host gefunden")
|
||||
payload = {"address": address, "status": "active", "assigned_object_type": "dcim.interface"}
|
||||
raise ValueError("mehrere IP-Adressen mit diesem Host in derselben VRF gefunden")
|
||||
payload = {"address": address, "status": "active", "assigned_object_type": "dcim.interface",
|
||||
"tenant": tenant_id, "vrf": vrf_id}
|
||||
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)
|
||||
or related_id(current, "tenant") != tenant_id
|
||||
)
|
||||
if differs:
|
||||
report["ips_updated"] += 1
|
||||
@@ -871,6 +1421,7 @@ 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:
|
||||
@@ -881,7 +1432,12 @@ 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
|
||||
remote_device = lookup.device(neighbor)
|
||||
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)
|
||||
if not remote_device:
|
||||
report["cables_skipped"] += 1
|
||||
continue
|
||||
@@ -898,6 +1454,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
"a_terminations": [{"object_type": "dcim.interface", "object_id": local.id}],
|
||||
"b_terminations": [{"object_type": "dcim.interface", "object_id": remote.id}],
|
||||
"status": "connected",
|
||||
"tenant": tenant_id,
|
||||
})
|
||||
remote.cable = True # avoid a second cable from the reverse direction
|
||||
except Exception as error: # noqa: BLE001
|
||||
|
||||
@@ -87,7 +87,7 @@ def load_vmware_source(source, log=_noop):
|
||||
if properties.get("name") and not properties.get("config.template"):
|
||||
vm = _normalize_vmware_vm(properties, source, vim)
|
||||
host = properties.get("runtime.host")
|
||||
vm["cluster"] = host_clusters.get(getattr(host, "_moId", None), "")
|
||||
vm["cluster"], vm["host"] = host_clusters.get(getattr(host, "_moId", None), ("", ""))
|
||||
normalized.append(vm)
|
||||
return normalized
|
||||
finally:
|
||||
@@ -97,14 +97,14 @@ def load_vmware_source(source, log=_noop):
|
||||
|
||||
|
||||
def _vmware_host_clusters(content, vim):
|
||||
"""Map ESXi host IDs to their cluster name (or the host name when standalone)."""
|
||||
"""Map ESXi host IDs to ``(cluster name, host name)``; standalone hosts use their own name as cluster."""
|
||||
result = {}
|
||||
view = content.viewManager.CreateContainerView(content.rootFolder, [vim.ComputeResource], True)
|
||||
try:
|
||||
for resource in view.view:
|
||||
name = resource.name
|
||||
for host in resource.host or []:
|
||||
result[host._moId] = name
|
||||
result[host._moId] = (name, host.name)
|
||||
finally:
|
||||
view.Destroy()
|
||||
return result
|
||||
@@ -205,6 +205,7 @@ def load_proxmox_source(source, log=_noop):
|
||||
try:
|
||||
guest = _normalize_proxmox_guest(session, source, resource)
|
||||
guest["cluster"] = cluster_name or resource.get("node", "")
|
||||
guest["host"] = resource.get("node", "")
|
||||
result.append(guest)
|
||||
except Exception as error: # noqa: BLE001 - one broken guest must not stop the source
|
||||
log(f"{source['name']} / VMID {resource.get('vmid')}: {error}", "warning")
|
||||
|
||||
@@ -28,6 +28,11 @@ def cluster_key(vm):
|
||||
return f"{vm.get('source_id', vm.get('source', ''))}:{vm.get('cluster', '')}"
|
||||
|
||||
|
||||
def host_key(vm):
|
||||
"""Identifies the hypervisor host (ESXi host / Proxmox node) of a VM across sources."""
|
||||
return f"{vm.get('source', '')}:{vm.get('host', '')}"
|
||||
|
||||
|
||||
def _compact(name):
|
||||
return re.sub(r"[^0-9a-z]", "", (name or "").casefold())
|
||||
|
||||
@@ -60,6 +65,7 @@ class VMSyncEngine:
|
||||
self.tenants = {}
|
||||
self.vrfs = []
|
||||
self.platforms = []
|
||||
self.devices = {}
|
||||
self.existing_vms = {}
|
||||
self._reset_run_state()
|
||||
|
||||
@@ -86,12 +92,19 @@ class VMSyncEngine:
|
||||
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.devices = {}
|
||||
for device in self.nb.dcim.devices.all():
|
||||
if device.name:
|
||||
self.devices[device.id] = {
|
||||
"name": device.name, "site": related_name(device, "site") or "",
|
||||
"cluster_id": related_id(device, "cluster"),
|
||||
}
|
||||
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"
|
||||
f"{len(self.vrfs)} VRFs, {len(self.devices)} Geräte, {sum(map(len, self.existing_vms.values()))} VMs"
|
||||
)
|
||||
|
||||
def tenant_vrfs(self, tenant_id):
|
||||
@@ -301,7 +314,28 @@ class VMSyncEngine:
|
||||
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):
|
||||
def device_label(self, device_id):
|
||||
device = self.devices[device_id]
|
||||
return f"{device['name']} ({device['site']})" if device["site"] else device["name"]
|
||||
|
||||
def prepare_host_device(self, device_id, cluster_id):
|
||||
"""Make sure the device may host VMs of the cluster; NetBox requires both to match.
|
||||
|
||||
A device without cluster is added to it. Returns ``False`` if it belongs to another cluster.
|
||||
"""
|
||||
device = self.devices[device_id]
|
||||
if device["cluster_id"] == cluster_id:
|
||||
return True
|
||||
if device["cluster_id"]:
|
||||
self.log(f"Gerät {device['name']} gehört in NetBox zu einem anderen Cluster – "
|
||||
"wird nicht als Host eingetragen", "warning")
|
||||
return False
|
||||
self.nb.dcim.devices.get(device_id).update({"cluster": cluster_id})
|
||||
device["cluster_id"] = cluster_id
|
||||
self.log(f"Gerät {device['name']} dem Cluster zugeordnet", "success")
|
||||
return True
|
||||
|
||||
def sync_vm(self, source_vm, cluster_id, tenant_id, vrf_id, device_id=None):
|
||||
"""Create or update one VM. Returns ``"created"`` or ``"updated"``."""
|
||||
payload = {
|
||||
"name": source_vm["name"], "cluster": cluster_id, "status": source_vm["status"],
|
||||
@@ -311,6 +345,8 @@ class VMSyncEngine:
|
||||
platform_id = self.get_platform_id(source_vm.get("guest_os"))
|
||||
if platform_id:
|
||||
payload["platform"] = platform_id
|
||||
if device_id and self.prepare_host_device(device_id, cluster_id):
|
||||
payload["device"] = device_id
|
||||
|
||||
netbox_vm = self._find_vm(source_vm["name"], cluster_id)
|
||||
if netbox_vm:
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
"""In-process access to WinRM (WSMan.Automation) and Active Directory (ADSI).
|
||||
|
||||
Both run through Windows COM inside the application process. No PowerShell
|
||||
or other helper process is started – endpoint protection such as Sophos
|
||||
"Application Lockdown" terminates applications that spawn script hosts.
|
||||
Authentication uses the Windows stack (Kerberos/Negotiate) with either the
|
||||
signed-in user or explicit credentials.
|
||||
"""
|
||||
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
WMI_CIMV2 = "http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/"
|
||||
STD_REG_PROV = "http://schemas.microsoft.com/wbem/wsman/1/wmi/root/default/StdRegProv"
|
||||
XSI_NIL = "{http://www.w3.org/2001/XMLSchema-instance}nil"
|
||||
HKEY_LOCAL_MACHINE = 2147483650
|
||||
|
||||
# WSManSessionFlags
|
||||
FLAG_UTF8 = 0x1
|
||||
FLAG_CRED_USERNAME_PASSWORD = 0x1000
|
||||
FLAG_USE_NEGOTIATE = 0x20000
|
||||
FLAG_USE_SSL = 0x8000000
|
||||
|
||||
ADS_SECURE_AUTHENTICATION = 0x1
|
||||
ADS_USE_SEALING = 0x40
|
||||
|
||||
|
||||
class WSManError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _com():
|
||||
import pythoncom
|
||||
import pywintypes
|
||||
import win32com.client
|
||||
|
||||
return pythoncom, pywintypes, win32com.client
|
||||
|
||||
|
||||
class com_thread:
|
||||
"""Initialise COM for the calling worker thread."""
|
||||
|
||||
def __enter__(self):
|
||||
pythoncom = _com()[0]
|
||||
pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
|
||||
return self
|
||||
|
||||
def __exit__(self, *_exc):
|
||||
_com()[0].CoUninitialize()
|
||||
return False
|
||||
|
||||
|
||||
def _local(tag):
|
||||
return tag.rsplit("}", 1)[-1]
|
||||
|
||||
|
||||
def parse_instance(text):
|
||||
"""Turn a WS-Man CIM instance (XML) into ``{property: value or [values]}``."""
|
||||
root = ET.fromstring(text)
|
||||
result = {}
|
||||
for child in root:
|
||||
name = _local(child.tag)
|
||||
if child.get(XSI_NIL) == "true":
|
||||
value = None
|
||||
elif len(child):
|
||||
value = (child[0].text or "").strip() # e.g. <cim:Datetime>
|
||||
else:
|
||||
value = (child.text or "").strip()
|
||||
if name in result:
|
||||
if not isinstance(result[name], list):
|
||||
result[name] = [result[name]]
|
||||
result[name].append(value)
|
||||
else:
|
||||
result[name] = value
|
||||
return result
|
||||
|
||||
|
||||
def as_list(value):
|
||||
if value is None:
|
||||
return []
|
||||
return value if isinstance(value, list) else [value]
|
||||
|
||||
|
||||
def as_bool(value):
|
||||
return str(value).strip().lower() == "true"
|
||||
|
||||
|
||||
def as_int(value):
|
||||
try:
|
||||
return int(str(value).strip())
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
def _error_text(error, session=None):
|
||||
"""Readable message (with HRESULT) from a COM error or a WSMan fault."""
|
||||
details = ""
|
||||
info = getattr(error, "excepinfo", None)
|
||||
if session is not None:
|
||||
try:
|
||||
fault = session.Error or ""
|
||||
except Exception: # noqa: BLE001 - the session may already be unusable
|
||||
fault = ""
|
||||
if fault:
|
||||
try:
|
||||
root = ET.fromstring(fault)
|
||||
code = root.get("Code", "")
|
||||
message = " ".join(text.strip() for text in root.itertext() if text.strip())
|
||||
details = f"{message} (WSMan {code})" if code else message
|
||||
except ET.ParseError:
|
||||
details = fault
|
||||
if not details:
|
||||
details = (info[2] if info and len(info) > 2 and info[2] else "") or str(error)
|
||||
hresult = getattr(error, "hresult", None)
|
||||
if isinstance(info, tuple) and len(info) > 5 and info[5]:
|
||||
hresult = info[5]
|
||||
if isinstance(hresult, int):
|
||||
details = f"{details} [0x{hresult & 0xFFFFFFFF:08X}]"
|
||||
return details
|
||||
|
||||
|
||||
class Session:
|
||||
def __init__(self, host, credential=None, use_ssl=False, port=None, timeout=30):
|
||||
_pythoncom, self._pywintypes, client = _com()
|
||||
self.wsman = client.Dispatch("WSMan.Automation")
|
||||
flags = FLAG_UTF8 | FLAG_USE_NEGOTIATE
|
||||
options = None
|
||||
if credential is not None:
|
||||
options = self.wsman.CreateConnectionOptions()
|
||||
options.UserName = credential.username
|
||||
options.Password = credential.password
|
||||
flags |= FLAG_CRED_USERNAME_PASSWORD
|
||||
if use_ssl:
|
||||
flags |= FLAG_USE_SSL
|
||||
scheme = "https" if use_ssl else "http"
|
||||
port = port or (5986 if use_ssl else 5985)
|
||||
self.session = self.wsman.CreateSession(f"{scheme}://{host}:{port}/wsman", flags, options)
|
||||
self.session.Timeout = int(timeout * 1000)
|
||||
|
||||
def _fail(self, error):
|
||||
raise WSManError(_error_text(error, self.session)) from error
|
||||
|
||||
def enumerate(self, cim_class):
|
||||
try:
|
||||
enumerator = self.session.Enumerate(WMI_CIMV2 + cim_class, "", "", 0)
|
||||
items = []
|
||||
while not enumerator.AtEndOfStream:
|
||||
items.append(parse_instance(enumerator.ReadItem()))
|
||||
return items
|
||||
except self._pywintypes.com_error as error:
|
||||
self._fail(error)
|
||||
|
||||
def first(self, cim_class):
|
||||
items = self.enumerate(cim_class)
|
||||
return items[0] if items else {}
|
||||
|
||||
def registry_string(self, key, value):
|
||||
parameters = (
|
||||
f'<p:GetStringValue_INPUT xmlns:p="{STD_REG_PROV}">'
|
||||
f"<p:hDefKey>{HKEY_LOCAL_MACHINE}</p:hDefKey>"
|
||||
f"<p:sSubKeyName>{key}</p:sSubKeyName><p:sValueName>{value}</p:sValueName>"
|
||||
"</p:GetStringValue_INPUT>"
|
||||
)
|
||||
try:
|
||||
result = parse_instance(self.session.Invoke("GetStringValue", STD_REG_PROV, parameters, 0))
|
||||
except (self._pywintypes.com_error, ET.ParseError):
|
||||
return ""
|
||||
return result.get("sValue") or ""
|
||||
|
||||
|
||||
def _datetime(value):
|
||||
"""CIM datetimes arrive as ISO strings; keep second precision."""
|
||||
return (value or "")[:19]
|
||||
|
||||
|
||||
def query_client(host, credential=None, use_ssl=False, port=None, timeout=30):
|
||||
"""Read inventory data from one client. Returns the raw result dict used by ``apply_scan``."""
|
||||
result = {"host": host, "ok": False}
|
||||
try:
|
||||
session = Session(host, credential, use_ssl, port, timeout)
|
||||
system = session.first("Win32_ComputerSystem")
|
||||
os_info = session.first("Win32_OperatingSystem")
|
||||
bios = session.first("Win32_BIOS")
|
||||
product = session.first("Win32_ComputerSystemProduct")
|
||||
enclosure = session.first("Win32_SystemEnclosure")
|
||||
processors = session.enumerate("Win32_Processor")
|
||||
adapters = {as_int(item.get("InterfaceIndex")): item for item in session.enumerate("Win32_NetworkAdapter")
|
||||
if as_bool(item.get("PhysicalAdapter"))}
|
||||
nics = []
|
||||
for config in session.enumerate("Win32_NetworkAdapterConfiguration"):
|
||||
if not as_bool(config.get("IPEnabled")):
|
||||
continue
|
||||
adapter = adapters.get(as_int(config.get("InterfaceIndex")))
|
||||
nics.append({
|
||||
"name": (adapter or {}).get("NetConnectionID") or "",
|
||||
"description": config.get("Description") or "",
|
||||
"mac": config.get("MACAddress") or "",
|
||||
"ips": as_list(config.get("IPAddress")),
|
||||
"masks": as_list(config.get("IPSubnet")),
|
||||
"gateway": as_list(config.get("DefaultIPGateway")),
|
||||
"dhcp": as_bool(config.get("DHCPEnabled")),
|
||||
"physical": adapter is not None,
|
||||
"speed": as_int((adapter or {}).get("Speed")),
|
||||
})
|
||||
display = session.registry_string(r"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "DisplayVersion")
|
||||
except WSManError as error:
|
||||
result["error"] = str(error)
|
||||
return result
|
||||
except Exception as error: # noqa: BLE001 - one broken client must not stop the scan
|
||||
result["error"] = _error_text(error)
|
||||
return result
|
||||
result.update({
|
||||
"ok": True,
|
||||
"name": system.get("Name") or "",
|
||||
"domain": system.get("Domain") or "",
|
||||
"part_of_domain": as_bool(system.get("PartOfDomain")),
|
||||
"manufacturer": system.get("Manufacturer") or "",
|
||||
"model": system.get("Model") or "",
|
||||
"product_name": product.get("Name") or "",
|
||||
"product_version": product.get("Version") or "",
|
||||
"serial": bios.get("SerialNumber") or "",
|
||||
"bios_version": bios.get("SMBIOSBIOSVersion") or "",
|
||||
"chassis": [as_int(value) for value in as_list(enclosure.get("ChassisTypes"))],
|
||||
"user": system.get("UserName") or "",
|
||||
"memory": as_int(system.get("TotalPhysicalMemory")),
|
||||
"cpu": (processors[0].get("Name") or "") if processors else "",
|
||||
"cores": sum(as_int(item.get("NumberOfCores")) for item in processors),
|
||||
"os": os_info.get("Caption") or "",
|
||||
"os_version": os_info.get("Version") or "",
|
||||
"os_build": os_info.get("BuildNumber") or "",
|
||||
"os_display_version": display,
|
||||
"os_architecture": os_info.get("OSArchitecture") or "",
|
||||
"installed": _datetime(os_info.get("InstallDate")),
|
||||
"last_boot": _datetime(os_info.get("LastBootUpTime")),
|
||||
"nics": nics,
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Active Directory (ADSI via ADODB)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
AD_ATTRIBUTES = ("name", "dNSHostName", "operatingSystem", "operatingSystemVersion", "lastLogonTimestamp",
|
||||
"distinguishedName", "description", "userAccountControl")
|
||||
|
||||
|
||||
def _field(record, name):
|
||||
value = record.Fields(name).Value
|
||||
if isinstance(value, (tuple, list)):
|
||||
value = value[0] if value else None
|
||||
return value
|
||||
|
||||
|
||||
def _large_integer(value):
|
||||
if value is None:
|
||||
return 0
|
||||
if isinstance(value, int):
|
||||
return value
|
||||
try:
|
||||
return (int(value.HighPart) << 32) + (int(value.LowPart) & 0xFFFFFFFF)
|
||||
except Exception: # noqa: BLE001 - unexpected COM type
|
||||
return 0
|
||||
|
||||
|
||||
def search_ad(location, ldap_filter, credential=None):
|
||||
"""Query computer objects. ``location`` is ``server/base`` or ``base`` (without ``LDAP://``)."""
|
||||
_pythoncom, pywintypes, client = _com()
|
||||
try:
|
||||
connection = client.Dispatch("ADODB.Connection")
|
||||
connection.Provider = "ADsDSOObject"
|
||||
if credential is not None:
|
||||
connection.Properties("User ID").Value = credential.username
|
||||
connection.Properties("Password").Value = credential.password
|
||||
connection.Properties("Encrypt Password").Value = True
|
||||
connection.Properties("ADSI Flag").Value = ADS_SECURE_AUTHENTICATION | ADS_USE_SEALING
|
||||
connection.Open("Active Directory Provider")
|
||||
command = client.Dispatch("ADODB.Command")
|
||||
command.ActiveConnection = connection
|
||||
command.Properties("Page Size").Value = 1000
|
||||
command.CommandText = f"<LDAP://{location}>;{ldap_filter};{','.join(AD_ATTRIBUTES)};subtree"
|
||||
records = command.Execute()[0]
|
||||
rows = []
|
||||
while not records.EOF:
|
||||
rows.append({
|
||||
"name": _field(records, "name") or "",
|
||||
"dns": _field(records, "dNSHostName") or "",
|
||||
"os": _field(records, "operatingSystem") or "",
|
||||
"os_version": _field(records, "operatingSystemVersion") or "",
|
||||
"last_logon": _large_integer(_field(records, "lastLogonTimestamp")),
|
||||
"dn": _field(records, "distinguishedName") or "",
|
||||
"description": _field(records, "description") or "",
|
||||
"disabled": bool(as_int(_field(records, "userAccountControl")) & 2),
|
||||
})
|
||||
records.MoveNext()
|
||||
connection.Close()
|
||||
return rows
|
||||
except pywintypes.com_error as error:
|
||||
raise WSManError(_error_text(error)) from error
|
||||
@@ -17,6 +17,7 @@ from netbox_sync.core.switches import (
|
||||
PLATFORMS,
|
||||
describe_snapshot,
|
||||
discover_switch,
|
||||
plan_switch_sync,
|
||||
suggest_platform,
|
||||
sync_snapshot_to_netbox,
|
||||
)
|
||||
@@ -24,7 +25,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 SyncPreviewDialog
|
||||
from netbox_sync.ui.dialogs import SwitchMappingDialog, SyncPreviewDialog
|
||||
from netbox_sync.ui.tasks import area_log, logger
|
||||
|
||||
|
||||
@@ -412,8 +413,45 @@ class Actions:
|
||||
connect = self._connector()
|
||||
log = area_log("switch")
|
||||
|
||||
def preview(ctx):
|
||||
def plan(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"])
|
||||
or item["networks"] or any(not vlan["netbox_name"] for vlan in item["vlans"])
|
||||
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"])
|
||||
@@ -423,7 +461,6 @@ 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
|
||||
@@ -433,7 +470,7 @@ class Actions:
|
||||
self._apply_switch_sync(nb, items, create_cables, log)
|
||||
QTimer.singleShot(0, ask)
|
||||
|
||||
self.tasks.run(preview, title="Änderungen berechnen", area="switch", on_success=show_preview,
|
||||
self.tasks.run(plan, title="Zuordnung ermitteln", area="switch", on_success=review,
|
||||
on_error=self._netbox_failed)
|
||||
|
||||
def _apply_switch_sync(self, nb, items, create_cables, log):
|
||||
|
||||
@@ -36,9 +36,9 @@ class ClientTargetDialog(_Dialog):
|
||||
else:
|
||||
self.role.setEditText(remembered)
|
||||
form.addRow("Geräterolle *", self.role)
|
||||
self.tenant = SearchableComboBox("Kein Mandant")
|
||||
self.tenant.set_items([("Kein Mandant", None)] + list(engine.tenants), options.get("netbox_tenant"))
|
||||
form.addRow("Mandant", self.tenant)
|
||||
self.tenant = SearchableComboBox("Mandant wählen …")
|
||||
self.tenant.set_items(list(engine.tenants), options.get("netbox_tenant"))
|
||||
form.addRow("Mandant *", self.tenant)
|
||||
self.root.addLayout(form)
|
||||
self.interfaces = checkbox("Netzwerkkarten, MAC- und IP-Adressen übernehmen",
|
||||
options.get("sync_interfaces", True),
|
||||
@@ -60,16 +60,21 @@ class ClientTargetDialog(_Dialog):
|
||||
role_text = self.role.currentText().strip()
|
||||
role = self.role.valid_data()
|
||||
_mark_invalid(self.site, site is None)
|
||||
tenant = self.tenant.valid_data()
|
||||
_mark_invalid(self.role, not role_text)
|
||||
_mark_invalid(self.tenant, tenant is None)
|
||||
if site is None:
|
||||
self.show_error("Bitte einen vorhandenen Standort auswählen.")
|
||||
return
|
||||
if not role_text:
|
||||
self.show_error("Bitte eine Geräterolle auswählen oder einen Namen für eine neue Rolle eingeben.")
|
||||
return
|
||||
if tenant is None:
|
||||
self.show_error("Bitte einen Mandanten auswählen – alle Objekte in NetBox brauchen einen Mandanten.")
|
||||
return
|
||||
self.result = {
|
||||
"site_id": site, "role_id": role, "role_name": role_text,
|
||||
"tenant_id": self.tenant.valid_data(),
|
||||
"tenant_id": tenant,
|
||||
"interfaces": self.interfaces.isChecked(), "update_existing": self.update_existing.isChecked(),
|
||||
}
|
||||
super().accept()
|
||||
|
||||
+262
-3
@@ -3,7 +3,7 @@
|
||||
import uuid
|
||||
|
||||
from PySide6.QtCore import QThreadPool, Qt
|
||||
from PySide6.QtGui import QGuiApplication
|
||||
from PySide6.QtGui import QColor, QGuiApplication
|
||||
from PySide6.QtWidgets import (
|
||||
QButtonGroup,
|
||||
QComboBox,
|
||||
@@ -16,6 +16,8 @@ from PySide6.QtWidgets import (
|
||||
QPlainTextEdit,
|
||||
QPushButton,
|
||||
QSpinBox,
|
||||
QTableWidget,
|
||||
QTableWidgetItem,
|
||||
QTabWidget,
|
||||
QTreeWidget,
|
||||
QTreeWidgetItem,
|
||||
@@ -24,7 +26,7 @@ from PySide6.QtWidgets import (
|
||||
)
|
||||
|
||||
from netbox_sync.core.config import known_hosts_path
|
||||
from netbox_sync.core.switches import PLATFORMS, forget_host_key
|
||||
from netbox_sync.core.switches import MATCH_METHODS, 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
|
||||
@@ -525,6 +527,10 @@ class SyncPreviewDialog(_Dialog):
|
||||
(f"{totals.get('interfaces_updated', 0)} Interfaces geändert", "info"),
|
||||
(f"{totals.get('ips_created', 0) + totals.get('ips_updated', 0)} IP-Adressen", "info"),
|
||||
]
|
||||
for key, text in (("vrfs_created", "VRF(s) neu"), ("prefixes_created", "Prefix(e) neu"),
|
||||
("vlans_created", "VLAN(s) neu")):
|
||||
if totals.get(key):
|
||||
items.append((f"{totals[key]} {text}", "info"))
|
||||
if create_cables:
|
||||
items.append((f"{totals.get('cables_created', 0)} Kabel", "info"))
|
||||
errors = sum(len(report["errors"]) for _switch, report in reports)
|
||||
@@ -566,10 +572,263 @@ 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, Nachbarn, Netze und VLANs prüfen und bei Bedarf korrigieren. Neue Objekte "
|
||||
"erhalten immer den Mandanten des Switches – die Auswahl wird im Profil gespeichert.",
|
||||
width=820)
|
||||
self.resize(1120, 680)
|
||||
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)")
|
||||
|
||||
# Networks --------------------------------------------------------------
|
||||
self.network_rows = []
|
||||
networks = [(switch, plan, item) for switch, plan in plans for item in plan["networks"]]
|
||||
if networks:
|
||||
network_page = QWidget()
|
||||
network_layout = QVBoxLayout(network_page)
|
||||
network_layout.setContentsMargins(0, 12, 0, 0)
|
||||
network_layout.addWidget(label(
|
||||
"Netze der Switch-IP-Adressen. Die VRF gilt für Prefix und IP-Adressen; zur Auswahl stehen die "
|
||||
"globale Tabelle und die VRFs des Mandanten. Fehlende Prefixe werden nur angelegt, wenn sie "
|
||||
"angehakt sind – immer mit dem Mandanten des Switches.", muted=True, wrap=True))
|
||||
self.network_table = QTableWidget(0, 5)
|
||||
self.network_table.setHorizontalHeaderLabels(["Switch", "Mandant", "Netz", "VRF", "Prefix in NetBox"])
|
||||
for switch, plan, item in networks:
|
||||
row = self.network_table.rowCount()
|
||||
self.network_table.insertRow(row)
|
||||
combo = QComboBox()
|
||||
combo.addItem("Global (keine VRF)", "")
|
||||
for name in plan["vrfs"]:
|
||||
combo.addItem(name, name)
|
||||
combo.addItem("+ Neue VRF …", self.NEW)
|
||||
combo.setCurrentIndex(max(0, combo.findData(item["vrf"])))
|
||||
combo.setProperty("previous", combo.currentIndex())
|
||||
for column, text in enumerate((switch["name"], plan["tenant"], item["network"])):
|
||||
self.network_table.setItem(row, column, QTableWidgetItem(text))
|
||||
self.network_table.setCellWidget(row, 3, combo)
|
||||
status = QTableWidgetItem()
|
||||
self.network_table.setItem(row, 4, status)
|
||||
entry = (row, switch, item, combo, status)
|
||||
self.network_rows.append(entry)
|
||||
combo.activated.connect(lambda _index, entry=entry: self._vrf_chosen(entry))
|
||||
self._update_network_row(entry, item["create"])
|
||||
self._prepare_table(self.network_table, (140, 140, 150, 220, 200))
|
||||
network_layout.addWidget(self.network_table, 1)
|
||||
missing = sum(1 for _row, _switch, item, _combo, _status in self.network_rows if not item["existing_vrfs"])
|
||||
tabs.addTab(network_page, f"Netze ({missing} Prefix(e) fehlen)")
|
||||
|
||||
# VLANs -----------------------------------------------------------------
|
||||
self.vlan_rows = []
|
||||
vlans = [(switch, plan, item) for switch, plan in plans for item in plan["vlans"]]
|
||||
if vlans:
|
||||
vlan_page = QWidget()
|
||||
vlan_layout = QVBoxLayout(vlan_page)
|
||||
vlan_layout.setContentsMargins(0, 12, 0, 0)
|
||||
vlan_layout.addWidget(label(
|
||||
"VLANs der Switch-Ports. Vorhandene VLANs des Mandanten werden den Schnittstellen zugeordnet "
|
||||
"(802.1Q-Modus, untagged/tagged). Fehlende VLANs werden nur angelegt, wenn sie angehakt sind.",
|
||||
muted=True, wrap=True))
|
||||
self.vlan_table = QTableWidget(0, 5)
|
||||
self.vlan_table.setHorizontalHeaderLabels(["Switch", "Mandant", "VLAN", "Name (Switch)", "In NetBox"])
|
||||
for switch, plan, item in vlans:
|
||||
row = self.vlan_table.rowCount()
|
||||
self.vlan_table.insertRow(row)
|
||||
for column, text in enumerate((switch["name"], plan["tenant"], str(item["vid"]), item["name"])):
|
||||
self.vlan_table.setItem(row, column, QTableWidgetItem(text))
|
||||
status = QTableWidgetItem(item["netbox_name"] or "fehlt – anlegen")
|
||||
if item["netbox_name"]:
|
||||
status.setFlags(Qt.ItemIsEnabled)
|
||||
else:
|
||||
status.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
|
||||
status.setCheckState(Qt.Checked if item["create"] else Qt.Unchecked)
|
||||
status.setForeground(QColor(theme.color("warning")))
|
||||
self.vlan_table.setItem(row, 4, status)
|
||||
self.vlan_rows.append((switch, item, status))
|
||||
self._prepare_table(self.vlan_table, (140, 140, 70, 200, 200))
|
||||
vlan_layout.addWidget(self.vlan_table, 1)
|
||||
missing = sum(1 for _switch, item, _status in self.vlan_rows if not item["netbox_name"])
|
||||
tabs.addTab(vlan_page, f"VLANs ({missing} fehlen)")
|
||||
|
||||
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):
|
||||
# Rows must fit the styled combo boxes, otherwise their text is clipped.
|
||||
height = max((table.cellWidget(row, column).sizeHint().height()
|
||||
for row in range(min(table.rowCount(), 1)) for column in range(table.columnCount())
|
||||
if table.cellWidget(row, column)), default=0)
|
||||
table.verticalHeader().setDefaultSectionSize(max(height + 10, table.verticalHeader().defaultSectionSize()))
|
||||
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 _vrf_chosen(self, entry):
|
||||
_row, switch, _item, combo, _status = entry
|
||||
if combo.currentData() == self.NEW:
|
||||
name = ask_text(self, "Neue VRF", "Name der neuen VRF. Sie wird beim Übertragen mit dem Mandanten "
|
||||
"des Switches angelegt.")
|
||||
if not name:
|
||||
combo.setCurrentIndex(combo.property("previous"))
|
||||
return
|
||||
# Offer the new VRF in every row of the same switch.
|
||||
for _r, other_switch, _i, other, _s in self.network_rows:
|
||||
if other_switch["id"] == switch["id"] and other.findData(name) < 0:
|
||||
other.insertItem(other.count() - 1, name, name)
|
||||
combo.setCurrentIndex(combo.findData(name))
|
||||
combo.setProperty("previous", combo.currentIndex())
|
||||
self._update_network_row(entry)
|
||||
|
||||
def _update_network_row(self, entry, create=None):
|
||||
_row, _switch, item, combo, status = entry
|
||||
if combo.currentData() in item["existing_vrfs"]:
|
||||
status.setText("vorhanden")
|
||||
status.setFlags(Qt.ItemIsEnabled)
|
||||
status.setData(Qt.CheckStateRole, None)
|
||||
status.setForeground(QColor(theme.color("text_muted")))
|
||||
return
|
||||
status.setText("fehlt – anlegen")
|
||||
status.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
|
||||
if create is not None or status.data(Qt.CheckStateRole) is None:
|
||||
status.setCheckState(Qt.Checked if create is not False else Qt.Unchecked)
|
||||
status.setForeground(QColor(theme.color("warning")))
|
||||
|
||||
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
|
||||
for switch, plan in self.plans:
|
||||
result[switch["id"]].update({"network_vrfs": {}, "create_prefixes": [], "create_vlans": []})
|
||||
for _row, switch, item, combo, status in self.network_rows:
|
||||
choices = result[switch["id"]]
|
||||
choices["network_vrfs"][item["network"]] = combo.currentData()
|
||||
if status.data(Qt.CheckStateRole) is not None and status.checkState() == Qt.Checked:
|
||||
choices["create_prefixes"].append(item["network"])
|
||||
for switch, item, status in self.vlan_rows:
|
||||
if not item["netbox_name"] and status.checkState() == Qt.Checked:
|
||||
result[switch["id"]]["create_vlans"].append(item["vid"])
|
||||
self.result = result
|
||||
super().accept()
|
||||
|
||||
|
||||
class RawDataDialog(_Dialog):
|
||||
SECTIONS = {
|
||||
"interfaces": "Schnittstellen", "ipv4_interfaces": "IPv4", "ipv6_interfaces": "IPv6",
|
||||
"neighbors": "LLDP", "cdp_neighbors": "CDP", "lldp_status": "LLDP-Status",
|
||||
"neighbors": "LLDP", "cdp_neighbors": "CDP", "vlan_config": "VLAN-Konfiguration", "lldp_status": "LLDP-Status",
|
||||
}
|
||||
|
||||
def __init__(self, parent, items, selected_id=None):
|
||||
|
||||
@@ -22,7 +22,7 @@ from PySide6.QtWidgets import (
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from netbox_sync.core.vm_sync import cluster_key, prefix_choices, vrf_label
|
||||
from netbox_sync.core.vm_sync import cluster_key, host_key, prefix_choices, vrf_label
|
||||
from netbox_sync.ui.icons import icon
|
||||
from netbox_sync.ui.tasks import log_bus
|
||||
from netbox_sync.ui.theme import theme
|
||||
@@ -31,6 +31,7 @@ from netbox_sync.ui.widgets import Banner, SearchableComboBox, button, checkbox,
|
||||
NEW_VRF = "__new__"
|
||||
NEW_CLUSTER = "__new_cluster__"
|
||||
GLOBAL_VRF = "__global__"
|
||||
NO_DEVICE = "__no_device__"
|
||||
STEPS = ("Ziel", "Netzwerke", "Prüfen", "Import")
|
||||
|
||||
|
||||
@@ -127,6 +128,53 @@ class ImportWizard(QDialog):
|
||||
group["vms"].append(vm)
|
||||
return sorted(groups.values(), key=lambda item: (item["source"].casefold(), item["cluster"].casefold()))
|
||||
|
||||
def _host_groups(self):
|
||||
groups = {}
|
||||
for vm in self.vms:
|
||||
if vm.get("host"):
|
||||
key = host_key(vm)
|
||||
groups.setdefault(key, {"key": key, "host": vm["host"], "source": vm.get("source", ""), "vms": []})
|
||||
groups[key]["vms"].append(vm)
|
||||
return sorted(groups.values(), key=lambda item: (item["source"].casefold(), item["host"].casefold()))
|
||||
|
||||
def _build_host_table(self):
|
||||
"""Hypervisor host → NetBox device. Names rarely match, so the user always chooses."""
|
||||
self.host_groups = self._host_groups()
|
||||
remembered = (self.state.profile or {}).get("host_map", {})
|
||||
devices = sorted(((self.engine.device_label(device_id), device_id) for device_id in self.engine.devices),
|
||||
key=lambda item: item[0].casefold())
|
||||
table = QTableWidget(len(self.host_groups), 3)
|
||||
table.setHorizontalHeaderLabels(["Hypervisor-Host", "VMs", "NetBox-Gerät"])
|
||||
table.verticalHeader().setVisible(False)
|
||||
table.verticalHeader().setDefaultSectionSize(46)
|
||||
table.setShowGrid(False)
|
||||
table.setAlternatingRowColors(True)
|
||||
table.setSelectionMode(QTableWidget.NoSelection)
|
||||
table.setFocusPolicy(Qt.NoFocus)
|
||||
table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
|
||||
table.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)
|
||||
table.setColumnWidth(1, 60)
|
||||
table.setFixedHeight(46 * min(len(self.host_groups), 4) + 40)
|
||||
for row, group in enumerate(self.host_groups):
|
||||
item = QTableWidgetItem(f"{group['host']} · {group['source']}")
|
||||
item.setToolTip("\n".join(sorted(vm["name"] for vm in group["vms"])))
|
||||
table.setItem(row, 0, item)
|
||||
count = QTableWidgetItem(str(len(group["vms"])))
|
||||
count.setTextAlignment(Qt.AlignCenter)
|
||||
table.setItem(row, 1, count)
|
||||
combo = SearchableComboBox("NetBox-Gerät suchen …")
|
||||
current = remembered.get(group["key"])
|
||||
if current not in self.engine.devices and current != NO_DEVICE:
|
||||
current = None
|
||||
combo.set_items([("– nicht zuordnen –", NO_DEVICE), *devices], current)
|
||||
holder = QWidget()
|
||||
holder_layout = QHBoxLayout(holder)
|
||||
holder_layout.setContentsMargins(0, 4, 8, 4)
|
||||
holder_layout.addWidget(combo)
|
||||
table.setCellWidget(row, 2, holder)
|
||||
group["combo"] = combo
|
||||
return table
|
||||
|
||||
def _build_target_page(self):
|
||||
page = QWidget()
|
||||
layout = QVBoxLayout(page)
|
||||
@@ -187,6 +235,11 @@ class ImportWizard(QDialog):
|
||||
group["status"] = status
|
||||
combo.activated.connect(lambda _index, g=group: (g.update(how="manual"), self._clusters_changed()))
|
||||
layout.addWidget(self.cluster_table)
|
||||
host_table = self._build_host_table()
|
||||
if self.host_groups:
|
||||
layout.addWidget(label("Auf welches NetBox-Gerät soll jeder Hypervisor-Host gemappt werden?",
|
||||
muted=True, wrap=True))
|
||||
layout.addWidget(host_table)
|
||||
|
||||
form = QFormLayout()
|
||||
form.setHorizontalSpacing(18)
|
||||
@@ -290,6 +343,10 @@ class ImportWizard(QDialog):
|
||||
if self._selected_cluster(group) is None]
|
||||
if missing:
|
||||
return None, "Bitte für folgende Hypervisor-Cluster einen NetBox-Cluster wählen: " + ", ".join(missing)
|
||||
unmapped = [group["host"] for group in self.host_groups if group["combo"].valid_data() is None]
|
||||
if unmapped:
|
||||
return None, ("Bitte für folgende Hypervisor-Hosts ein NetBox-Gerät wählen "
|
||||
"(oder „nicht zuordnen“): " + ", ".join(unmapped))
|
||||
tenant = self.tenant.valid_data()
|
||||
vrf = self.vrf.currentData()
|
||||
if not tenant:
|
||||
@@ -307,8 +364,10 @@ class ImportWizard(QDialog):
|
||||
"label": group["cluster"] or "(ohne Cluster)",
|
||||
"count": len(group["vms"]),
|
||||
}
|
||||
hosts = {group["key"]: group["combo"].valid_data() for group in self.host_groups}
|
||||
return {
|
||||
"clusters": clusters,
|
||||
"hosts": hosts,
|
||||
"tenant": tenant,
|
||||
"tenant_id": self.engine.tenants[tenant],
|
||||
"vrf_mode": "new" if vrf == NEW_VRF else ("global" if vrf == GLOBAL_VRF else "existing"),
|
||||
@@ -508,6 +567,10 @@ class ImportWizard(QDialog):
|
||||
]
|
||||
rows = [
|
||||
("Cluster", "\n".join(cluster_lines)),
|
||||
*([("Hosts", "\n".join(
|
||||
f"{group['host']} → " + ("nicht zuordnen" if target["hosts"][group["key"]] == NO_DEVICE
|
||||
else self.engine.device_label(target["hosts"][group["key"]]))
|
||||
for group in self.host_groups))] if self.host_groups else []),
|
||||
("Mandant", target["tenant"]),
|
||||
("Standard-VRF", vrf_text),
|
||||
("Virtuelle Maschinen", f"{len(self.vms)} gesamt · {new} werden angelegt · {existing} aktualisiert"),
|
||||
@@ -581,6 +644,7 @@ class ImportWizard(QDialog):
|
||||
if self.state.profile is not None:
|
||||
remembered = self.state.profile.setdefault("cluster_map", {})
|
||||
remembered.update({key: item["name"] for key, item in target["clusters"].items()})
|
||||
self.state.profile.setdefault("host_map", {}).update(target["hosts"])
|
||||
self.state.touch()
|
||||
log_bus.entry.connect(self._append_log)
|
||||
self.run_progress.setRange(0, len(vms))
|
||||
@@ -607,7 +671,9 @@ class ImportWizard(QDialog):
|
||||
break
|
||||
ctx.progress(index, len(vms), vm["name"])
|
||||
try:
|
||||
outcome = engine.sync_vm(vm, cluster_ids[cluster_key(vm)], target["tenant_id"], vrf_id)
|
||||
device_id = target["hosts"].get(host_key(vm))
|
||||
outcome = engine.sync_vm(vm, cluster_ids[cluster_key(vm)], target["tenant_id"], vrf_id,
|
||||
None if device_id == NO_DEVICE else device_id)
|
||||
results[outcome] += 1
|
||||
except Exception as error: # noqa: BLE001
|
||||
results["failed"].append(f"{vm['name']}: {error}")
|
||||
|
||||
@@ -60,7 +60,7 @@ class SettingsPage(Page):
|
||||
self.parallel_wmi.setRange(1, 32)
|
||||
self.parallel_wmi.setSuffix(" gleichzeitig")
|
||||
self.parallel_wmi.setFixedWidth(160)
|
||||
form.addRow("PowerShell-Sitzungen", self.parallel_wmi)
|
||||
form.addRow("WinRM-Sitzungen", self.parallel_wmi)
|
||||
clients.add(form)
|
||||
clients.add(label("Kennwörter aus dem Windows-Anmeldefenster werden nie gespeichert, sondern nur bis zum "
|
||||
"Beenden des Programms im Arbeitsspeicher gehalten.", muted=True, wrap=True))
|
||||
|
||||
@@ -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
|
||||
from netbox_sync.core.switches import PLATFORMS, vlan_label
|
||||
from netbox_sync.ui import widgets
|
||||
from netbox_sync.ui.dialogs import AddSwitchesDialog, RawDataDialog, SwitchDialog
|
||||
from netbox_sync.ui.icons import icon
|
||||
@@ -108,6 +108,7 @@ 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", "")),
|
||||
|
||||
@@ -3,3 +3,4 @@ pynetbox>=7.4
|
||||
pyvmomi>=8.0
|
||||
requests>=2.31
|
||||
paramiko>=3.4
|
||||
pywin32>=306; sys_platform == "win32"
|
||||
@@ -74,7 +74,7 @@ class FakeNetBox:
|
||||
mac_addresses=Endpoint(), platforms=Endpoint(),
|
||||
manufacturers=Endpoint(), device_types=Endpoint(), device_roles=Endpoint(),
|
||||
sites=Endpoint())
|
||||
self.ipam = SimpleNamespace(ip_addresses=Endpoint(), prefixes=Endpoint(), vrfs=Endpoint())
|
||||
self.ipam = SimpleNamespace(ip_addresses=Endpoint(), prefixes=Endpoint(), vrfs=Endpoint(), vlans=Endpoint())
|
||||
self.virtualization = SimpleNamespace(clusters=Endpoint(), cluster_types=Endpoint(), virtual_machines=Endpoint(),
|
||||
interfaces=Endpoint())
|
||||
self.tenancy = SimpleNamespace(tenants=Endpoint())
|
||||
@@ -181,3 +181,44 @@ def test_profile_keeps_client_options(tmp_path, monkeypatch):
|
||||
assert "password" not in loaded["Kunde"]["clients"]
|
||||
assert settings["parallel_wmi"] == 8
|
||||
|
||||
|
||||
|
||||
INSTANCE = """<p:Win32_NetworkAdapterConfiguration xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_NetworkAdapterConfiguration" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cim="http://schemas.dmtf.org/wbem/wscim/1/common">
|
||||
<p:Description>Intel(R) Ethernet</p:Description><p:DHCPEnabled>true</p:DHCPEnabled>
|
||||
<p:IPAddress>192.168.65.43</p:IPAddress><p:IPAddress>fe80::1</p:IPAddress>
|
||||
<p:DefaultIPGateway xsi:nil="true"/>
|
||||
<p:InstallDate><cim:Datetime>2025-12-23T17:23:16Z</cim:Datetime></p:InstallDate>
|
||||
</p:Win32_NetworkAdapterConfiguration>"""
|
||||
|
||||
|
||||
def test_parse_wsman_instance():
|
||||
from netbox_sync.core import wsman
|
||||
|
||||
item = wsman.parse_instance(INSTANCE)
|
||||
assert item["Description"] == "Intel(R) Ethernet" and wsman.as_bool(item["DHCPEnabled"])
|
||||
assert item["IPAddress"] == ["192.168.65.43", "fe80::1"]
|
||||
assert item["DefaultIPGateway"] is None and wsman.as_list(item["DefaultIPGateway"]) == []
|
||||
assert item["InstallDate"] == "2025-12-23T17:23:16Z"
|
||||
|
||||
|
||||
def test_ad_location_defaults_to_own_domain(monkeypatch):
|
||||
from netbox_sync.core import clients
|
||||
|
||||
monkeypatch.setenv("USERDNSDOMAIN", "FIRMA.LOCAL")
|
||||
assert clients.ad_location({}) == "DC=FIRMA,DC=LOCAL"
|
||||
assert clients.ad_location({"ad_server": "dc01.firma.local"}) == "dc01.firma.local"
|
||||
assert clients.ad_location({"ad_server": "dc01", "ad_base": "OU=PCs,DC=firma,DC=local"}) == \
|
||||
"dc01/OU=PCs,DC=firma,DC=local"
|
||||
|
||||
|
||||
def test_scan_runs_in_process(monkeypatch):
|
||||
from netbox_sync.core import clients
|
||||
|
||||
monkeypatch.setattr(clients, "resolves", lambda host: host != "unknown")
|
||||
monkeypatch.setattr(clients, "port_open", lambda host, port: host != "off")
|
||||
rows = [new_row(host) for host in ("pc01.firma.local", "off", "unknown")]
|
||||
seen = []
|
||||
results = clients.scan_clients(rows, query=lambda host: dict(RAW, host=host), on_result=seen.append)
|
||||
status = {row["host"]: row["status"] for row in results}
|
||||
assert status == {"pc01.firma.local": "ok", "off": "offline", "unknown": "offline"}
|
||||
assert len(seen) == 3
|
||||
+108
-1
@@ -2,7 +2,7 @@ from types import SimpleNamespace
|
||||
|
||||
from fake_netbox import FakeNetBox, Record
|
||||
|
||||
from netbox_sync.core.switches import build_snapshot, sync_snapshot_to_netbox
|
||||
from netbox_sync.core.switches import build_snapshot, match_interfaces, plan_switch_sync, sync_snapshot_to_netbox
|
||||
from test_switches import COMWARE_BRIEF, COMWARE_LLDP
|
||||
|
||||
|
||||
@@ -63,3 +63,110 @@ 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
|
||||
|
||||
|
||||
def test_missing_vlans_prefixes_and_vrfs_are_only_created_when_approved():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
nb.ipam.vlans.records.append(Record(nb.ipam.vlans, id=110, vid=10, name="Server", tenant=SimpleNamespace(id=7)))
|
||||
snapshot["interfaces"][2]["vlans"] = {"untagged": [1], "tagged": [10, 20], "tagged_all": False}
|
||||
snapshot["interfaces"][0]["ip_addresses"] = ["10.1.0.1/24"]
|
||||
snapshot["vlan_names"] = {20: "Clients"}
|
||||
|
||||
plan = plan_switch_sync(nb, switch, snapshot)
|
||||
assert [(item["vid"], item["netbox_name"], item["name"]) for item in plan["vlans"]] == [
|
||||
(1, None, "VLAN1"), (10, "Server", "VLAN10"), (20, None, "Clients")]
|
||||
assert plan["networks"] == [{"network": "10.1.0.0/24", "vrf": "", "existing_vrfs": [], "create": True}]
|
||||
|
||||
# Not approved: nothing is created, only the existing VLAN 10 is assigned.
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||
assert (report["vlans_created"], report["prefixes_created"], report["vrfs_created"]) == (0, 0, 0)
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert nb.ipam.vlans.created == [] and nb.ipam.prefixes.created == []
|
||||
assert nb.dcim.interfaces.get(1).untagged_vlan == 110 and nb.dcim.interfaces.get(1).mode == "access"
|
||||
assert nb.ipam.ip_addresses.created[0]["tenant"] == 7 and nb.ipam.ip_addresses.created[0]["vrf"] is None
|
||||
|
||||
switch.update({"create_vlans": [20], "create_prefixes": ["10.1.0.0/24"],
|
||||
"network_vrfs": {"10.1.0.0/24": "Kunde-Mgmt"}})
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert report["errors"] == []
|
||||
assert nb.ipam.vrfs.created == [{"name": "Kunde-Mgmt", "tenant": 7}]
|
||||
vrf_id = nb.ipam.vrfs.records[0].id
|
||||
assert nb.ipam.prefixes.created == [{"prefix": "10.1.0.0/24", "status": "active", "tenant": 7, "vrf": vrf_id}]
|
||||
assert nb.ipam.vlans.created == [{"vid": 20, "name": "Clients", "status": "active", "tenant": 7}]
|
||||
port = nb.dcim.interfaces.get(3)
|
||||
assert port.mode == "tagged" and sorted(port.tagged_vlans) == sorted([110, nb.ipam.vlans.records[1].id])
|
||||
|
||||
|
||||
def test_switch_without_tenant_is_refused():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
nb.dcim.devices.get(1).tenant = None
|
||||
assert "keinen Mandanten" in plan_switch_sync(nb, switch, snapshot)["error"]
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot)
|
||||
assert "keinen Mandanten" in report["errors"][0] and nb.dcim.interfaces.updates == []
|
||||
|
||||
|
||||
def test_vlan_names_are_parsed():
|
||||
from netbox_sync.core.switches import parse_vlan_names
|
||||
assert parse_vlan_names('vlan 10\n name "Server"\n exit\nvlan 20\n name Clients\n#\n') == {
|
||||
10: "Server", 20: "Clients"}
|
||||
@@ -201,3 +201,103 @@ 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"]
|
||||
Reference in new issue
Block a user