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

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

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

No files matched your search

+2 -1
View File
@@ -1,11 +1,12 @@
.venv/
build/
dist/
__pycache__/
*.py[cod]
.pytest_cache/
*.zip
output/
# Lokale Konfigurationen und Zugangsdaten
config.json
*.tmp
-39
View File
@@ -1,39 +0,0 @@
# -*- mode: python ; coding: utf-8 -*-
a = Analysis(
['app.py'],
pathex=[],
binaries=[],
datas=[('netbox_vm_import.ico', '.')],
hiddenimports=[],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=[],
noarchive=False,
optimize=0,
)
pyz = PYZ(a.pure)
exe = EXE(
pyz,
a.scripts,
a.binaries,
a.datas,
[],
name='NetBox VM Import',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
upx_exclude=[],
runtime_tmpdir=None,
console=False,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
icon=['netbox_vm_import.ico'],
)
+97
View File
@@ -0,0 +1,97 @@
# -*- mode: python ; coding: utf-8 -*-
# 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.
import re
from pathlib import Path
from PyInstaller.utils.win32.versioninfo import (
FixedFileInfo,
StringFileInfo,
StringStruct,
StringTable,
VarFileInfo,
VarStruct,
VSVersionInfo,
)
ROOT = Path(SPECPATH)
META = (ROOT / "netbox_sync" / "__init__.py").read_text(encoding="utf-8")
VERSION = re.search(r'APP_VERSION = "([^"]+)"', META).group(1)
PUBLISHER = re.search(r'APP_PUBLISHER = "([^"]+)"', META).group(1)
NUMBERS = tuple(int(part) for part in (VERSION.split(".") + ["0", "0", "0"])[:4])
version_info = VSVersionInfo(
ffi=FixedFileInfo(filevers=NUMBERS, prodvers=NUMBERS),
kids=[
StringFileInfo([StringTable("040704B0", [
StringStruct("CompanyName", PUBLISHER),
StringStruct("FileDescription", "NetBox Synchronizer"),
StringStruct("FileVersion", VERSION),
StringStruct("InternalName", "NetBoxSynchronizer"),
StringStruct("OriginalFilename", "NetBoxSynchronizer.exe"),
StringStruct("ProductName", "NetBox Synchronizer"),
StringStruct("ProductVersion", VERSION),
StringStruct("LegalCopyright", f"© {PUBLISHER}"),
])]),
VarFileInfo([VarStruct("Translation", [0x0407, 1200])]),
],
)
a = Analysis(
["main.py"],
pathex=[str(ROOT)],
binaries=[],
datas=[("netbox_sync/resources", "resources")],
hiddenimports=[],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=["tkinter", "pytest", "PySide6.QtNetwork", "PySide6.QtQml", "PySide6.QtQuick", "PySide6.QtPdf"],
noarchive=False,
optimize=0,
)
# Qt ships much more than a widget application needs. Dropping the software
# OpenGL fallback, unused image plugins and foreign translations saves ~30 MB.
UNNEEDED = {
"opengl32sw.dll", "qdirect2d.dll", "qtiff.dll", "qwebp.dll", "qjpeg.dll", "qgif.dll", "qicns.dll",
"qtga.dll", "qwbmp.dll", "qpdf.dll",
}
a.binaries = [item for item in a.binaries if Path(item[0]).name.lower() not in UNNEEDED]
a.datas = [
item for item in a.datas
if "translations" not in Path(item[0]).parts or Path(item[0]).name.startswith(("qtbase_de", "qt_de"))
]
pyz = PYZ(a.pure)
exe = EXE(
pyz,
a.scripts,
[],
exclude_binaries=True,
name="NetBoxSynchronizer",
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=False,
console=False,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
icon=["netbox_sync/resources/app.ico"],
version=version_info,
)
coll = COLLECT(
exe,
a.binaries,
a.datas,
strip=False,
upx=False,
upx_exclude=[],
name="NetBoxSynchronizer",
)
+66 -33
View File
@@ -1,50 +1,83 @@
# NetBox VM Import Desktop
# NetBox Synchronizer
Windows-Desktopanwendung zum Synchronisieren virtueller Maschinen sowie HPE-/Aruba-Switche nach NetBox.
Windows-Desktopanwendung, die virtuelle Maschinen aus VMware vSphere und Proxmox VE sowie
HPE-/Aruba-Switche in NetBox dokumentiert.
## Installation
`NetBoxSynchronizer-Setup-<version>.exe` ausführen. Der 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.
Bestehende Kundenprofile der Vorgängerversion („NetBox VM Import“) werden automatisch übernommen.
## Funktionen
- Mehrere VMware- und Proxmox-Quellen pro Kundenprofil
- QEMU/KVM-VMs und optional LXC-Container aus Proxmox VE
- Mit Windows DPAPI verschlüsselte Passwörter, API-Token und Token-Secrets
- Automatische Übernahme des Cluster-Mandanten mit verbindlicher Bestätigung vor dem Sync
- Mandantenzuweisung für IPv4-/IPv6-Adressen und erkannte NetBox-Präfixe
- Gemeinsame Importmaske für alle neu erkannten Netze mit Subnetzgröße und vorausgefüllter VRF-Auswahl
- Mehrere neue VRFs direkt in der Netzwerkmaske anlegen; Namensfelder erscheinen nur bei Bedarf
- Auswahl vorhandener Mandanten-VRFs oder automatische VRF-Erstellung pro Cluster mit frei wählbarem Namen
- Wiederverwendung bereits vorhandener, zur IP passender Präfixe bei erneuten Imports
- Optionale Unterstützung selbstsignierter TLS-Zertifikate
- Synchronisierung von VMs, Hardwaredaten, Interfaces und IP-Adressen
- Übernahme primärer IPv4- und IPv6-Adressen
- Getrennte Haupt-Tabs für Virtualisierung und Switche
- Gemeinsame, synchronisierte Kundenprofil- und NetBox-Zielansicht in beiden Tabs
- Verschlüsselte SSH-Zugänge pro bestehendem NetBox-Switch
- SSH-Erkennung für Aruba CX, ArubaOS-Switch/ProCurve und HPE Comware
- Durchsuchbare, nach Mandant filterbare Auswahl vorhandener NetBox-Geräte
- Automatische Aktivierung von global deaktiviertem LLDP auf unterstützten Switches
- Synchronisierung von Switch-Schnittstellen und optionalen LLDP-/CDP-Verbindungen als NetBox-Kabel
- Auslesen und Synchronisieren vorhandener IPv4-/IPv6-Adressen auf Switch-Schnittstellen
- Robustes, vollständiges Einlesen großer SSH-Ausgaben von 48-Port-Switches
- Spezieller LLDP-Detailparser und ergänzender CDP-Fallback für Aruba-6100-Switches mit AOS-CX 10.13
- Skalierbares Switch-Protokoll sowie separates Fenster für Protokoll und SSH-Rohdaten
**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…7` Navigation, `F5` neu laden/auslesen, `Strg+F` Suche
## Verwendung
**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
- Import-Assistent in vier Schritten: **Ziel** (Cluster, 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
Die fertige Windows-Anwendung befindet sich unter `dist/NetBox VM Import.exe`.
**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
Profile werden im Benutzerprofil unter `%APPDATA%\NetBox VM Import\config.json` gespeichert. Passwort und Token sind an das jeweilige Windows-Benutzerkonto und den Rechner gebunden verschlüsselt.
**VRFs & Netze**
- Mehrere VRFs oder Präfixe für einen Mandanten gesammelt anlegen
## Entwicklung
```powershell
python -m venv .venv
py -3 -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install -r requirements.txt
python app.py
pip install -r requirements-dev.txt
python main.py # Anwendung starten
python -m pytest # Tests
```
## EXE erstellen
Projektstruktur:
```
netbox_sync/
core/ UI-unabhängige Logik: Konfiguration, NetBox, VMware/Proxmox, VM-Import, Switche
ui/ Qt-Oberfläche (PySide6): Hauptfenster, Seiten, Dialoge, Import-Assistent, Theme
resources/ Icons
installer/ Inno-Setup-Skript
tests/ pytest (Parser, Konfiguration, Sync gegen eine In-Memory-NetBox)
```
## Build & Installer
Voraussetzung für den Installer ist [Inno Setup 6](https://jrsoftware.org/isinfo.php)
(`winget install JRSoftware.InnoSetup`).
```powershell
pyinstaller "NetBox VM Import.spec"
.\build.ps1 # Tests, PyInstaller-Build und Installer
.\build.ps1 -SkipInstaller # nur dist\NetBoxSynchronizer\
```
Ergebnis: `dist\installer\NetBoxSynchronizer-Setup-<version>.exe`. Die Version steht in `netbox_sync/__init__.py`.
-2341
View File
File diff suppressed because it is too large. Load diff
+64
View File
@@ -0,0 +1,64 @@
<#
.SYNOPSIS
Baut NetBox Synchronizer: Tests, PyInstaller-Build und Inno-Setup-Installer.
.EXAMPLE
.\build.ps1 # alles
.\build.ps1 -SkipInstaller # nur dist\NetBoxSynchronizer\
.\build.ps1 -SkipTests
#>
param(
[switch]$SkipTests,
[switch]$SkipInstaller,
[string]$InnoSetupCompiler
)
$ErrorActionPreference = "Stop"
Set-Location $PSScriptRoot
$python = Join-Path $PSScriptRoot ".venv\Scripts\python.exe"
if (-not (Test-Path $python)) {
Write-Host "Erstelle virtuelle Umgebung …" -ForegroundColor Cyan
py -3 -m venv .venv
if ($LASTEXITCODE) { throw "Virtuelle Umgebung konnte nicht erstellt werden." }
}
Write-Host "Installiere Abhängigkeiten …" -ForegroundColor Cyan
& $python -m pip install --quiet --disable-pip-version-check -r requirements-dev.txt
if ($LASTEXITCODE) { throw "pip install fehlgeschlagen." }
if (-not $SkipTests) {
Write-Host "Führe Tests aus …" -ForegroundColor Cyan
& $python -m pytest -q
if ($LASTEXITCODE) { throw "Tests fehlgeschlagen – Build abgebrochen." }
}
$version = (Select-String -Path "netbox_sync\__init__.py" -Pattern 'APP_VERSION = "([^"]+)"').Matches[0].Groups[1].Value
Write-Host "Baue NetBox Synchronizer $version …" -ForegroundColor Cyan
& $python -m PyInstaller --noconfirm --clean --log-level WARN NetBoxSynchronizer.spec
if ($LASTEXITCODE) { throw "PyInstaller fehlgeschlagen." }
if ($SkipInstaller) {
Write-Host "Fertig: dist\NetBoxSynchronizer\NetBoxSynchronizer.exe" -ForegroundColor Green
return
}
if (-not $InnoSetupCompiler) {
$candidates = @(
(Get-Command iscc.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source),
"$env:LOCALAPPDATA\Programs\Inno Setup 6\ISCC.exe",
"${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe",
"$env:ProgramFiles\Inno Setup 6\ISCC.exe"
) | Where-Object { $_ -and (Test-Path $_) }
$InnoSetupCompiler = $candidates | Select-Object -First 1
}
if (-not $InnoSetupCompiler) {
Write-Warning "Inno Setup 6 wurde nicht gefunden. Installation z. B. mit: winget install JRSoftware.InnoSetup"
Write-Warning "Der Programmordner liegt trotzdem unter dist\NetBoxSynchronizer\."
exit 1
}
Write-Host "Erzeuge Installer …" -ForegroundColor Cyan
& $InnoSetupCompiler /Q "/DAppVersion=$version" "installer\NetBoxSynchronizer.iss"
if ($LASTEXITCODE) { throw "Inno Setup fehlgeschlagen." }
Write-Host "Fertig: dist\installer\NetBoxSynchronizer-Setup-$version.exe" -ForegroundColor Green
BIN
View File
Binary file not shown.
+82
View File
@@ -0,0 +1,82 @@
; Inno Setup 6 script for NetBox Synchronizer.
; Built by build.ps1, which passes the version: ISCC /DAppVersion=2.0.0 NetBoxSynchronizer.iss
#define AppName "NetBox Synchronizer"
#ifndef AppVersion
#define AppVersion "2.0.0"
#endif
#define AppPublisher "Louis-Alexander Kerst"
#define AppExeName "NetBoxSynchronizer.exe"
#define AppUserModelID "AlexanderKerst.NetBoxSynchronizer"
#define SourceDir "..\dist\NetBoxSynchronizer"
#define ConfigDir "NetBox VM Import"
[Setup]
AppId={{6F0B8E3C-4A9D-4C1E-9B7A-2D5E8F1A3C47}
AppName={#AppName}
AppVersion={#AppVersion}
AppVerName={#AppName} {#AppVersion}
AppPublisher={#AppPublisher}
DefaultDirName={autopf}\{#AppName}
DefaultGroupName={#AppName}
DisableProgramGroupPage=yes
; Installs per user without admin rights; the wizard offers "all users" as well.
PrivilegesRequired=lowest
PrivilegesRequiredOverridesAllowed=dialog
OutputDir=..\dist\installer
OutputBaseFilename=NetBoxSynchronizer-Setup-{#AppVersion}
SetupIconFile=..\netbox_sync\resources\app.ico
UninstallDisplayIcon={app}\{#AppExeName}
UninstallDisplayName={#AppName}
Compression=lzma2/ultra64
SolidCompression=yes
WizardStyle=modern
WizardSizePercent=110
ArchitecturesAllowed=x64compatible
ArchitecturesInstallIn64BitMode=x64compatible
MinVersion=10.0
CloseApplications=yes
RestartApplications=no
VersionInfoVersion={#AppVersion}
VersionInfoProductName={#AppName}
VersionInfoCompany={#AppPublisher}
ShowLanguageDialog=auto
[Languages]
Name: "german"; MessagesFile: "compiler:Languages\German.isl"
Name: "english"; MessagesFile: "compiler:Default.isl"
[CustomMessages]
german.DeleteUserData=Sollen auch die Kundenprofile (inklusive verschlüsselter Zugangsdaten) und Protokolle gelöscht werden?%n%nBei „Nein“ bleiben sie für eine spätere Neuinstallation erhalten.
english.DeleteUserData=Do you also want to delete the customer profiles (including encrypted credentials) and logs?%n%nChoose "No" to keep them for a later reinstallation.
[Tasks]
Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked
[InstallDelete]
; Remove libraries of the previous version before copying the new build.
Type: filesandordirs; Name: "{app}\_internal"
[Files]
Source: "{#SourceDir}\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
[Icons]
Name: "{autoprograms}\{#AppName}"; Filename: "{app}\{#AppExeName}"; AppUserModelID: "{#AppUserModelID}"
Name: "{autodesktop}\{#AppName}"; Filename: "{app}\{#AppExeName}"; AppUserModelID: "{#AppUserModelID}"; Tasks: desktopicon
[Run]
Filename: "{app}\{#AppExeName}"; Description: "{cm:LaunchProgram,{#AppName}}"; Flags: nowait postinstall skipifsilent
[Code]
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
var
DataDir: String;
begin
if (CurUninstallStep = usPostUninstall) and not UninstallSilent then
begin
DataDir := ExpandConstant('{userappdata}\{#ConfigDir}');
if DirExists(DataDir) then
if MsgBox(CustomMessage('DeleteUserData'), mbConfirmation, MB_YESNO or MB_DEFBUTTON2) = IDYES then
DelTree(DataDir, True, True, True);
end;
end;
+8
View File
@@ -0,0 +1,8 @@
"""Start script for development and PyInstaller: ``python main.py``."""
import sys
from netbox_sync.ui.app import main
if __name__ == "__main__":
sys.exit(main())
+10
View File
@@ -0,0 +1,10 @@
"""NetBox Synchronizer – VMs and switches from the field into NetBox."""
APP_NAME = "NetBox Synchronizer"
APP_VERSION = "2.0.0"
APP_PUBLISHER = "Louis-Alexander Kerst"
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
# The configuration folder keeps its historical name so existing customer
# profiles and DPAPI-encrypted secrets continue to work after the update.
CONFIG_DIR_NAME = "NetBox VM Import"
+5
View File
@@ -0,0 +1,5 @@
import sys
from netbox_sync.ui.app import main
sys.exit(main())
+1
View File
@@ -0,0 +1 @@
"""UI-independent synchronization logic."""
+229
View File
@@ -0,0 +1,229 @@
"""Customer profiles, application settings and DPAPI-protected secrets."""
import base64
import ctypes
import json
import logging
import os
import sys
from pathlib import Path
from netbox_sync import CONFIG_DIR_NAME
SECRET_KEYS = ("password", "token_secret")
CONFIG_VERSION = 5
DEFAULT_SETTINGS = {
"theme": "system", # system | light | dark
"parallel_ssh": 4, # concurrent switch discoveries
"enable_lldp": False, # allow configuration changes on switches
"create_cables": True,
}
log = logging.getLogger(__name__)
def config_dir():
if sys.platform == "win32":
base = Path(os.environ.get("APPDATA", Path.home()))
else:
base = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
return base / CONFIG_DIR_NAME
def config_path():
return config_dir() / "config.json"
def log_dir():
return config_dir() / "logs"
def known_hosts_path():
return config_dir() / "known_hosts"
# --------------------------------------------------------------------------
# Windows DPAPI
# --------------------------------------------------------------------------
if sys.platform == "win32":
from ctypes import wintypes
class _DataBlob(ctypes.Structure):
_fields_ = [("cbData", wintypes.DWORD), ("pbData", ctypes.POINTER(ctypes.c_byte))]
def _blob(data):
buffer = ctypes.create_string_buffer(data, len(data))
return _DataBlob(len(data), ctypes.cast(buffer, ctypes.POINTER(ctypes.c_byte))), buffer
class SecretError(RuntimeError):
"""A stored secret cannot be decrypted by the current Windows user."""
def protect(value):
"""Encrypt a value for the current Windows user with DPAPI."""
if not value:
return ""
if sys.platform != "win32":
raise RuntimeError("Verschlüsselte Profile werden derzeit nur unter Windows unterstützt.")
source, _buffer = _blob(value.encode("utf-8"))
result = _DataBlob()
if not ctypes.windll.crypt32.CryptProtectData(
ctypes.byref(source), "NetBox VM Import", None, None, None, 0, ctypes.byref(result)
):
raise ctypes.WinError()
try:
return base64.b64encode(ctypes.string_at(result.pbData, result.cbData)).decode("ascii")
finally:
ctypes.windll.kernel32.LocalFree(result.pbData)
def unprotect(value):
"""Decrypt a DPAPI value for the current Windows user."""
if not value:
return ""
if sys.platform != "win32":
raise SecretError("DPAPI ist nur unter Windows verfügbar.")
source, _buffer = _blob(base64.b64decode(value))
result = _DataBlob()
if not ctypes.windll.crypt32.CryptUnprotectData(
ctypes.byref(source), None, None, None, None, 0, ctypes.byref(result)
):
raise SecretError("Gespeichertes Geheimnis kann mit diesem Windows-Konto nicht entschlüsselt werden.")
try:
return ctypes.string_at(result.pbData, result.cbData).decode("utf-8")
finally:
ctypes.windll.kernel32.LocalFree(result.pbData)
# --------------------------------------------------------------------------
# Profile store
# --------------------------------------------------------------------------
def empty_profile(name):
return {
"name": name,
"netbox_url": "",
"netbox_token": "",
"netbox_ignore_ssl": False,
"sources": [],
"switches": [],
}
class ProfileStore:
def __init__(self, path=None):
self.path = Path(path) if path else config_path()
self.decrypt_failures = []
def _decrypt(self, value, context):
try:
return unprotect(value)
except Exception as error: # noqa: BLE001 - a broken secret must not block the app
self.decrypt_failures.append(context)
log.warning("Secret für %s nicht lesbar: %s", context, error)
return ""
def _decrypt_record(self, record, context):
item = dict(record)
for key in SECRET_KEYS:
encrypted_key = f"{key}_encrypted"
if encrypted_key in item:
item[key] = self._decrypt(item.pop(encrypted_key), context)
return item
def load(self):
"""Return ``(profiles, active_profile, settings)``."""
self.decrypt_failures = []
settings = dict(DEFAULT_SETTINGS)
if not self.path.exists():
return {}, "", settings
with self.path.open("r", encoding="utf-8") as stream:
data = json.load(stream)
settings.update({key: value for key, value in data.get("settings", {}).items() if key in DEFAULT_SETTINGS})
profiles = {}
for record in data.get("profiles", []):
name = record.get("name", "").strip()
if not name:
continue
profile = empty_profile(name)
profile.update({
"netbox_url": record.get("netbox_url", ""),
"netbox_token": self._decrypt(record.get("netbox_token_encrypted", ""), f"{name}: NetBox-Token"),
"netbox_ignore_ssl": bool(record.get("netbox_ignore_ssl", record.get("ignore_ssl_errors", False))),
})
for source in record.get("sources", []):
profile["sources"].append(self._decrypt_record(source, f"{name}: {source.get('name', 'Quelle')}"))
for switch in record.get("switches", []):
profile["switches"].append(self._decrypt_record(switch, f"{name}: {switch.get('name', 'Switch')}"))
# Migration from v2: one VMware source embedded in each profile.
if not profile["sources"] and record.get("esxi_host"):
profile["sources"].append({
"id": "vmware-legacy",
"type": "vmware",
"name": "VMware",
"enabled": True,
"host": record.get("esxi_host", ""),
"username": record.get("esxi_user", ""),
"password": self._decrypt(record.get("esxi_password_encrypted", ""), f"{name}: VMware"),
"ignore_ssl": bool(record.get("ignore_ssl_errors", False)),
})
profiles[name] = profile
# Migration from the first plaintext single-profile format.
if not profiles and any(key in data for key in ("esxi_host", "netbox_url")):
profile = empty_profile("Standard")
profile.update({
"netbox_url": data.get("netbox_url", ""),
"netbox_token": data.get("netbox_token", ""),
"netbox_ignore_ssl": bool(data.get("ignore_ssl_errors", False)),
"sources": [{
"id": "vmware-legacy",
"type": "vmware",
"name": "VMware",
"enabled": True,
"host": data.get("esxi_host", ""),
"username": data.get("esxi_user", ""),
"password": data.get("esxi_password", ""),
"ignore_ssl": bool(data.get("ignore_ssl_errors", False)),
}],
})
profiles["Standard"] = profile
return profiles, data.get("active_profile", ""), settings
@staticmethod
def _encrypt_record(record):
item = {key: value for key, value in record.items() if key not in SECRET_KEYS and not key.startswith("_")}
for key in SECRET_KEYS:
if key in record:
item[f"{key}_encrypted"] = protect(record.get(key, ""))
return item
def save(self, profiles, active_profile, settings=None):
records = []
for name in sorted(profiles, key=str.casefold):
profile = profiles[name]
records.append({
"name": name,
"netbox_url": profile.get("netbox_url", ""),
"netbox_token_encrypted": protect(profile.get("netbox_token", "")),
"netbox_ignore_ssl": bool(profile.get("netbox_ignore_ssl", False)),
"sources": [self._encrypt_record(source) for source in profile.get("sources", [])],
"switches": [self._encrypt_record(switch) for switch in profile.get("switches", [])],
})
payload = {
"version": CONFIG_VERSION,
"active_profile": active_profile,
"settings": dict(settings or DEFAULT_SETTINGS),
"profiles": records,
}
self.path.parent.mkdir(parents=True, exist_ok=True)
temp_path = self.path.with_suffix(".tmp")
with temp_path.open("w", encoding="utf-8") as stream:
json.dump(payload, stream, indent=2, ensure_ascii=False)
temp_path.replace(self.path)
+128
View File
@@ -0,0 +1,128 @@
"""Small helpers around pynetbox that both sync engines share."""
import re
import pynetbox
import requests
import urllib3
class NetBoxError(RuntimeError):
pass
class _TimeoutSession(requests.Session):
"""pynetbox issues requests without a timeout; never hang the UI forever."""
def __init__(self, timeout):
super().__init__()
self.default_timeout = timeout
def request(self, method, url, **kwargs):
kwargs.setdefault("timeout", self.default_timeout)
return super().request(method, url, **kwargs)
def connect(url, token, ignore_ssl=False, timeout=60):
"""Create a pynetbox API object and verify that URL and token work."""
url = (url or "").strip().rstrip("/")
if not url or not token:
raise NetBoxError("Bitte NetBox-URL und API-Token im Bereich „Verbindungen“ eintragen.")
if not url.startswith(("http://", "https://")):
url = f"https://{url}"
nb = pynetbox.api(url, token=token)
session = _TimeoutSession(timeout)
session.verify = not ignore_ssl
if ignore_ssl:
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
nb.http_session = session
try:
status = nb.status()
except requests.exceptions.SSLError as error:
raise NetBoxError(
"TLS-Zertifikat von NetBox ist nicht vertrauenswürdig. "
"Bei selbstsignierten Zertifikaten „Zertifikatsprüfung deaktivieren“ aktivieren."
) from error
except requests.exceptions.ConnectionError as error:
raise NetBoxError(f"NetBox unter {url} ist nicht erreichbar.") from error
except pynetbox.RequestError as error:
if getattr(error.req, "status_code", None) in (401, 403):
raise NetBoxError("NetBox hat den API-Token abgelehnt (fehlende Berechtigung oder ungültig).") from error
raise NetBoxError(f"NetBox-Anfrage fehlgeschlagen: {error}") from error
nb.netbox_version = str(status.get("netbox-version", "") or nb.version or "")
return nb
def version_tuple(nb):
text = getattr(nb, "netbox_version", "") or getattr(nb, "version", "") or ""
numbers = re.findall(r"\d+", text)
return tuple(int(value) for value in numbers[:2]) or (0, 0)
def uses_mac_objects(nb):
"""NetBox 4.2 moved MAC addresses into their own model."""
return version_tuple(nb) >= (4, 2)
def related_id(record, attribute):
value = getattr(record, attribute, None)
if value is None:
return None
if isinstance(value, dict):
return value.get("id")
if isinstance(value, int):
return value
return getattr(value, "id", None)
def related_name(record, attribute):
value = getattr(record, attribute, None)
if value is None:
return ""
if isinstance(value, dict):
return value.get("name") or value.get("display") or ""
return getattr(value, "name", None) or getattr(value, "display", None) or ""
def choice_value(record, attribute):
value = getattr(record, attribute, None)
if value is None:
return None
if isinstance(value, dict):
return value.get("value")
return getattr(value, "value", value)
def normalize_mac(value):
if not value:
return None
compact = re.sub(r"[^0-9a-fA-F]", "", str(value)).upper()
if len(compact) != 12:
return None
return ":".join(compact[index:index + 2] for index in range(0, 12, 2))
def assign_mac(nb, interface, mac, object_type):
"""Attach a MAC address to an interface for old and new NetBox versions."""
mac = normalize_mac(mac)
if not mac:
return False
if not uses_mac_objects(nb):
current = normalize_mac(getattr(interface, "mac_address", None))
if current == mac:
return False
interface.update({"mac_address": mac})
return True
matches = list(nb.dcim.mac_addresses.filter(
mac_address=mac, assigned_object_type=object_type, assigned_object_id=interface.id,
))
record = matches[0] if matches else nb.dcim.mac_addresses.create({
"mac_address": mac,
"assigned_object_type": object_type,
"assigned_object_id": interface.id,
})
if related_id(interface, "primary_mac_address") != record.id:
interface.update({"primary_mac_address": record.id})
return True
return not matches
+903
View File
@@ -0,0 +1,903 @@
"""SSH discovery and NetBox synchronization for HPE and Aruba switches."""
import ipaddress
import re
import threading
import time
from pathlib import Path
import paramiko
from netbox_sync.core.netbox import assign_mac, related_id
PLATFORMS = {
"auto": "Automatisch erkennen",
"aruba_cx": "Aruba CX (AOS-CX)",
"aruba_aos": "ArubaOS-Switch / ProCurve",
"hpe_comware": "HPE Comware",
}
COMMANDS = {
"aruba_cx": ("no page", "show interface brief", "show lldp neighbor-info detail"),
"aruba_aos": ("no page", "show interfaces brief", "show lldp info remote-device detail"),
"hpe_comware": ("screen-length disable", "display interface brief", "display lldp neighbor-information verbose"),
}
IP_COMMANDS = {
"aruba_cx": ("show ip interface brief", "show ipv6 interface brief"),
"aruba_aos": ("show ip", "show ipv6"),
"hpe_comware": ("display ip interface brief", "display ipv6 interface brief"),
}
LLDP_CONTROL = {
"aruba_cx": {
"status": "show lldp configuration",
"disabled": r"LLDP Enabled\s*:\s*No",
"enable": ("configure terminal", "lldp", "end"),
},
"aruba_aos": {
"status": "show lldp config",
"disabled": r"LLDP (?:Enabled|Run)\s*:\s*(?:No|False)|LLDP operation.*disabled",
"enable": ("configure terminal", "lldp run", "exit"),
},
"hpe_comware": {
"status": "display lldp status",
"disabled": r"Global status of LLDP\s*:\s*Disable",
"enable": ("system-view", "lldp global enable", "return"),
},
}
ANSI_ESCAPE = re.compile(r"\x1b(?:\][^\x07]*(?:\x07|\x1b\\)|\[[0-?]*[ -/]*[@-~]|[@-_]|[=>])")
TERMINAL_CONTROL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
MAC_PATTERN = re.compile(r"(?i)\b(?:[0-9a-f]{2}[:-]){5}[0-9a-f]{2}\b|\b[0-9a-f]{4}(?:-[0-9a-f]{4}){2}\b")
# "host#", "host>", Comware "<host>" and Comware system-view "[host]".
CLI_PROMPT = re.compile(r"(?:^|\n)(?:[^\r\n]*[>#]|\s*\[[^\[\]\r\n]+\])[ \t]*(?:\n)?\Z")
COMWARE_PROMPT = re.compile(r"(?:^|\n)\s*[<\[][^<>\[\]\r\n]+[>\]][ \t]*\Z")
CLI_ERROR = re.compile(r"(?i)invalid input|unknown command|unrecognized command|% ?wrong parameter|incomplete command")
_HOSTKEY_LOCK = threading.Lock()
def _noop(*_args, **_kwargs):
return None
class HostKeyChangedError(RuntimeError):
pass
# --------------------------------------------------------------------------
# Interface names
# --------------------------------------------------------------------------
# Every spelling maps to one short token so that e.g. Comware "GE1/0/1",
# NetBox "GigabitEthernet1/0/1" and a Cisco neighbor "Gi1/0/1" compare equal.
_NAME_ALIASES = {
"ge": "ge", "gi": "ge", "gigabitethernet": "ge", "gigethernet": "ge",
"xge": "xge", "te": "xge", "tengigabitethernet": "xge", "tengige": "xge",
"wge": "wge", "twe": "wge", "twentyfivegige": "wge", "twentyfivegigabitethernet": "wge",
"fge": "fge", "fo": "fge", "fortygige": "fge", "fortygigabitethernet": "fge",
"hge": "hge", "hu": "hge", "hundredgige": "hge", "hundredgigabitethernet": "hge",
"fa": "fe", "fastethernet": "fe",
"mge": "mge", "mgigabitethernet": "mge",
"bagg": "bagg", "bridgeaggregation": "bagg",
"ragg": "ragg", "routeaggregation": "ragg",
"po": "po", "portchannel": "po",
"vlan": "vlan", "vl": "vlan", "vlaninterface": "vlan", "vlanif": "vlan",
"loop": "lo", "lo": "lo", "loopback": "lo",
"eth": "eth", "et": "eth", "ethernet": "eth",
}
_COMWARE_EXPANSION = {
"GE": "GigabitEthernet", "XGE": "Ten-GigabitEthernet", "FGE": "FortyGigE", "HGE": "HundredGigE",
"WGE": "Twenty-FiveGigE", "MGE": "M-GigabitEthernet", "BAGG": "Bridge-Aggregation",
"RAGG": "Route-Aggregation", "VLAN": "Vlan-interface", "LOOP": "LoopBack",
}
_NAME_SPLIT = re.compile(r"^([A-Za-z][A-Za-z\- ]*?)\s*(\d[\d/:.]*)$")
def interface_key(value):
"""Normalized comparison key for interface names across vendors."""
value = (value or "").strip()
match = _NAME_SPLIT.match(value)
if match:
prefix = re.sub(r"[\s\-_]", "", match.group(1)).casefold()
return _NAME_ALIASES.get(prefix, prefix) + match.group(2)
return re.sub(r"[\s\-_]", "", value).casefold()
def expand_comware_name(name):
match = _NAME_SPLIT.match(name)
if not match:
return name
full = _COMWARE_EXPANSION.get(match.group(1).upper())
return f"{full}{match.group(2)}" if full else name
def _interface_name(token):
token = token.strip(" |:")
return bool(re.match(
r"(?i)^(?:\d+(?:/\d+){0,3}|[A-Z]{1,2}\d{1,2}|"
r"(?:GE|XGE|HGE|FGE|WGE|MGE|FortyGigE|HundredGigE|Ten-GigabitEthernet|GigabitEthernet|M-GigabitEthernet)\S+|"
r"Bridge-Aggregation\d+|BAGG\d+|RAGG\d+|Trk\d+|lag\d+|Vlan-interface\d+|vlan\s*\d+|Loop(?:Back)?\d+|"
r"loopback\s*\d*|lo\d+|mgmt)$",
token,
))
# --------------------------------------------------------------------------
# SSH session handling
# --------------------------------------------------------------------------
def clean_output(value):
value = ANSI_ESCAPE.sub("", value).replace("\r", "")
value = TERMINAL_CONTROL.sub("", value)
return re.sub(r"--\s*MORE\s*--|Press any key to continue.*", "", value, flags=re.I)
def _read_available(channel, timeout=20, initialize_session=False):
chunks = []
started = time.monotonic()
next_nudge = started + 0.5
nudges = 0
while time.monotonic() - started < timeout:
if channel.recv_ready():
chunks.append(channel.recv(65535).decode("utf-8", errors="replace"))
# The command is complete when the device prompt returns. This
# avoids truncating output at a short pause and fixed delays.
if CLI_PROMPT.search(clean_output("".join(chunks))):
break
now = time.monotonic()
if initialize_session and nudges < 3 and now >= next_nudge:
# ArubaOS-S may stop at the login banner until a key is pressed.
channel.send("\r")
nudges += 1
next_nudge = now + 1.5
time.sleep(0.05)
output = clean_output("".join(chunks))
if not CLI_PROMPT.search(output):
tail = " | ".join(line.strip() for line in output.splitlines()[-3:] if line.strip())
detail = f" Letzte Ausgabe: {tail[-300:]}" if tail else " Keine Ausgabe vom Switch empfangen."
raise TimeoutError("Der Switch hat die CLI-Ausgabe nicht mit einem vollständigen Prompt abgeschlossen." + detail)
return output
def _run_cli_command(channel, command, timeout=20):
channel.send(command + "\n")
try:
return _read_available(channel, timeout=timeout)
except TimeoutError as error:
raise TimeoutError(f"CLI-Befehl nicht vollständig abgeschlossen: {command}. {error}") from error
class _TrustOnFirstUse(paramiko.MissingHostKeyPolicy):
"""Remember unknown host keys; paramiko rejects changed keys afterwards."""
def __init__(self, path, log):
self.path = Path(path)
self.log = log
def missing_host_key(self, client, hostname, key):
with _HOSTKEY_LOCK:
keys = paramiko.HostKeys()
if self.path.exists():
keys.load(str(self.path))
keys.add(hostname, key.get_name(), key)
self.path.parent.mkdir(parents=True, exist_ok=True)
keys.save(str(self.path))
fingerprint = key.fingerprint if hasattr(key, "fingerprint") else key.get_base64()[:24]
self.log(f"{hostname}: neuer SSH-Hostschlüssel gespeichert ({key.get_name()} {fingerprint})")
def _host_entry(host, port):
return host if int(port) == 22 else f"[{host}]:{port}"
def forget_host_key(known_hosts, host, port=22):
path = Path(known_hosts)
if not path.exists():
return False
with _HOSTKEY_LOCK:
keys = paramiko.HostKeys(str(path))
entry = _host_entry(host, port)
if entry not in keys:
return False
del keys[entry]
keys.save(str(path))
return True
def _open_client(config, known_hosts, log):
client = paramiko.SSHClient()
if known_hosts:
if Path(known_hosts).exists():
with _HOSTKEY_LOCK:
client.load_host_keys(str(known_hosts))
client.set_missing_host_key_policy(_TrustOnFirstUse(known_hosts, log))
else:
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(
hostname=config["host"],
port=int(config.get("port", 22)),
username=config["username"],
password=config["password"],
look_for_keys=False,
allow_agent=False,
timeout=12,
auth_timeout=12,
banner_timeout=12,
)
except paramiko.BadHostKeyException as error:
client.close()
raise HostKeyChangedError(
f"Der SSH-Hostschlüssel von {config['host']} hat sich geändert! Mögliche Ursache: Austausch des "
"Geräts – oder ein Angriff. Falls der Wechsel erwartet ist, im Switch-Dialog "
"„Gespeicherten Hostschlüssel vergessen“ wählen."
) from error
except paramiko.AuthenticationException as error:
client.close()
raise PermissionError("SSH-Anmeldung abgelehnt – Benutzername oder Passwort prüfen.") from error
except Exception:
client.close()
raise
return client
def detect_platform(channel, banner):
"""Identify the switch OS from prompt and ``show version`` output."""
if COMWARE_PROMPT.search(banner):
return "hpe_comware"
_run_cli_command(channel, "no page")
version = _run_cli_command(channel, "show version", timeout=30)
if re.search(r"(?i)ArubaOS-CX|AOS-CX|\b[A-Z]{2}\.10\.\d+", version):
return "aruba_cx"
if re.search(r"(?i)Image stamp|ProCurve|\b[A-Z]{1,2}\.1[456]\.\d+", version):
return "aruba_aos"
display = _run_cli_command(channel, "display version", timeout=30)
if re.search(r"(?i)Comware", display):
return "hpe_comware"
raise RuntimeError("Plattform konnte nicht automatisch erkannt werden – bitte im Switch-Dialog manuell wählen.")
def run_switch_commands(config, enable_lldp=False, known_hosts=None, log=_noop):
platform = config.get("platform", "auto")
if platform not in PLATFORMS:
raise ValueError(f"Nicht unterstützte Switch-Plattform: {platform}")
client = _open_client(config, known_hosts, log)
try:
channel = client.invoke_shell(width=240, height=1000)
try:
banner = _read_available(channel, timeout=45, initialize_session=True)
except TimeoutError as error:
raise TimeoutError(f"SSH-Anmeldung nicht mit einem vollständigen CLI-Prompt abgeschlossen. {error}") from error
if platform == "auto":
platform = detect_platform(channel, banner)
log(f"{config.get('name', config['host'])}: Plattform erkannt – {PLATFORMS[platform]}")
pager_command, interface_command, neighbor_command = COMMANDS[platform]
_run_cli_command(channel, pager_command)
control = LLDP_CONTROL[platform]
lldp_status = _run_cli_command(channel, control["status"])
lldp_disabled = bool(re.search(control["disabled"], lldp_status, flags=re.I))
lldp_enabled_automatically = False
if lldp_disabled and enable_lldp:
enable_output = [_run_cli_command(channel, command) for command in control["enable"]]
combined = "\n".join(enable_output)
if platform == "hpe_comware" and CLI_ERROR.search(combined):
_run_cli_command(channel, "system-view")
combined = _run_cli_command(channel, "lldp enable")
combined += "\n" + _run_cli_command(channel, "return")
if re.search(r"(?i)permission denied|authorization failed|access denied", combined):
raise PermissionError("LLDP konnte mangels Konfigurationsrechten nicht aktiviert werden.")
if CLI_ERROR.search(combined):
raise RuntimeError("Der LLDP-Aktivierungsbefehl wird von diesem Switch nicht unterstützt.")
lldp_enabled_automatically = True
time.sleep(2)
interfaces = _run_cli_command(channel, interface_command, timeout=45)
ip_outputs = [_run_cli_command(channel, command, timeout=35) for command in IP_COMMANDS[platform]]
neighbors = _run_cli_command(channel, neighbor_command, timeout=60)
if platform == "aruba_cx" and CLI_ERROR.search(neighbors):
neighbors = _run_cli_command(channel, "show lldp neighbor-info", timeout=60)
cdp_neighbors = ""
if platform == "aruba_cx":
cdp_summary = _run_cli_command(channel, "show cdp neighbor-info", timeout=35)
cdp_ports = []
for line in cdp_summary.splitlines():
match = re.match(r"^\s*(\d+/\d+/\d+)\s+\S+", line)
if match and match.group(1) not in cdp_ports:
cdp_ports.append(match.group(1))
details = [_run_cli_command(channel, f"show cdp neighbor-info {port}", timeout=30) for port in cdp_ports]
cdp_neighbors = "\n".join([cdp_summary, *details])
return {
"platform": platform,
"interfaces": interfaces,
"ipv4_interfaces": ip_outputs[0],
"ipv6_interfaces": ip_outputs[1],
"neighbors": neighbors,
"cdp_neighbors": cdp_neighbors,
"lldp_status": lldp_status,
"lldp_disabled": lldp_disabled and not lldp_enabled_automatically,
"lldp_enabled_automatically": lldp_enabled_automatically,
}
finally:
client.close()
# --------------------------------------------------------------------------
# Parsers
# --------------------------------------------------------------------------
def speed_mbps(text):
gig = re.search(r"(?i)\b(\d+(?:\.\d+)?)\s*Gig", text)
if gig:
return int(float(gig.group(1)) * 1000)
matches = re.findall(r"(?i)\b(\d+(?:\.\d+)?)\s*(T|G|M)(?:b(?:it)?|bps)?(?:T|X|SR|LR|CR)?\b", text)
if not matches:
duplex = re.search(r"(?i)\b(\d+)(?:FDx|HDx)\b", text)
if duplex:
return int(duplex.group(1))
trailing = re.search(r"\b(\d{2,6})\s*$", text)
return int(trailing.group(1)) if trailing else None
value, unit = matches[-1]
return int(float(value) * {"M": 1, "G": 1000, "T": 1_000_000}[unit.upper()])
def _interface(name, **values):
record = {
"name": name, "enabled": True, "connected": False, "speed_mbps": None, "media": "",
"mac_address": None, "description": "", "neighbor": None, "ip_addresses": [], "virtual": False,
}
record.update(values)
return record
def _parse_aos_interfaces(output):
"""ArubaOS-S: ``Port Type | Alert Enabled Status Mode ...``."""
interfaces = []
seen = set()
for raw_line in clean_output(output).splitlines():
if "|" not in raw_line:
continue
left, right = raw_line.split("|", 1)
left_tokens = left.split()
right_tokens = right.split()
if not left_tokens or not _interface_name(left_tokens[0]) or len(right_tokens) < 3:
continue
name = left_tokens[0]
if name in seen:
continue
enabled_value, status_value = right_tokens[1].lower(), right_tokens[2].lower()
if enabled_value not in ("yes", "no") or status_value not in ("up", "down"):
continue
mode = right_tokens[3] if len(right_tokens) > 3 else ""
interfaces.append(_interface(
name,
enabled=enabled_value == "yes",
connected=status_value == "up",
speed_mbps=speed_mbps(mode) if status_value == "up" else None,
media=left_tokens[1] if len(left_tokens) > 1 else "",
))
seen.add(name)
return interfaces
def parse_interfaces(output, platform):
if platform == "aruba_aos":
return _parse_aos_interfaces(output)
interfaces = []
seen = set()
for raw_line in clean_output(output).splitlines():
line = raw_line.strip()
if not line or set(line) <= {"-", "=", " "}:
continue
tokens = re.split(r"\s+", line)
name_index = next((index for index, token in enumerate(tokens[:3]) if _interface_name(token)), None)
if name_index is None:
continue
name = tokens[name_index].strip(" |:")
if platform == "hpe_comware":
name = expand_comware_name(name)
if name in seen:
continue
lower = line.lower()
if not re.search(r"\b(up|down|adm|administratively down|disabled|enabled)\b", lower):
continue
enabled = not re.search(r"administratively down|admin.*down|\badm\b|disabled|\bno\s+(?:up|down)\b", lower)
connected = bool(re.search(r"\bup\b", lower)) and not re.search(r"\bdown\b", lower)
mac_match = MAC_PATTERN.search(line)
media = tokens[name_index + 3] if platform == "aruba_cx" and len(tokens) > name_index + 3 else ""
interfaces.append(_interface(
name,
enabled=bool(enabled),
connected=connected,
speed_mbps=speed_mbps(line),
media=media,
mac_address=mac_match.group(0) if mac_match else None,
))
seen.add(name)
return interfaces
def _address_with_mask(address, mask=None):
try:
if "/" in address:
return str(ipaddress.ip_interface(address))
if mask:
return str(ipaddress.ip_interface(f"{address}/{mask}"))
except ValueError:
return None
return None
def parse_interface_ips(ipv4_output, ipv6_output, platform):
entries = []
if platform == "aruba_aos":
current_interface = ""
for line in clean_output(ipv4_output).splitlines():
if "|" not in line:
continue
interface_column, values = line.split("|", 1)
candidate = interface_column.strip()
if candidate and not re.search(r"(?i)^VLAN$", candidate) and not set(candidate) <= {"-", "+", " "}:
current_interface = candidate
addresses = re.findall(r"\b\d{1,3}(?:\.\d{1,3}){3}\b", values)
if current_interface and len(addresses) >= 2:
address = _address_with_mask(addresses[0], addresses[1])
if address and not address.startswith("0.0.0.0/"):
entries.append({"interface": current_interface, "address": address})
current_interface = ""
for line in clean_output(ipv6_output).splitlines():
vlan_match = re.match(r"^\s*Vlan Name\s*:\s*(.+)$", line, flags=re.I)
if vlan_match:
current_interface = vlan_match.group(1).strip()
address_match = re.search(r"([0-9a-fA-F:]+/\d{1,3})", line)
if address_match and current_interface:
address = _address_with_mask(address_match.group(1))
if address and not address.lower().startswith("fe80:"):
entries.append({"interface": current_interface, "address": address})
else:
for output, version in ((ipv4_output, 4), (ipv6_output, 6)):
pattern = r"\b(\d+(?:\.\d+){3}/\d{1,2})\b" if version == 4 else r"\b([0-9a-fA-F]*:[0-9a-fA-F:]+/\d{1,3})\b"
for line in clean_output(output).splitlines():
tokens = re.split(r"\s+", line.strip())
if len(tokens) < 2 or not _interface_name(tokens[0]):
continue
match = re.search(pattern, line)
if not match:
continue
address = _address_with_mask(match.group(1))
if not address or address.startswith("0.0.0.0/") or address.lower().startswith("fe80:"):
continue
name = expand_comware_name(tokens[0]) if platform == "hpe_comware" else tokens[0]
entries.append({"interface": name, "address": address})
unique = {}
for entry in entries:
unique[(interface_key(entry["interface"]), entry["address"])] = entry
return list(unique.values())
def _field(block, patterns):
for pattern in patterns:
match = re.search(pattern, block, flags=re.I | re.M)
if match:
return match.group(1).strip()
return ""
def parse_neighbors(output):
clean = clean_output(output)
# "Port : 1/1/1" (CX) starts a record, but "Port ID : …" or
# "Port description : …" inside a Comware record must not.
starts = list(re.finditer(
r"(?im)^\s*(?:Port\s*:|Local (?:Port|Interface|Intf)\s*[: ]|LLDP neighbor-information of port\s).*$",
clean,
))
if not starts:
return _parse_neighbor_table(clean)
neighbors = []
for index, start in enumerate(starts):
end = starts[index + 1].start() if index + 1 < len(starts) else len(clean)
block = clean[start.start():end]
local_port = _field(block, (
r"^\s*Port\s*:\s*(\S+)",
r"^\s*Local (?:Port|Interface|Intf)\s*[: ]\s*(\S+)",
r"^\s*LLDP neighbor-information of port\s+(?:\d+\[)?([^\]\s:]+)\]?",
))
system_name = _field(block, (
r"^\s*Neighbor Chassis-Name\s*:\s*(.+)$",
r"^[ \t]*Neighbor System-Name[ \t]*:[ \t]*(.*)$",
r"^[ \t]*(?:System Name|SysName)[ \t]*:[ \t]*(.*)$",
r"^\s*Neighbor name\s*[: ]\s*(.+)$",
))
if not system_name:
system_name = _field(block, (r"^[ \t]*Neighbor Chassis-ID[ \t]*:[ \t]*(.+)$", r"^[ \t]*ChassisId[ \t]*:[ \t]*(.+)$"))
remote_port = _field(block, (
r"^\s*Neighbor Port-ID\s*:\s*(.+)$",
r"^[ \t]*(?:Port ID|PortId)[ \t]*:[ \t]*(.*)$",
r"^\s*Port ID subtype.*\n\s*Port ID\s*[: ]\s*(.+)$",
r"^\s*Neighbor Port-Desc\s*:\s*(.+)$",
r"^\s*(?:Port Description|PortDesc|PortDescr)\s*[: ]\s*(.+)$",
))
port_description = _field(block, (
r"^\s*Neighbor Port-Desc\s*:\s*(.+)$",
r"^\s*(?:Port Description|PortDesc|PortDescr)\s*[: ]\s*(.+)$",
))
management_ip = _field(block, (
r"^\s*Neighbor Management-Address\s*:\s*([0-9a-fA-F:.]+)",
r"^\s*(?:Management Address|Management address|Management IP)\s*[: ]\s*([0-9a-fA-F:.]+)",
r"^[ \t]*Address[ \t]*:[ \t]*([0-9a-fA-F:.]+)[ \t]*$",
))
if local_port and (system_name or remote_port):
neighbors.append({
"local_port": local_port,
"system_name": system_name,
"remote_port": remote_port,
"port_description": port_description,
"management_ip": management_ip,
"protocol": "LLDP",
})
return neighbors
def parse_cdp_neighbors(output):
"""Parse detailed AOS-CX CDP records into the common neighbor shape."""
clean = clean_output(output)
starts = list(re.finditer(r"(?im)^\s*Local Port\s*:\s*\S+", clean))
neighbors = []
for index, start in enumerate(starts):
end = starts[index + 1].start() if index + 1 < len(starts) else len(clean)
block = clean[start.start():end]
local_port = _field(block, (r"^\s*Local Port\s*:\s*(\S+)",))
system_name = _field(block, (r"^\s*Device ID\s*:\s*(.+)$", r"^\s*System Name\s*:\s*(.+)$"))
remote_port = _field(block, (r"^\s*Neighbor Port-ID\s*:\s*(.+)$", r"^\s*Port ID\s*:\s*(.+)$"))
management_ip = _field(block, (r"^\s*Address\s*:\s*([0-9a-fA-F:.]+)", r"^\s*Management Address\s*:\s*([0-9a-fA-F:.]+)"))
if local_port and (system_name or remote_port or management_ip):
neighbors.append({
"local_port": local_port,
"system_name": system_name,
"remote_port": remote_port,
"port_description": "",
"management_ip": management_ip,
"protocol": "CDP",
})
return neighbors
def _parse_neighbor_table(output):
neighbors = []
for raw_line in output.splitlines():
line = raw_line.strip()
if not line or set(line) <= {"-", "=", " "}:
continue
tokens = re.split(r"\s+", line.replace("|", " | "))
if not tokens or not _interface_name(tokens[0]):
continue
if "|" in tokens:
remaining = tokens[tokens.index("|") + 1:]
if len(remaining) < 3:
continue
remote_port, system_name = remaining[1], remaining[-1]
else:
if len(tokens) < 5:
continue
remote_port, system_name = tokens[2], tokens[-1]
neighbors.append({
"local_port": tokens[0], "system_name": system_name, "remote_port": remote_port,
"port_description": "", "management_ip": "", "protocol": "LLDP",
})
return neighbors
def build_snapshot(outputs, platform):
interfaces = parse_interfaces(outputs["interfaces"], platform)
interface_ips = parse_interface_ips(outputs.get("ipv4_interfaces", ""), outputs.get("ipv6_interfaces", ""), platform)
lldp_neighbors = parse_neighbors(outputs["neighbors"])
cdp_neighbors = parse_cdp_neighbors(outputs.get("cdp_neighbors", ""))
# LLDP normally contains richer data. CDP fills ports for which CX did not
# return an LLDP record, without duplicating a physical local interface.
neighbors = list(lldp_neighbors)
occupied = {interface_key(item["local_port"]) for item in neighbors}
for neighbor in cdp_neighbors:
key = interface_key(neighbor["local_port"])
if key not in occupied:
neighbors.append(neighbor)
occupied.add(key)
interface_map = {interface_key(interface["name"]): interface for interface in interfaces}
for item in interface_ips:
key = interface_key(item["interface"])
interface = interface_map.get(key)
if not interface:
interface = _interface(item["interface"], connected=True, description="Logisches Layer-3-Interface", virtual=True)
interfaces.append(interface)
interface_map[key] = interface
interface["ip_addresses"].append(item["address"])
for neighbor in neighbors:
local = interface_map.get(interface_key(neighbor["local_port"]))
if local:
local["neighbor"] = neighbor
return {
"platform": platform,
"interfaces": interfaces,
"ip_addresses": interface_ips,
"neighbors": neighbors,
"lldp_neighbors": lldp_neighbors,
"cdp_neighbors": cdp_neighbors,
"raw": outputs,
"lldp_disabled": outputs.get("lldp_disabled", False),
"lldp_enabled_automatically": outputs.get("lldp_enabled_automatically", False),
"discovered_at": time.time(),
}
def discover_switch(config, enable_lldp=False, known_hosts=None, log=_noop):
outputs = run_switch_commands(config, enable_lldp=enable_lldp, known_hosts=known_hosts, log=log)
return build_snapshot(outputs, outputs["platform"])
# --------------------------------------------------------------------------
# Platform suggestion from NetBox data
# --------------------------------------------------------------------------
def suggest_platform(*texts):
"""Guess the switch OS from NetBox platform, manufacturer and model names."""
text = " ".join(str(value or "") for value in texts).casefold()
if not text.strip():
return "auto"
if re.search(r"comware|h3c|\b(?:19[0-9]0|51[234]0|55[01]0|57[01]0|59[0-9]0|75\d\d|10500|12500|12900)\b", text):
return "hpe_comware"
if re.search(r"aos-?cx|arubaos-?cx|\bcx\b|\b(?:4100i|6000|6100|6200[fm]?|6300[fm]?|6400|8100|8320|8325|8360|8400|9300|10000)\b", text):
return "aruba_cx"
if re.search(r"procurve|aos-?s\b|arubaos-?switch|provision|\b(?:2530|2540|2620|2920|2930[fm]?|3800|3810m?|5400r?l?|5406|5412)\b", text):
return "aruba_aos"
return "auto"
# --------------------------------------------------------------------------
# NetBox synchronization
# --------------------------------------------------------------------------
def netbox_interface_type(interface):
if interface.get("virtual"):
return "virtual"
key = interface_key(interface["name"])
if re.match(r"^(?:lag|trk|bagg|ragg|po)\d", key):
return "lag"
if re.match(r"^(?:vlan|lo)\d", key):
return "virtual"
media = (interface.get("media") or "").casefold()
if media and media != "--":
if "qsfp28" in media or "100g" in media:
return "100gbase-x-qsfp28"
if "qsfp" in media or "40g" in media:
return "40gbase-x-qsfpp"
if "sfp28" in media or "25g" in media:
return "25gbase-x-sfp28"
if "smartrate" in media or "2.5g" in media or "mgig" in media:
return "2.5gbase-t"
if re.search(r"10gbe?-?t\b|10gbaset", media):
return "10gbase-t"
if "sfp+" in media or "10g" in media:
return "10gbase-x-sfpp"
if "sfp" in media or "1000sx" in media or "1000lx" in media or "gbic" in media:
return "1000base-x-sfp"
if re.search(r"1000t|1gbt|1gbaset", media):
return "1000base-t"
if "100tx" in media or "100/" in media:
return "100base-tx"
prefix = re.match(r"^[a-z]+", key)
by_prefix = {"xge": "10gbase-x-sfpp", "wge": "25gbase-x-sfp28", "fge": "40gbase-x-qsfpp",
"hge": "100gbase-x-qsfp28", "ge": "1000base-t", "fe": "100base-tx", "mge": "1000base-t"}
if prefix and prefix.group(0) in by_prefix:
return by_prefix[prefix.group(0)]
speed = interface.get("speed_mbps")
if not speed:
return "other"
for threshold, value in ((100_000, "100gbase-x-qsfp28"), (40_000, "40gbase-x-qsfpp"),
(25_000, "25gbase-x-sfp28"), (10_000, "10gbase-x-sfpp"), (1000, "1000base-t")):
if speed >= threshold:
return value
return "100base-tx"
def _device_interfaces(nb, device_id):
records = {}
for record in nb.dcim.interfaces.filter(device_id=device_id):
key = interface_key(record.name)
# Prefer a template-created full name over a stray short duplicate.
if key not in records or len(record.name) > len(records[key].name):
records[key] = record
return records
class _RemoteLookup:
"""Find neighbor devices and interfaces in NetBox, cached per sync run."""
def __init__(self, nb):
self.nb = nb
self.devices = {}
self.interfaces = {}
def device(self, neighbor):
name = (neighbor.get("system_name") or "").strip()
cache_key = (name.casefold(), neighbor.get("management_ip"))
if cache_key in self.devices:
return self.devices[cache_key]
found = None
for candidate in dict.fromkeys(filter(None, (name, name.split(".")[0]))):
matches = list(self.nb.dcim.devices.filter(name__ie=candidate))
if len(matches) == 1:
found = matches[0]
break
if not found and neighbor.get("management_ip"):
for ip in self.nb.ipam.ip_addresses.filter(address=neighbor["management_ip"]):
if getattr(ip, "assigned_object_type", "") == "dcim.interface":
device_id = related_id(ip.assigned_object, "device")
if device_id:
found = self.nb.dcim.devices.get(device_id)
break
self.devices[cache_key] = found
return found
def interface(self, device, neighbor):
if device.id not in self.interfaces:
self.interfaces[device.id] = _device_interfaces(self.nb, device.id)
records = self.interfaces[device.id]
candidates = [neighbor.get("remote_port"), neighbor.get("port_description")]
if neighbor.get("port_description"):
candidates.append(neighbor["port_description"].split()[0])
for candidate in filter(None, candidates):
record = records.get(interface_key(candidate))
if record:
return record
return None
def _new_report():
return {
"interfaces_created": 0, "interfaces_updated": 0, "interfaces_unchanged": 0,
"ips_created": 0, "ips_updated": 0, "ips_unchanged": 0,
"cables_created": 0, "cables_skipped": 0,
"changes": [], "errors": [],
}
def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=False, log=_noop):
"""Write a discovery snapshot to NetBox.
With ``dry_run`` nothing is written; the returned report lists what would
change. Interface types are only set when an interface is created, so
device-type templates and manual corrections in NetBox are preserved.
"""
report = _new_report()
device_id = int(config["device_id"])
device = nb.dcim.devices.get(device_id)
if not device:
report["errors"].append(f"NetBox-Gerät #{device_id} existiert nicht mehr")
return report
tenant_id = related_id(device, "tenant")
existing = _device_interfaces(nb, device_id)
records = {}
for interface in snapshot["interfaces"]:
key = interface_key(interface["name"])
record = existing.get(key)
try:
if record:
changes = {}
if bool(getattr(record, "enabled", True)) != bool(interface.get("enabled", True)):
changes["enabled"] = bool(interface.get("enabled", True))
if changes:
report["interfaces_updated"] += 1
state = "aktivieren" if changes["enabled"] else "deaktivieren"
report["changes"].append(f"Interface {record.name}: {state}")
if not dry_run:
record.update(changes)
else:
report["interfaces_unchanged"] += 1
else:
payload = {
"device": device_id,
"name": interface["name"],
"type": netbox_interface_type(interface),
"enabled": bool(interface.get("enabled", True)),
}
if interface.get("description"):
payload["description"] = interface["description"][:200]
report["interfaces_created"] += 1
report["changes"].append(f"Interface {interface['name']} neu ({payload['type']})")
if not dry_run:
record = nb.dcim.interfaces.create(payload)
existing[key] = record
if record and not dry_run and interface.get("mac_address"):
assign_mac(nb, record, interface["mac_address"], "dcim.interface")
records[key] = record
except Exception as error: # noqa: BLE001
report["errors"].append(f"Interface {interface['name']}: {error}")
for interface in snapshot["interfaces"]:
key = interface_key(interface["name"])
if key not in records:
continue
record = records[key]
for address in interface.get("ip_addresses", []):
try:
host = str(ipaddress.ip_interface(address).ip)
candidates = [
item for item in nb.ipam.ip_addresses.filter(address=host)
if related_id(item, "vrf") is None
]
if len(candidates) > 1:
raise ValueError("mehrere globale IP-Adressen mit diesem Host gefunden")
payload = {"address": address, "status": "active", "assigned_object_type": "dcim.interface"}
if record:
payload["assigned_object_id"] = record.id
if tenant_id:
payload["tenant"] = tenant_id
if candidates:
current = candidates[0]
differs = (
str(current.address) != address
or getattr(current, "assigned_object_type", None) != "dcim.interface"
or getattr(current, "assigned_object_id", None) != payload.get("assigned_object_id")
or (tenant_id and related_id(current, "tenant") != tenant_id)
)
if differs:
report["ips_updated"] += 1
report["changes"].append(f"IP {address} → {interface['name']}")
if not dry_run:
current.update(payload)
else:
report["ips_unchanged"] += 1
else:
report["ips_created"] += 1
report["changes"].append(f"IP {address} neu auf {interface['name']}")
if not dry_run:
nb.ipam.ip_addresses.create(payload)
except Exception as error: # noqa: BLE001
report["errors"].append(f"IP-Adresse {address} auf {interface['name']}: {error}")
if create_cables:
lookup = _RemoteLookup(nb)
for neighbor in snapshot["neighbors"]:
label = f"{neighbor.get('local_port')} → {neighbor.get('system_name')} {neighbor.get('remote_port')}"
try:
key = interface_key(neighbor["local_port"])
if key not in records:
continue
local = records[key]
if local is not None and getattr(local, "cable", None):
report["cables_skipped"] += 1
continue
remote_device = lookup.device(neighbor)
if not remote_device:
report["cables_skipped"] += 1
continue
if remote_device.id == device_id:
continue
remote = lookup.interface(remote_device, neighbor)
if not remote or getattr(remote, "cable", None):
report["cables_skipped"] += 1
continue
report["cables_created"] += 1
report["changes"].append(f"Kabel {device.name} {label}")
if not dry_run:
nb.dcim.cables.create({
"a_terminations": [{"object_type": "dcim.interface", "object_id": local.id}],
"b_terminations": [{"object_type": "dcim.interface", "object_id": remote.id}],
"status": "connected",
})
remote.cable = True # avoid a second cable from the reverse direction
except Exception as error: # noqa: BLE001
report["errors"].append(f"Nachbar {label}: {error}")
return report
def describe_snapshot(snapshot):
return (
f"{len(snapshot['interfaces'])} Schnittstellen, {len(snapshot.get('ip_addresses', []))} IP-Adressen, "
f"{len(snapshot.get('lldp_neighbors', []))} LLDP- und {len(snapshot.get('cdp_neighbors', []))} CDP-Nachbarn"
)
+326
View File
@@ -0,0 +1,326 @@
"""Read virtual machines from VMware vSphere and Proxmox VE."""
import ipaddress
import re
import ssl
import requests
import urllib3
SOURCE_TYPES = {"vmware": "VMware vSphere", "proxmox": "Proxmox VE"}
def _noop(*_args, **_kwargs):
return None
# --------------------------------------------------------------------------
# IP helpers
# --------------------------------------------------------------------------
def valid_guest_ip(value):
try:
address = ipaddress.ip_interface(value).ip if "/" in value else ipaddress.ip_address(value)
return not (address.is_loopback or address.is_link_local or address.is_unspecified)
except ValueError:
return False
def ip_with_prefix(value):
"""Return ``address/prefix``; guess /24 or /64 if the hypervisor omits it."""
try:
if "/" in value:
return str(ipaddress.ip_interface(value))
address = ipaddress.ip_address(value)
return f"{address}/24" if address.version == 4 else f"{address}/64"
except ValueError:
return None
def source_endpoint(source):
return source.get("host") or source.get("url") or ""
# --------------------------------------------------------------------------
# VMware
# --------------------------------------------------------------------------
def load_vmware_source(source, log=_noop):
from pyVim.connect import Disconnect, SmartConnect
from pyVmomi import vim
log(f"Verbinde zu VMware: {source['name']} …")
context = ssl._create_unverified_context() if source.get("ignore_ssl") else None
service_instance = SmartConnect(
host=source["host"], user=source["username"], pwd=source["password"], sslContext=context
)
try:
content = service_instance.RetrieveContent()
view = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True)
try:
# Fetch every required VM property in one PropertyCollector call.
# Accessing properties on each ManagedObject separately is extremely
# slow on vCenter because every access may cause another SOAP request.
traversal = vim.PropertyCollector.TraversalSpec(
name="vmViewTraversal", type=vim.view.ContainerView, path="view", skip=False,
)
object_spec = vim.PropertyCollector.ObjectSpec(obj=view, skip=True, selectSet=[traversal])
property_spec = vim.PropertyCollector.PropertySpec(
type=vim.VirtualMachine, all=False, pathSet=[
"name", "config.hardware.memoryMB", "config.hardware.numCPU",
"config.hardware.device", "config.guestFullName", "config.template",
"runtime.powerState", "guest.net",
],
)
filter_spec = vim.PropertyCollector.FilterSpec(objectSet=[object_spec], propSet=[property_spec])
result = content.propertyCollector.RetrievePropertiesEx(
[filter_spec], vim.PropertyCollector.RetrieveOptions()
)
objects = list(result.objects or []) if result else []
while result and result.token:
result = content.propertyCollector.ContinueRetrievePropertiesEx(result.token)
objects.extend(result.objects or [])
normalized = []
for item in objects:
properties = {prop.name: prop.val for prop in (item.propSet or [])}
if properties.get("name") and not properties.get("config.template"):
normalized.append(_normalize_vmware_vm(properties, source, vim))
return normalized
finally:
view.Destroy()
finally:
Disconnect(service_instance)
def _normalize_vmware_vm(properties, source, vim):
disks = sum(
round(device.capacityInKB / 1024)
for device in properties.get("config.hardware.device", []) or []
if isinstance(device, vim.vm.device.VirtualDisk)
)
interfaces = []
for index, net in enumerate(properties.get("guest.net", []) or []):
mac = getattr(net, "macAddress", None)
if not mac:
continue
interfaces.append({
"name": getattr(net, "device", None) or f"NIC-{index}",
"mac": mac,
"ips": _vmware_guest_ips(net),
})
return {
"name": properties["name"],
"source": source["name"],
"source_type": "VMware",
"kind": "VM",
"status": "active" if "poweredOn" in str(properties.get("runtime.powerState", "")) else "offline",
"vcpus": int(properties.get("config.hardware.numCPU", 0) or 0),
"memory": int(properties.get("config.hardware.memoryMB", 0) or 0),
"disk": disks,
"guest_os": properties.get("config.guestFullName", "") or "",
"interfaces": interfaces,
}
def _vmware_guest_ips(net):
"""Prefer VMware-reported prefix lengths and retain legacy IP fallback."""
ips = []
ip_config = getattr(net, "ipConfig", None)
for entry in (getattr(ip_config, "ipAddress", None) or []):
value = getattr(entry, "ipAddress", None)
prefix = getattr(entry, "prefixLength", None)
if value and valid_guest_ip(value):
ips.append(f"{value}/{prefix}" if prefix is not None else value)
known = {str(ipaddress.ip_interface(value).ip if "/" in value else ipaddress.ip_address(value)) for value in ips}
for value in (getattr(net, "ipAddress", None) or []):
if not valid_guest_ip(value):
continue
normalized = str(ipaddress.ip_address(value))
if normalized not in known:
ips.append(value)
known.add(normalized)
return ips
# --------------------------------------------------------------------------
# Proxmox
# --------------------------------------------------------------------------
def _proxmox_session(source):
session = requests.Session()
session.verify = not source.get("ignore_ssl")
if source.get("ignore_ssl"):
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
session.headers["Authorization"] = f"PVEAPIToken={source['token_id']}={source['token_secret']}"
return session
def _proxmox_get(session, base_url, path):
response = session.get(f"{base_url}/api2/json{path}", timeout=30)
if response.status_code == 401:
raise PermissionError("Proxmox hat Token-ID oder Token-Secret abgelehnt.")
response.raise_for_status()
return response.json().get("data")
def load_proxmox_source(source, log=_noop):
log(f"Verbinde zu Proxmox: {source['name']} …")
session = _proxmox_session(source)
resources = _proxmox_get(session, source["url"], "/cluster/resources?type=vm") or []
log(f"{source['name']}: Cluster-API meldet {len(resources)} Ressourcen")
# Some restricted API tokens may not see the cluster-wide resource
# endpoint. Try the per-node endpoints as a compatible fallback.
if not resources:
resources = _proxmox_resources_by_node(session, source)
log(f"{source['name']}: Node-Abfrage meldet {len(resources)} Ressourcen")
result = []
for resource in resources:
kind = resource.get("type")
if kind not in ("qemu", "lxc") or _is_template(resource.get("template")):
continue
if kind == "lxc" and not source.get("include_lxc", True):
continue
try:
result.append(_normalize_proxmox_guest(session, source, resource))
except Exception as error: # noqa: BLE001 - one broken guest must not stop the source
log(f"{source['name']} / VMID {resource.get('vmid')}: {error}", "warning")
if not result:
raise RuntimeError(
"API erreichbar, aber keine sichtbaren VMs/LXCs gefunden. "
"Dem Benutzer und dem API-Token mindestens PVEAuditor auf /vms zuweisen."
)
return result
def _proxmox_resources_by_node(session, source):
resources = []
kinds = ["qemu"] + (["lxc"] if source.get("include_lxc", True) else [])
for node_data in _proxmox_get(session, source["url"], "/nodes") or []:
node = node_data.get("node")
if not node:
continue
for kind in kinds:
for guest in _proxmox_get(session, source["url"], f"/nodes/{node}/{kind}") or []:
resources.append({**guest, "node": node, "type": kind})
return resources
def _is_template(value):
return str(value).strip().lower() in ("1", "true", "yes")
def _normalize_proxmox_guest(session, source, resource):
kind = resource["type"]
node = resource["node"]
vmid = resource["vmid"]
config = _proxmox_get(session, source["url"], f"/nodes/{node}/{kind}/{vmid}/config") or {}
interfaces = proxmox_interfaces(config, kind)
if kind == "qemu" and resource.get("status") == "running":
_add_qemu_agent_ips(session, source, node, vmid, interfaces)
return {
"name": resource.get("name") or f"{kind}-{vmid}",
"source": source["name"],
"source_type": "Proxmox",
"kind": "LXC" if kind == "lxc" else "VM",
"status": "active" if resource.get("status") == "running" else "offline",
"vcpus": int(resource.get("maxcpu") or config.get("cores") or 0),
"memory": round(int(resource.get("maxmem") or 0) / 1024 / 1024) or int(config.get("memory") or 0),
"disk": round(int(resource.get("maxdisk") or 0) / 1024 / 1024),
"guest_os": proxmox_os_name(config.get("ostype", ""), kind),
"interfaces": interfaces,
}
def proxmox_interfaces(config, kind):
interfaces = []
for key in sorted(config):
if not re.fullmatch(r"net\d+", key):
continue
values = parse_proxmox_options(str(config[key]))
if kind == "qemu":
mac = next(
(value for name, value in values.items() if name in ("virtio", "e1000", "e1000e", "vmxnet3", "rtl8139")),
None,
)
name = key
ips = []
else:
mac = values.get("hwaddr")
name = values.get("name", key)
ip_value = values.get("ip", "")
ips = [ip_value] if ip_value and ip_value not in ("dhcp", "manual") else []
ip6_value = values.get("ip6", "")
if ip6_value and ip6_value not in ("dhcp", "auto", "manual"):
ips.append(ip6_value)
if mac:
interfaces.append({"name": name, "mac": mac, "ips": ips})
return interfaces
def parse_proxmox_options(value):
result = {}
for part in value.split(","):
if "=" in part:
key, item = part.split("=", 1)
result[key.strip().lower()] = item.strip()
return result
def _add_qemu_agent_ips(session, source, node, vmid, interfaces):
try:
payload = _proxmox_get(session, source["url"], f"/nodes/{node}/qemu/{vmid}/agent/network-get-interfaces") or {}
except (requests.RequestException, ValueError, KeyError):
# The guest agent is optional; configured MAC addresses are still useful.
return
agent_interfaces = payload.get("result", []) if isinstance(payload, dict) else payload
by_mac = {interface["mac"].lower(): interface for interface in interfaces}
for agent_interface in agent_interfaces or []:
target = by_mac.get((agent_interface.get("hardware-address") or "").lower())
if not target:
continue
for address in agent_interface.get("ip-addresses", []):
ip = address.get("ip-address")
prefix = address.get("prefix")
if ip and valid_guest_ip(ip):
target["ips"].append(f"{ip}/{prefix}" if prefix is not None else ip)
def proxmox_os_name(ostype, kind):
names = {
"win11": "Microsoft Windows 11", "win10": "Microsoft Windows 10/2016/2019",
"win8": "Microsoft Windows 8/2012", "win7": "Microsoft Windows 7/2008 R2",
"winxp": "Microsoft Windows XP", "l26": "Linux 2.6+", "l24": "Linux 2.4",
"solaris": "Solaris", "other": "Other",
}
return names.get(ostype, "Linux Container" if kind == "lxc" else ostype)
# --------------------------------------------------------------------------
# Common entry points
# --------------------------------------------------------------------------
def load_source(source, log=_noop):
if source.get("type") == "proxmox":
return load_proxmox_source(source, log)
return load_vmware_source(source, log)
def test_source(source):
"""Check credentials quickly and return a short human readable result."""
if source.get("type") == "proxmox":
session = _proxmox_session(source)
version = _proxmox_get(session, source["url"], "/version") or {}
return f"Proxmox VE {version.get('version', '?')} erreichbar"
from pyVim.connect import Disconnect, SmartConnect
context = ssl._create_unverified_context() if source.get("ignore_ssl") else None
instance = SmartConnect(host=source["host"], user=source["username"], pwd=source["password"], sslContext=context)
try:
about = instance.RetrieveContent().about
return f"{about.fullName} erreichbar"
finally:
Disconnect(instance)
+431
View File
@@ -0,0 +1,431 @@
"""Import virtual machines, interfaces, IP addresses and prefixes into NetBox."""
import ipaddress
from netbox_sync.core.netbox import assign_mac, related_id, related_name
from netbox_sync.core.virtualization import ip_with_prefix, valid_guest_ip
GLOBAL_VRF = None # NetBox "global" routing table
def _noop(*_args, **_kwargs):
return None
def vrf_label(vrf):
rd = getattr(vrf, "rd", None)
return f"{vrf.name} (RD: {rd})" if rd else vrf.name
def suggested_prefixlen(interface):
"""IPv4 defaults to /24 because guests often report host masks; IPv6 keeps its prefix."""
return 24 if interface.version == 4 else interface.network.prefixlen
def prefix_choices(host_address, detected_prefixlen):
host = ipaddress.ip_address(host_address)
if host.version == 4:
return list(range(8, 31))
return sorted({32, 40, 48, 52, 56, 60, 64, 80, 96, 112, 120, 124, 126, 127, 128, detected_prefixlen})
class VMSyncEngine:
"""Holds NetBox lookup data and performs the VM import.
The engine is used from worker threads. It never touches UI objects; all
feedback goes through the ``log`` callback ``log(text, level="info")``.
"""
def __init__(self, nb, log=_noop):
self.nb = nb
self.log = log
self.clusters = {}
self.cluster_tenants = {}
self.tenants = {}
self.vrfs = []
self.platforms = []
self.existing_vms = {}
self._reset_run_state()
def _reset_run_state(self):
self.synced_prefixes = set()
self.prefix_plans = []
self.preexisting_prefixes = []
# ------------------------------------------------------------------
# NetBox lookup data
# ------------------------------------------------------------------
def load_targets(self):
self.log("Lade Cluster, Mandanten, VRFs und Plattformen aus NetBox …")
clusters = list(self.nb.virtualization.clusters.all())
self.clusters = {item.name: item.id for item in clusters}
self.tenants = {item.name: item.id for item in self.nb.tenancy.tenants.all()}
self.vrfs = list(self.nb.ipam.vrfs.all())
self.platforms = list(self.nb.dcim.platforms.all())
self.cluster_tenants = {}
for cluster in clusters:
tenant_id = related_id(cluster, "tenant")
tenant_name = related_name(cluster, "tenant")
if tenant_id and tenant_name:
self.cluster_tenants[cluster.name] = {"id": tenant_id, "name": tenant_name}
self.tenants.setdefault(tenant_name, tenant_id)
self.existing_vms = {}
for vm in self.nb.virtualization.virtual_machines.filter(brief=True):
self.existing_vms.setdefault(vm.name, []).append(vm.id)
self.log(
f"NetBox: {len(self.clusters)} Cluster, {len(self.tenants)} Mandanten, "
f"{len(self.vrfs)} VRFs, {sum(map(len, self.existing_vms.values()))} VMs"
)
def tenant_vrfs(self, tenant_id):
return sorted(
(vrf for vrf in self.vrfs if related_id(vrf, "tenant") == tenant_id),
key=lambda item: item.name.casefold(),
)
def vrf_name(self, vrf_id):
if vrf_id is None:
return "Global"
return next((vrf.name for vrf in self.vrfs if vrf.id == vrf_id), f"VRF #{vrf_id}")
def get_or_create_tenant_vrf(self, vrf_name, tenant_id):
existing = next(
(vrf for vrf in self.vrfs if vrf.name == vrf_name and related_id(vrf, "tenant") == tenant_id),
None,
)
if existing:
self.log(f"Vorhandene VRF verwendet: {vrf_name}")
return existing.id
vrf = self.nb.ipam.vrfs.create({
"name": vrf_name,
"tenant": tenant_id,
"enforce_unique": True,
"description": "Automatisch erstellt durch NetBox Synchronizer",
})
self.vrfs.append(vrf)
self.log(f"VRF erstellt: {vrf_name}", "success")
return vrf.id
def get_platform_id(self, guest_os):
guest_os = (guest_os or "").lower()
if not guest_os:
return None
for platform in self.platforms:
name = platform.name.lower()
if name in guest_os or guest_os in name:
return platform.id
return None
# ------------------------------------------------------------------
# Prefix lookups
# ------------------------------------------------------------------
def find_prefixes_in_vrf(self, network, vrf_id):
return [
prefix for prefix in self.nb.ipam.prefixes.filter(prefix=str(network))
if related_id(prefix, "vrf") == vrf_id
]
def find_covering_prefixes(self, host_address, allowed_vrf_ids):
host = ipaddress.ip_address(host_address)
try:
candidates = list(self.nb.ipam.prefixes.filter(contains=str(host)))
except Exception as error: # noqa: BLE001
self.log(f"Präfixsuche für {host} nicht möglich: {error}", "warning")
return []
matches = []
for prefix in candidates:
prefix_vrf_id = related_id(prefix, "vrf")
if prefix_vrf_id not in allowed_vrf_ids:
continue
try:
parsed = ipaddress.ip_network(str(prefix.prefix))
except ValueError:
continue
if host in parsed:
matches.append((parsed.prefixlen, prefix, str(parsed), prefix_vrf_id))
return matches
def _allowed_vrfs(self, tenant_id, default_vrf_id):
return {vrf.id for vrf in self.tenant_vrfs(tenant_id)} | {default_vrf_id}
@staticmethod
def _reusable_prefix(covering, default_vrf_id):
default_matches = [match for match in covering if match[3] == default_vrf_id]
if default_matches:
return max(default_matches, key=lambda match: match[0])
if len({match[3] for match in covering}) == 1:
return max(covering, key=lambda match: match[0])
return None
# ------------------------------------------------------------------
# Import plan
# ------------------------------------------------------------------
def detect_missing_networks(self, vms, tenant_id, default_vrf_id):
"""Return networks of the selected VMs that NetBox does not know yet."""
self._reset_run_state()
detected = {}
for vm in vms:
for interface in vm.get("interfaces", []):
for ip_value in dict.fromkeys(interface.get("ips", [])):
address = ip_with_prefix(ip_value) if valid_guest_ip(ip_value) else None
if not address:
continue
parsed = ipaddress.ip_interface(address)
length = suggested_prefixlen(parsed)
network = ipaddress.ip_network(f"{parsed.ip}/{length}", strict=False)
entry = detected.setdefault(str(network), {
"host_address": parsed.ip,
"host_addresses": set(),
"detected_prefixlen": parsed.network.prefixlen,
"suggested_prefixlen": length,
"suggested_network": network,
"vms": set(),
})
entry["host_addresses"].add(parsed.ip)
entry["vms"].add(vm["name"])
allowed = self._allowed_vrfs(tenant_id, default_vrf_id)
missing = []
for item in detected.values():
group_is_missing = False
for host in item["host_addresses"]:
reusable = self._reusable_prefix(self.find_covering_prefixes(host, allowed), default_vrf_id)
if reusable:
cached = reusable[1:]
if cached not in self.preexisting_prefixes:
self.preexisting_prefixes.append(cached)
else:
group_is_missing = True
if group_is_missing:
missing.append(item)
self.log(
f"Netzwerkprüfung: {len(detected)} Netz(e) erkannt, {len(missing)} davon fehlen in NetBox"
)
return missing
def apply_network_plan(self, decisions, tenant_id):
"""Create VRFs requested in the plan and remember the confirmed networks."""
for decision in decisions:
if decision.get("create_vrf"):
decision["vrf_id"] = self.get_or_create_tenant_vrf(decision["vrf_name"], tenant_id)
decision["create_vrf"] = False
self.prefix_plans = list(decisions)
def classify_vms(self, vms):
"""Return how many selected VMs are new or already exist in NetBox."""
new = sum(1 for vm in vms if vm["name"] not in self.existing_vms)
return new, len(vms) - new
# ------------------------------------------------------------------
# VM synchronization
# ------------------------------------------------------------------
def _find_vm(self, name, cluster_id):
in_cluster = list(self.nb.virtualization.virtual_machines.filter(name=name, cluster_id=cluster_id))
if in_cluster:
return in_cluster[0]
anywhere = list(self.nb.virtualization.virtual_machines.filter(name=name))
if len(anywhere) == 1:
self.log(f"{name}: in anderem Cluster gefunden – wird in den Zielcluster verschoben", "warning")
return anywhere[0]
if len(anywhere) > 1:
raise RuntimeError("mehrere gleichnamige VMs in anderen Clustern – Zuordnung nicht eindeutig")
return None
def _find_ip(self, host_address, vrf_id):
candidates = list(self.nb.ipam.ip_addresses.filter(
address=host_address, vrf_id=vrf_id if vrf_id is not None else "null",
))
if len(candidates) > 1:
raise RuntimeError(f"IP-Adresse {host_address} ist in dieser VRF mehrfach vorhanden")
return candidates[0] if candidates else None
def sync_vm(self, source_vm, cluster_id, tenant_id, vrf_id):
"""Create or update one VM. Returns ``"created"`` or ``"updated"``."""
payload = {
"name": source_vm["name"], "cluster": cluster_id, "status": source_vm["status"],
"vcpus": source_vm["vcpus"], "memory": source_vm["memory"], "disk": source_vm["disk"],
"tenant": tenant_id,
}
platform_id = self.get_platform_id(source_vm.get("guest_os"))
if platform_id:
payload["platform"] = platform_id
netbox_vm = self._find_vm(source_vm["name"], cluster_id)
if netbox_vm:
netbox_vm.update(payload)
outcome = "updated"
self.log(f"VM aktualisiert: {source_vm['name']}")
else:
netbox_vm = self.nb.virtualization.virtual_machines.create(payload)
outcome = "created"
self.existing_vms.setdefault(source_vm["name"], []).append(netbox_vm.id)
self.log(f"VM erstellt: {source_vm['name']}", "success")
primary_ipv4 = None
primary_ipv6 = None
for interface in source_vm.get("interfaces", []):
netbox_interface = self.nb.virtualization.interfaces.get(
virtual_machine_id=netbox_vm.id, name=interface["name"]
)
interface_payload = {"virtual_machine": netbox_vm.id, "name": interface["name"], "enabled": True}
if netbox_interface:
netbox_interface.update(interface_payload)
else:
netbox_interface = self.nb.virtualization.interfaces.create(interface_payload)
try:
assign_mac(self.nb, netbox_interface, interface.get("mac"), "virtualization.vminterface")
except Exception as error: # noqa: BLE001 - MAC is optional metadata
self.log(f"{source_vm['name']}/{interface['name']}: MAC-Adresse nicht gesetzt ({error})", "warning")
for ip_value in dict.fromkeys(interface.get("ips", [])):
address = ip_with_prefix(ip_value) if valid_guest_ip(ip_value) else None
if not address:
continue
effective_vrf_id = self.sync_prefix_tenant(address, tenant_id, vrf_id)
ip_payload = {
"address": address, "status": "active", "tenant": tenant_id, "vrf": effective_vrf_id,
"assigned_object_type": "virtualization.vminterface",
"assigned_object_id": netbox_interface.id,
}
try:
host_address = str(ipaddress.ip_interface(address).ip)
ip_object = self._find_ip(host_address, effective_vrf_id)
if ip_object:
ip_object.update(ip_payload)
else:
ip_object = self.nb.ipam.ip_addresses.create(ip_payload)
except Exception as error:
raise RuntimeError(f"IP-Adresse {address}: {error}") from error
version = ipaddress.ip_interface(address).version
if version == 4 and not primary_ipv4:
primary_ipv4 = ip_object.id
elif version == 6 and not primary_ipv6:
primary_ipv6 = ip_object.id
primary = {}
if primary_ipv4:
primary["primary_ip4"] = primary_ipv4
if primary_ipv6:
primary["primary_ip6"] = primary_ipv6
if primary:
netbox_vm.update(primary)
return outcome
def sync_prefix_tenant(self, address, tenant_id, default_vrf_id):
"""Assign the tenant to the matching prefix and apply the confirmed network plan."""
parsed_interface = ipaddress.ip_interface(address)
host_address = parsed_interface.ip
network = str(parsed_interface.network)
vrf_id = default_vrf_id
for existing_prefix, existing_network, existing_vrf_id in self.preexisting_prefixes:
if host_address in ipaddress.ip_network(existing_network):
if (existing_network, existing_vrf_id) not in self.synced_prefixes:
existing_prefix.update({"tenant": tenant_id})
self.synced_prefixes.add((existing_network, existing_vrf_id))
self.log(f"Vorhandenes Netzwerk übernommen: {existing_network}")
return existing_vrf_id
for cached_network, cached_vrf in self.synced_prefixes:
if host_address in ipaddress.ip_network(cached_network):
return cached_vrf
cache_key = (network, vrf_id)
candidates = self.find_prefixes_in_vrf(network, vrf_id)
if len(candidates) > 1:
self.log(f"Präfix {network} nicht geändert: mehrere passende Präfixe gefunden", "warning")
return vrf_id
try:
if candidates:
candidates[0].update({"tenant": tenant_id})
self.log(f"Mandant am Präfix aktualisiert: {network}")
else:
covering = self.find_covering_prefixes(host_address, self._allowed_vrfs(tenant_id, vrf_id))
reusable = self._reusable_prefix(covering, vrf_id)
if reusable:
_, existing_prefix, existing_network, existing_vrf_id = reusable
existing_prefix.update({"tenant": tenant_id})
self.synced_prefixes.add((existing_network, existing_vrf_id))
self.log(f"Vorhandenes Netzwerk übernommen: {existing_network}")
return existing_vrf_id
matching_plans = [
decision for decision in self.prefix_plans
if host_address in ipaddress.ip_network(decision["network"])
]
if not matching_plans:
self.log(f"Kein Präfix für {host_address} angelegt (nicht im Netzwerkplan)")
return vrf_id
decision = max(matching_plans, key=lambda item: ipaddress.ip_network(item["network"]).prefixlen)
network = decision["network"]
vrf_id = decision["vrf_id"]
cache_key = (network, vrf_id)
selected = self.find_prefixes_in_vrf(network, vrf_id)
if len(selected) > 1:
self.log(f"Präfix {network} nicht geändert: mehrere passende Präfixe gefunden", "warning")
return vrf_id
if selected:
selected[0].update({"tenant": tenant_id})
self.log(f"Mandant am Präfix aktualisiert: {network}")
else:
payload = {"prefix": network, "status": "active", "tenant": tenant_id}
if vrf_id is not None:
payload["vrf"] = vrf_id
self.nb.ipam.prefixes.create(payload)
self.log(f"Präfix erstellt: {network}", "success")
except Exception as error:
raise RuntimeError(f"Präfix {network}: {error}") from error
self.synced_prefixes.add(cache_key)
return vrf_id
# ------------------------------------------------------------------
# IPAM batch tools
# ------------------------------------------------------------------
def create_vrfs_batch(self, tenant_name, names):
tenant_id = self.tenants[tenant_name]
created = reused = 0
errors = []
for name in names:
exists = any(vrf.name == name for vrf in self.tenant_vrfs(tenant_id))
try:
self.get_or_create_tenant_vrf(name, tenant_id)
reused += exists
created += not exists
except Exception as error: # noqa: BLE001
errors.append(f"{name}: {error}")
self.log(f"VRF {name}: {error}", "error")
return created, reused, errors
def create_prefixes_batch(self, tenant_name, vrf_id, values):
tenant_id = self.tenants[tenant_name]
created = reused = 0
canonical = []
errors = []
for value in values:
try:
network = ipaddress.ip_network(value, strict=False)
network_text = str(network)
candidates = self.find_prefixes_in_vrf(network_text, vrf_id)
if len(candidates) > 1:
raise ValueError("mehrere identische Präfixe in dieser VRF gefunden")
if candidates:
candidates[0].update({"tenant": tenant_id})
reused += 1
else:
payload = {"prefix": network_text, "status": "active", "tenant": tenant_id}
if vrf_id is not None:
payload["vrf"] = vrf_id
self.nb.ipam.prefixes.create(payload)
created += 1
canonical.append(network_text)
self.log(f"Netzwerk verarbeitet: {network_text}")
except Exception as error: # noqa: BLE001
errors.append(f"{value}: {error}")
self.log(f"Netzwerk {value}: {error}", "error")
return created, reused, canonical, errors
File renamed without changes.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 65 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 416 KiB

After

Width:  |  Height:  |  Size: 416 KiB

+1
View File
@@ -0,0 +1 @@
"""Qt user interface."""
+363
View File
@@ -0,0 +1,363 @@
"""Long-running operations started from the UI. Everything here runs in background tasks."""
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from PySide6.QtCore import QTimer
from netbox_sync.core import netbox
from netbox_sync.core.config import known_hosts_path
from netbox_sync.core.netbox import NetBoxError, related_name
from netbox_sync.core.switches import (
PLATFORMS,
describe_snapshot,
discover_switch,
suggest_platform,
sync_snapshot_to_netbox,
)
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.dialogs import SyncPreviewDialog
from netbox_sync.ui.tasks import area_log, logger
def _device_row(device):
primary = getattr(device, "primary_ip", None) or getattr(device, "primary_ip4", None)
address = ""
if primary is not None:
address = str(getattr(primary, "address", None) or (primary.get("address") if isinstance(primary, dict) else ""))
device_type = getattr(device, "device_type", None)
model = related_name(device, "device_type") or getattr(device_type, "model", "") or ""
manufacturer = related_name(device_type, "manufacturer") if device_type is not None else ""
platform = related_name(device, "platform")
site = related_name(device, "site")
tenant = related_name(device, "tenant")
role = related_name(device, "role") or related_name(device, "device_role")
name = str(device.name)
return {
"id": device.id,
"name": name,
"site": site,
"tenant": tenant,
"role": role,
"model": model,
"manufacturer": manufacturer,
"host": address.split("/")[0] if address else "",
"platform": suggest_platform(platform, manufacturer, model),
"label": " · ".join(part for part in (name, site, tenant) if part),
}
class Actions:
def __init__(self, window):
self.window = window
self.state = window.state
self.tasks = window.tasks
# ------------------------------------------------------------------
# helpers
# ------------------------------------------------------------------
def _netbox_params(self):
profile = self.state.profile or {}
return profile.get("netbox_url", ""), profile.get("netbox_token", ""), profile.get("netbox_ignore_ssl", False)
def _connector(self):
"""Return a function for worker threads that yields a connected API object."""
existing = self.state.nb
url, token, ignore_ssl = self._netbox_params()
def get(ctx):
if existing is not None:
return existing
ctx.log(f"Verbinde zu NetBox ({url}) …")
nb = netbox.connect(url, token, ignore_ssl)
area_log("netbox")(f"Verbunden mit NetBox {nb.netbox_version}", "success")
return nb
return get
def _netbox_failed(self, error, title="NetBox-Verbindung fehlgeschlagen"):
if isinstance(error, NetBoxError):
self.state.set_netbox(status="error", message=str(error))
widgets.error(self.window, title, str(error), getattr(error, "traceback_text", None)
if not isinstance(error, NetBoxError) else None)
def require_netbox_config(self):
if self.state.netbox_configured():
return True
if widgets.confirm(self.window, "NetBox ist noch nicht eingerichtet",
"Bitte zuerst URL und API-Token der NetBox-Instanz hinterlegen.",
ok_text="Verbindungen öffnen"):
self.window.navigate("connections")
return False
# ------------------------------------------------------------------
# NetBox
# ------------------------------------------------------------------
def test_netbox(self, on_done=None):
url, token, ignore_ssl = self._netbox_params()
def work(ctx):
ctx.log(f"Teste Verbindung zu {url} …")
return netbox.connect(url, token, ignore_ssl)
def success(nb):
self.state.set_netbox(nb, "ok", f"Verbunden · NetBox {nb.netbox_version}")
logger("netbox").log(25, "Verbindung zu NetBox %s erfolgreich", nb.netbox_version)
self.window.toast(f"Verbindung zu NetBox {nb.netbox_version} erfolgreich")
if on_done:
on_done(True)
def failed(error):
self.state.set_netbox(status="error", message=str(error))
logger("netbox").error("%s", error)
if on_done:
on_done(False)
self.tasks.run(work, title="NetBox-Verbindungstest", area="netbox", on_success=success, on_error=failed)
def load_targets(self, on_done=None):
"""Connect and load clusters, tenants and VRFs (needed by the IPAM tools)."""
if not self.require_netbox_config():
return
connect = self._connector()
def work(ctx):
nb = connect(ctx)
engine = VMSyncEngine(nb, log=area_log("vm"))
engine.load_targets()
return nb, engine
def success(result):
nb, engine = result
self.state.set_netbox(nb, "ok", f"Verbunden · NetBox {nb.netbox_version}", engine)
if on_done:
on_done()
self.tasks.run(work, title="NetBox-Daten laden", area="netbox", on_success=success,
on_error=self._netbox_failed)
# ------------------------------------------------------------------
# Virtual machines
# ------------------------------------------------------------------
def load_vms(self):
if not self.require_netbox_config():
return
sources = [dict(source) for source in self.state.sources if source.get("enabled", True)]
if not sources:
if widgets.confirm(self.window, "Keine aktive Quelle",
"Es ist noch keine aktive VMware- oder Proxmox-Quelle hinterlegt.",
ok_text="Quelle hinzufügen"):
self.window.navigate("connections")
self.window.pages["connections"].add_source()
return
connect = self._connector()
def work(ctx):
nb = connect(ctx)
engine = VMSyncEngine(nb, log=area_log("vm"))
engine.load_targets()
ctx.check_cancelled()
vms, failures = [], []
ctx.progress(0, len(sources), "Lese Quellen …")
with ThreadPoolExecutor(max_workers=min(4, len(sources))) as pool:
futures = {pool.submit(load_source, source, ctx.log): source for source in sources}
for done, future in enumerate(as_completed(futures), start=1):
source = futures[future]
try:
loaded = future.result()
for index, vm in enumerate(loaded):
vm["id"] = f"{source['id']}:{index}:{vm['name']}"
vm["source_id"] = source["id"]
vms.extend(loaded)
ctx.log(f"{source['name']}: {len(loaded)} System(e) geladen", "success")
except Exception as error: # noqa: BLE001
failures.append(f"{source['name']}: {error}")
ctx.log(f"{source['name']}: {error}", "error")
ctx.progress(done, len(sources), source["name"])
vms.sort(key=lambda item: item["name"].casefold())
return nb, engine, vms, failures
def success(result):
nb, engine, vms, failures = result
self.state.set_netbox(nb, "ok", f"Verbunden · NetBox {nb.netbox_version}", engine)
self.state.vms = vms
self.state.vms_loaded_at = time.time()
self.state.vms_changed.emit()
if failures and not vms:
widgets.error(self.window, "Keine VMs geladen", "Keine Quelle konnte gelesen werden.",
"\n".join(failures))
elif failures:
widgets.message(self.window, "Teilweise geladen",
f"{len(vms)} System(e) geladen, {len(failures)} Quelle(n) nicht erreichbar.",
"warning", "\n".join(failures))
else:
self.window.toast(f"{len(vms)} System(e) aus {len(sources)} Quelle(n) geladen")
self.tasks.run(work, title="VMs laden", area="vm", on_success=success, on_error=self._netbox_failed)
# ------------------------------------------------------------------
# Switches
# ------------------------------------------------------------------
def load_devices(self, on_done=None):
if not self.require_netbox_config():
return
connect = self._connector()
def work(ctx):
nb = connect(ctx)
ctx.log("Lade NetBox-Geräte …")
devices = list(nb.dcim.devices.all())
rows = [_device_row(device) for device in devices if getattr(device, "name", None)]
skipped = len(devices) - len(rows)
ctx.log(f"{len(rows)} Geräte geladen" + (f" ({skipped} ohne Namen übersprungen)" if skipped else ""),
"success")
return nb, sorted(rows, key=lambda row: row["name"].casefold())
def success(result):
nb, rows = result
self.state.set_netbox(nb, "ok", f"Verbunden · NetBox {nb.netbox_version}")
self.state.netbox_devices = rows
if on_done:
on_done(rows)
self.tasks.run(work, title="NetBox-Geräte laden", area="switch", on_success=success,
on_error=self._netbox_failed)
def discover_switches(self, switches):
switches = [dict(switch) for switch in switches if switch.get("enabled", True)]
if not switches:
widgets.message(self.window, "Keine aktiven Switche", "Die ausgewählten Switche sind deaktiviert.", "info")
return
enable_lldp = bool(self.state.settings.get("enable_lldp"))
parallel = max(1, int(self.state.settings.get("parallel_ssh", 4)))
known_hosts = known_hosts_path()
def work(ctx):
snapshots, failures = {}, {}
ctx.progress(0, len(switches), "Verbinde …")
with ThreadPoolExecutor(max_workers=min(parallel, len(switches))) as pool:
futures = {}
for switch in switches:
ctx.log(f"{switch['name']}: lese {switch['host']} aus …")
futures[pool.submit(discover_switch, switch, enable_lldp, known_hosts, ctx.log)] = switch
for done, future in enumerate(as_completed(futures), start=1):
switch = futures[future]
try:
snapshot = future.result()
snapshots[switch["id"]] = snapshot
ctx.log(f"{switch['name']}: {describe_snapshot(snapshot)}", "success")
if snapshot.get("lldp_enabled_automatically"):
ctx.log(f"{switch['name']}: LLDP war deaktiviert und wurde aktiviert", "warning")
elif snapshot.get("lldp_disabled"):
ctx.log(f"{switch['name']}: LLDP ist global deaktiviert – es werden keine Nachbarn "
"erkannt. Bei Bedarf in den Einstellungen „LLDP aktivieren“ erlauben.", "warning")
if not snapshot["interfaces"]:
ctx.log(f"{switch['name']}: keine Schnittstellen erkannt – bitte SSH-Rohdaten prüfen",
"warning")
except Exception as error: # noqa: BLE001
failures[switch["id"]] = str(error)
ctx.log(f"{switch['name']}: {error}", "error")
ctx.progress(done, len(switches), switch["name"])
if ctx.cancelled:
for pending in futures:
pending.cancel()
return snapshots, failures
def success(result):
snapshots, failures = result
by_id = {switch["id"]: switch for switch in self.state.switches}
platform_updates = 0
for switch_id, snapshot in snapshots.items():
self.state.switch_snapshots[switch_id] = snapshot
self.state.switch_status[switch_id] = ("ok", describe_snapshot(snapshot))
stored = by_id.get(switch_id)
if stored and stored.get("platform", "auto") == "auto" and snapshot.get("platform") in PLATFORMS:
stored["platform"] = snapshot["platform"]
platform_updates += 1
for switch_id, problem in failures.items():
self.state.switch_status[switch_id] = ("error", problem)
if platform_updates:
self.state.touch()
self.state.switches_changed.emit()
if failures:
names = {switch["id"]: switch["name"] for switch in switches}
widgets.message(self.window, "Nicht alle Switche ausgelesen",
f"{len(snapshots)} von {len(switches)} Switch(en) erfolgreich ausgelesen.", "warning",
"\n".join(f"{names.get(key, key)}: {value}" for key, value in failures.items()))
else:
self.window.toast(f"{len(snapshots)} Switch(e) ausgelesen")
self.tasks.run(work, title="Switche auslesen", area="switch", on_success=success)
def sync_switches(self, switch_ids, create_cables):
if not self.require_netbox_config():
return
by_id = {switch["id"]: switch for switch in self.state.switches}
items = [(dict(by_id[switch_id]), self.state.switch_snapshots[switch_id])
for switch_id in switch_ids if switch_id in by_id and switch_id in self.state.switch_snapshots]
if not items:
widgets.message(self.window, "Keine Daten", "Bitte die Switche zuerst auslesen.", "info")
return
connect = self._connector()
log = area_log("switch")
def preview(ctx):
nb = connect(ctx)
reports = []
for index, (switch, snapshot) in enumerate(items):
ctx.progress(index, len(items), switch["name"])
ctx.log(f"{switch['name']}: berechne Änderungen …")
reports.append((switch, sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=True)))
return nb, reports
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
# follow-up task is not rejected as "still busy".
dialog = SyncPreviewDialog(self.window, reports, create_cables)
if dialog.exec():
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,
on_error=self._netbox_failed)
def _apply_switch_sync(self, nb, items, create_cables, log):
def work(ctx):
reports = []
for index, (switch, snapshot) in enumerate(items):
ctx.check_cancelled()
ctx.progress(index, len(items), switch["name"])
ctx.log(f"{switch['name']}: übertrage nach NetBox …")
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=False)
for error in report["errors"]:
ctx.log(f"{switch['name']}: {error}", "error")
reports.append((switch, report))
return reports
def success(reports):
totals = {}
for _switch, report in reports:
for key, value in report.items():
if isinstance(value, int):
totals[key] = totals.get(key, 0) + value
text = (f"{totals.get('interfaces_created', 0)} Interfaces angelegt, "
f"{totals.get('interfaces_updated', 0)} geändert, "
f"{totals.get('ips_created', 0) + totals.get('ips_updated', 0)} IP-Adressen, "
f"{totals.get('cables_created', 0)} Kabel")
log(f"Switch-Synchronisierung: {text}", "success")
errors = [f"{switch['name']}: {error}" for switch, report in reports for error in report["errors"]]
if errors:
widgets.message(self.window, "Mit Problemen abgeschlossen", text + ".", "warning", "\n".join(errors))
else:
self.window.toast(f"NetBox aktualisiert: {text}")
self.tasks.run(work, title="Switche synchronisieren", area="switch", on_success=success)
+91
View File
@@ -0,0 +1,91 @@
"""Application entry point."""
import logging
import sys
import traceback
from logging.handlers import RotatingFileHandler
from PySide6.QtCore import QLibraryInfo, QLocale, Qt, QTranslator
from PySide6.QtGui import QGuiApplication, QIcon
from PySide6.QtWidgets import QApplication
from netbox_sync import APP_NAME, APP_USER_MODEL_ID, APP_VERSION
from netbox_sync.core.config import log_dir
def setup_logging():
from netbox_sync.ui.tasks import QtLogHandler, log_bus
root = logging.getLogger("netbox_sync")
root.setLevel(logging.DEBUG)
root.propagate = False
try:
folder = log_dir()
folder.mkdir(parents=True, exist_ok=True)
file_handler = RotatingFileHandler(folder / "netbox-sync.log", maxBytes=2_000_000, backupCount=5,
encoding="utf-8")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)-8s %(name)s: %(message)s"))
root.addHandler(file_handler)
except OSError:
pass
root.addHandler(QtLogHandler(log_bus))
# Third-party libraries only report problems.
for name in ("paramiko", "urllib3", "pyVmomi"):
logging.getLogger(name).setLevel(logging.WARNING)
logging.getLogger("netbox_sync.app").info("%s %s gestartet", APP_NAME, APP_VERSION)
def install_excepthook(window_getter):
def hook(exc_type, exc, tb):
details = "".join(traceback.format_exception(exc_type, exc, tb))
logging.getLogger("netbox_sync.app").error("Unerwarteter Fehler: %s", exc, exc_info=(exc_type, exc, tb))
from netbox_sync.ui import widgets
try:
widgets.error(window_getter(), "Unerwarteter Fehler",
f"{exc}\n\nDie Anwendung läuft weiter. Details stehen im Protokoll.", details)
except Exception: # noqa: BLE001
sys.__excepthook__(exc_type, exc, tb)
sys.excepthook = hook
def main():
if sys.platform == "win32":
import ctypes
try:
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(APP_USER_MODEL_ID)
except (AttributeError, OSError):
pass
QGuiApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
app = QApplication(sys.argv)
app.setApplicationName(APP_NAME)
app.setApplicationDisplayName(APP_NAME)
app.setOrganizationName("NetBox Synchronizer")
app.setApplicationVersion(APP_VERSION)
app.setStyle("Fusion")
translator = QTranslator(app)
if translator.load(QLocale(QLocale.German), "qtbase", "_", QLibraryInfo.path(QLibraryInfo.TranslationsPath)):
app.installTranslator(translator)
from netbox_sync.ui.resources import resource_path
from netbox_sync.ui.theme import base_font, theme
app.setFont(base_font())
app.setWindowIcon(QIcon(str(resource_path("app.ico"))))
setup_logging()
theme.apply("system")
from netbox_sync.ui.main_window import MainWindow
window = MainWindow()
window.apply_theme()
hints = QGuiApplication.styleHints()
if hasattr(hints, "colorSchemeChanged"):
hints.colorSchemeChanged.connect(lambda _scheme: theme.mode == "system" and theme.apply())
install_excepthook(lambda: window)
window.show()
return app.exec()
if __name__ == "__main__":
sys.exit(main())
+619
View File
@@ -0,0 +1,619 @@
"""Modal dialogs for editing connections and reviewing changes."""
import uuid
from PySide6.QtCore import QThreadPool, Qt
from PySide6.QtGui import QGuiApplication
from PySide6.QtWidgets import (
QButtonGroup,
QComboBox,
QDialog,
QFileDialog,
QFormLayout,
QGridLayout,
QHBoxLayout,
QLineEdit,
QPlainTextEdit,
QPushButton,
QSpinBox,
QTabWidget,
QTreeWidget,
QTreeWidgetItem,
QVBoxLayout,
QWidget,
)
from netbox_sync.core.config import known_hosts_path
from netbox_sync.core.switches import PLATFORMS, forget_host_key
from netbox_sync.core.virtualization import test_source
from netbox_sync.ui.icons import icon
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
from netbox_sync.ui.tasks import Task
from netbox_sync.ui.theme import theme
from netbox_sync.ui.widgets import (
Badge,
Banner,
PasswordField,
SearchField,
SearchableComboBox,
Table,
button,
checkbox,
form_dialog_buttons,
label,
repolish,
)
def _mark_invalid(widget, invalid):
widget.setProperty("invalid", bool(invalid))
repolish(widget)
class _Dialog(QDialog):
def __init__(self, parent, title, subtitle=None, width=560):
super().__init__(parent)
self.setWindowTitle(title)
self.setMinimumWidth(width)
self.root = QVBoxLayout(self)
self.root.setContentsMargins(24, 22, 24, 20)
self.root.setSpacing(16)
header = QVBoxLayout()
header.setSpacing(4)
header.addWidget(label(title, object_name="PageTitle"))
if subtitle:
header.addWidget(label(subtitle, muted=True, wrap=True))
self.root.addLayout(header)
self.error_banner = Banner("", "error")
self.error_banner.hide()
def show_error(self, text):
self.error_banner.set(text, "error")
self.error_banner.show()
def ask_text(parent, title, text, default="", validator=None, ok_text="OK"):
dialog = _Dialog(parent, title, text, width=440)
field = QLineEdit(default)
field.selectAll()
dialog.root.addWidget(field)
dialog.root.addWidget(dialog.error_banner)
buttons, _ok = form_dialog_buttons(dialog, ok_text)
dialog.root.addWidget(buttons)
result = {}
def accept():
value = field.text().strip()
problem = "Bitte einen Namen eingeben." if not value else (validator(value) if validator else None)
if problem:
_mark_invalid(field, True)
dialog.show_error(problem)
return
result["value"] = value
QDialog.accept(dialog)
dialog.accept = accept
return result.get("value") if dialog.exec() == QDialog.Accepted else None
# --------------------------------------------------------------------------
# Virtualization source
# --------------------------------------------------------------------------
class SourceDialog(_Dialog):
TEXTS = {
"vmware": {
"endpoint": ("Host / vCenter", "vcenter.example.de oder 192.0.2.10"),
"identity": ("Benutzer", "[email protected]"),
"secret": ("Passwort", ""),
"help": "Ein Benutzer mit Leserechten auf alle VMs genügt.",
},
"proxmox": {
"endpoint": ("Proxmox-URL", "https://pve.example.de:8006"),
"identity": ("API-Token-ID", "benutzer@pve!netbox"),
"secret": ("API-Token-Secret", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"),
"help": "Dem Benutzer und dem API-Token mindestens die Rolle <b>PVEAuditor</b> auf <code>/vms</code> zuweisen.",
},
}
def __init__(self, parent, source=None):
source = source or {}
super().__init__(parent, "Quelle bearbeiten" if source else "Quelle hinzufügen",
"Von hier werden virtuelle Maschinen gelesen. Zugangsdaten werden verschlüsselt gespeichert.")
self.source_id = source.get("id", uuid.uuid4().hex)
self.result = None
self._task = None
type_row = QHBoxLayout()
type_row.setSpacing(8)
self.type_group = QButtonGroup(self)
self.type_buttons = {}
for key, text in (("vmware", "VMware vSphere"), ("proxmox", "Proxmox VE")):
widget = QPushButton(text)
widget.setCheckable(True)
widget.setCursor(Qt.PointingHandCursor)
widget.setMinimumHeight(38)
self.type_group.addButton(widget)
self.type_buttons[key] = widget
type_row.addWidget(widget)
widget.toggled.connect(self._update_type)
self.root.addLayout(type_row)
form = QFormLayout()
form.setHorizontalSpacing(16)
form.setVerticalSpacing(10)
form.setLabelAlignment(Qt.AlignLeft | Qt.AlignVCenter)
self.name = QLineEdit(source.get("name", ""))
self.name.setPlaceholderText("z. B. vCenter Rechenzentrum")
self.endpoint = QLineEdit(source.get("host", source.get("url", "")))
self.identity = QLineEdit(source.get("username", source.get("token_id", "")))
self.secret = PasswordField()
self.secret.setText(source.get("password", source.get("token_secret", "")))
self.endpoint_label = label()
self.identity_label = label()
self.secret_label = label()
form.addRow("Anzeigename", self.name)
form.addRow(self.endpoint_label, self.endpoint)
form.addRow(self.identity_label, self.identity)
form.addRow(self.secret_label, self.secret)
self.root.addLayout(form)
self.help = label("", muted=True, wrap=True)
self.help.setTextFormat(Qt.RichText)
self.root.addWidget(self.help)
options = QVBoxLayout()
options.setSpacing(6)
self.enabled = checkbox("Quelle beim Laden berücksichtigen", source.get("enabled", True))
self.ignore_ssl = checkbox("Selbstsigniertes Zertifikat akzeptieren (TLS-Prüfung deaktivieren)",
source.get("ignore_ssl", False))
self.include_lxc = checkbox("LXC-Container mit einlesen", source.get("include_lxc", True))
for widget in (self.enabled, self.ignore_ssl, self.include_lxc):
options.addWidget(widget)
self.root.addLayout(options)
test_row = QHBoxLayout()
self.test_button = button("Verbindung testen", "zap", on_click=self.run_test)
self.test_result = Badge()
test_row.addWidget(self.test_button)
test_row.addWidget(self.test_result)
test_row.addStretch(1)
self.root.addLayout(test_row)
self.root.addWidget(self.error_banner)
buttons, _ok = form_dialog_buttons(self, "Speichern")
self.root.addWidget(buttons)
self.type_buttons[source.get("type", "vmware")].setChecked(True)
self._update_type()
(self.endpoint if self.name.text() else self.name).setFocus()
@property
def source_type(self):
return "proxmox" if self.type_buttons["proxmox"].isChecked() else "vmware"
def _update_type(self, *_args):
texts = self.TEXTS[self.source_type]
for key, widget, field in (("endpoint", self.endpoint_label, self.endpoint),
("identity", self.identity_label, self.identity),
("secret", self.secret_label, self.secret)):
widget.setText(texts[key][0])
field.setPlaceholderText(texts[key][1])
self.help.setText(texts["help"])
self.include_lxc.setVisible(self.source_type == "proxmox")
for key, widget in self.type_buttons.items():
widget.setProperty("variant", "primary" if key == self.source_type else None)
repolish(widget)
self.test_result.set("")
def collect(self):
fields = {"name": self.name, "endpoint": self.endpoint, "identity": self.identity, "secret": self.secret}
missing = [widget for widget in fields.values() if not widget.text().strip()]
for widget in fields.values():
_mark_invalid(widget, widget in missing)
if missing:
self.show_error("Bitte die markierten Felder ausfüllen.")
missing[0].setFocus()
return None
result = {
"id": self.source_id,
"type": self.source_type,
"name": self.name.text().strip(),
"enabled": self.enabled.isChecked(),
"ignore_ssl": self.ignore_ssl.isChecked(),
}
endpoint = self.endpoint.text().strip()
if self.source_type == "vmware":
result.update({"host": endpoint, "username": self.identity.text().strip(), "password": self.secret.text()})
else:
if not endpoint.startswith(("http://", "https://")):
endpoint = f"https://{endpoint}"
result.update({
"url": endpoint.rstrip("/"), "token_id": self.identity.text().strip(),
"token_secret": self.secret.text().strip(), "include_lxc": self.include_lxc.isChecked(),
})
return result
def run_test(self):
source = self.collect()
if not source:
return
self.error_banner.hide()
self.test_button.setEnabled(False)
self.test_result.set("Teste …", "neutral")
self._task = Task(lambda _ctx: test_source(source), "vm", "Verbindungstest")
self._task.signals.succeeded.connect(lambda text: self.test_result.set(text, "success"))
self._task.signals.failed.connect(self._test_failed)
self._task.signals.finished.connect(lambda: self.test_button.setEnabled(True))
QThreadPool.globalInstance().start(self._task)
def _test_failed(self, error):
self.test_result.set("Fehlgeschlagen", "error")
self.show_error(f"Verbindung fehlgeschlagen: {error}")
def accept(self):
self.result = self.collect()
if self.result:
super().accept()
# --------------------------------------------------------------------------
# Switches
# --------------------------------------------------------------------------
def _platform_combo(current="auto", include_per_device=False):
combo = QComboBox()
if include_per_device:
combo.addItem("Je Gerät vorschlagen (empfohlen)", None)
for key, text in PLATFORMS.items():
combo.addItem(text, key)
combo.setCurrentIndex(max(0, combo.findData(current)))
return combo
class SwitchDialog(_Dialog):
"""Edit one switch access."""
def __init__(self, parent, switch, devices=None):
super().__init__(parent, "Switch bearbeiten", "SSH-Zugang zu einem bestehenden NetBox-Gerät.")
self.switch = switch
self.devices = {item["id"]: item for item in devices or []}
self.result = None
form = QFormLayout()
form.setHorizontalSpacing(16)
form.setVerticalSpacing(10)
if self.devices:
self.device = SearchableComboBox("Gerät suchen …")
self.device.set_items(
[(item["label"], item["id"]) for item in sorted(self.devices.values(), key=lambda d: d["name"].casefold())],
switch.get("device_id"),
)
form.addRow("NetBox-Gerät", self.device)
else:
self.device = None
form.addRow("NetBox-Gerät", label(f"<b>{switch.get('name', '')}</b>"))
self.platform = _platform_combo(switch.get("platform", "auto"))
self.host = QLineEdit(switch.get("host", ""))
self.port = QSpinBox()
self.port.setRange(1, 65535)
self.port.setValue(int(switch.get("port", 22)))
self.username = QLineEdit(switch.get("username", ""))
self.password = PasswordField()
self.password.setText(switch.get("password", ""))
form.addRow("Plattform", self.platform)
form.addRow("Host / IP", self.host)
form.addRow("SSH-Port", self.port)
form.addRow("Benutzer", self.username)
form.addRow("Passwort", self.password)
self.root.addLayout(form)
self.enabled = checkbox("Switch aktiv", switch.get("enabled", True))
self.root.addWidget(self.enabled)
forget = button("Gespeicherten SSH-Hostschlüssel vergessen", "shield", "ghost", on_click=self.forget_key,
tooltip="Nötig, wenn ein Switch ausgetauscht wurde und sich sein Hostschlüssel geändert hat.")
self.root.addWidget(forget, 0, Qt.AlignLeft)
self.root.addWidget(self.error_banner)
buttons, _ok = form_dialog_buttons(self)
self.root.addWidget(buttons)
def forget_key(self):
removed = forget_host_key(known_hosts_path(), self.host.text().strip(), self.port.value())
text = "Hostschlüssel entfernt. Beim nächsten Auslesen wird der neue Schlüssel gespeichert." if removed \
else "Für diesen Host war kein Schlüssel gespeichert."
self.error_banner.set(text, "success" if removed else "info")
self.error_banner.show()
def accept(self):
fields = (self.host, self.username, self.password)
for widget in fields:
_mark_invalid(widget, not widget.text().strip())
device_id = self.device.valid_data() if self.device else self.switch.get("device_id")
if self.device:
_mark_invalid(self.device, device_id is None)
if device_id is None or any(not widget.text().strip() for widget in fields):
self.show_error("Bitte Gerät und alle Zugangsdaten angeben.")
return
result = dict(self.switch)
result.update({
"device_id": device_id,
"name": self.devices[device_id]["name"] if self.devices else self.switch.get("name", ""),
"platform": self.platform.currentData(),
"host": self.host.text().strip(),
"port": self.port.value(),
"username": self.username.text().strip(),
"password": self.password.text(),
"enabled": self.enabled.isChecked(),
})
self.result = result
super().accept()
class AddSwitchesDialog(_Dialog):
"""Pick several NetBox devices at once and give them shared SSH credentials."""
def __init__(self, parent, devices, existing_device_ids):
super().__init__(parent, "Switche hinzufügen",
"Wähle vorhandene NetBox-Geräte aus. Host und Plattform werden aus NetBox vorgeschlagen.",
width=980)
self.resize(1080, 720)
self.result = []
self.rows = [dict(device, added=device["id"] in existing_device_ids) for device in devices]
filters = QHBoxLayout()
filters.setSpacing(8)
self.search = SearchField("Name, Standort, Modell, IP …")
self.tenant = QComboBox()
self.site = QComboBox()
self.role = QComboBox()
for combo, key, everything in ((self.tenant, "tenant", "Alle Mandanten"), (self.site, "site", "Alle Standorte"),
(self.role, "role", "Alle Rollen")):
combo.addItem(everything, None)
for value in sorted({row[key] or "—" for row in self.rows}, key=str.casefold):
combo.addItem(value, value)
combo.setMinimumWidth(160)
self.only_switches = checkbox("Nur Switch-Rollen")
has_switch_role = any("switch" in (row["role"] or "").casefold() for row in self.rows)
self.only_switches.setChecked(has_switch_role)
self.only_switches.setVisible(has_switch_role)
filters.addWidget(self.search, 2)
filters.addWidget(self.tenant, 1)
filters.addWidget(self.site, 1)
filters.addWidget(self.role, 1)
filters.addWidget(self.only_switches)
self.root.addLayout(filters)
columns = [
Column("name", "Gerät", 200),
Column("site", "Standort", 130),
Column("tenant", "Mandant", 130),
Column("role", "Rolle", 120),
Column("model", "Modell", 170),
Column("host", "SSH-Host", 130),
Column("platform", "Plattform", 160, value=lambda row: PLATFORMS[row["platform"]],
color=lambda row: "text_faint" if row["platform"] == "auto" else None),
Column("added", "", 110, value=lambda row: "bereits im Profil" if row["added"] else "",
color=lambda row: "text_faint"),
]
self.model = RowTableModel(columns, checkable=True, row_id=lambda row: row["id"])
self.model.set_rows(self.rows)
self.proxy = FilterProxy(self.model)
self.table = Table(stretch_column=None)
self.table.setModel(self.proxy)
self.table.sortByColumn(0, Qt.AscendingOrder)
for index, column in enumerate(columns):
self.table.setColumnWidth(index, column.width)
self.table.doubleClicked.connect(self._toggle_row)
self.root.addWidget(self.table, 1)
selection_row = QHBoxLayout()
selection_row.addWidget(button("Alle sichtbaren auswählen", variant="ghost", on_click=self.select_visible))
selection_row.addWidget(button("Auswahl aufheben", variant="ghost", on_click=lambda: self.model.set_checked(
set(self.model.checked), False)))
selection_row.addStretch(1)
self.selection_label = label("", muted=True)
selection_row.addWidget(self.selection_label)
self.root.addLayout(selection_row)
credentials = QWidget()
grid = QGridLayout(credentials)
grid.setContentsMargins(0, 0, 0, 0)
grid.setHorizontalSpacing(12)
grid.setVerticalSpacing(6)
self.username = QLineEdit()
self.username.setPlaceholderText("SSH-Benutzer")
self.password = PasswordField("Passwort")
self.port = QSpinBox()
self.port.setRange(1, 65535)
self.port.setValue(22)
self.platform = _platform_combo(include_per_device=True)
self.platform.setCurrentIndex(0)
for column, (title, widget) in enumerate((("Benutzer", self.username), ("Passwort", self.password),
("SSH-Port", self.port), ("Plattform", self.platform))):
grid.addWidget(label(title, muted=True), 0, column)
grid.addWidget(widget, 1, column)
grid.setColumnStretch(0, 2)
grid.setColumnStretch(1, 2)
grid.setColumnStretch(3, 2)
self.root.addWidget(label("Gemeinsame Zugangsdaten", object_name="CardTitle"))
self.root.addWidget(credentials)
self.root.addWidget(self.error_banner)
buttons, self.ok_button = form_dialog_buttons(self, "Hinzufügen")
self.root.addWidget(buttons)
self.search.textChanged.connect(self.proxy.set_text)
for combo, key in ((self.tenant, "tenant"), (self.site, "site"), (self.role, "role")):
combo.currentIndexChanged.connect(lambda _i, c=combo, k=key: self.proxy.set_predicate(
k, None if c.currentData() is None else (lambda row, v=c.currentData(), k=k: (row[k] or "—") == v)))
self.only_switches.toggled.connect(self._apply_switch_filter)
self._apply_switch_filter(self.only_switches.isChecked())
self.model.checked_changed.connect(self._update_selection)
self._update_selection()
self.search.setFocus()
def _apply_switch_filter(self, enabled):
self.proxy.set_predicate("switch_role", (lambda row: "switch" in (row["role"] or "").casefold()) if enabled else None)
def _toggle_row(self, index):
row = self.proxy.row_at(index)
self.model.set_checked({row["id"]}, row["id"] not in self.model.checked)
def select_visible(self):
self.model.set_checked({row["id"] for row in self.proxy.visible_rows() if not row["added"]})
def _update_selection(self):
count = len(self.model.checked)
self.selection_label.setText(f"{count} Gerät(e) ausgewählt")
self.ok_button.setText(f"{count} Switch(e) hinzufügen" if count else "Hinzufügen")
self.ok_button.setEnabled(count > 0)
def accept(self):
chosen = self.model.checked_rows()
username = self.username.text().strip()
password = self.password.text()
_mark_invalid(self.username, not username)
_mark_invalid(self.password, not password)
if not chosen:
self.show_error("Bitte mindestens ein Gerät auswählen.")
return
if not username or not password:
self.show_error("Bitte Benutzer und Passwort für den SSH-Zugang angeben.")
return
platform = self.platform.currentData()
self.result = [{
"id": uuid.uuid4().hex,
"name": row["name"],
"device_id": row["id"],
"platform": platform or row["platform"],
"host": row["host"] or row["name"],
"port": self.port.value(),
"username": username,
"password": password,
"enabled": True,
} for row in chosen]
super().accept()
# --------------------------------------------------------------------------
# Sync preview and raw data
# --------------------------------------------------------------------------
class SyncPreviewDialog(_Dialog):
def __init__(self, parent, reports, create_cables):
super().__init__(parent, "Änderungen prüfen",
"Diese Änderungen werden in NetBox vorgenommen. Es wurde noch nichts geschrieben.",
width=760)
self.resize(860, 620)
totals = {}
for _switch, report in reports:
for key, value in report.items():
if isinstance(value, int):
totals[key] = totals.get(key, 0) + value
summary = QHBoxLayout()
summary.setSpacing(8)
items = [
(f"{totals.get('interfaces_created', 0)} Interfaces neu", "info"),
(f"{totals.get('interfaces_updated', 0)} Interfaces geändert", "info"),
(f"{totals.get('ips_created', 0) + totals.get('ips_updated', 0)} IP-Adressen", "info"),
]
if create_cables:
items.append((f"{totals.get('cables_created', 0)} Kabel", "info"))
errors = sum(len(report["errors"]) for _switch, report in reports)
if errors:
items.append((f"{errors} Probleme", "error"))
for text, kind in items:
summary.addWidget(Badge(text, kind))
summary.addStretch(1)
self.root.addLayout(summary)
tree = QTreeWidget()
tree.setHeaderHidden(True)
tree.setRootIsDecorated(True)
tree.setUniformRowHeights(True)
tree.setAlternatingRowColors(True)
total_changes = 0
for switch, report in reports:
changes = report["changes"]
total_changes += len(changes)
unchanged = report["interfaces_unchanged"]
top = QTreeWidgetItem([f"{switch['name']} — {len(changes)} Änderung(en), {unchanged} Interface(s) unverändert"])
top.setIcon(0, icon("network", theme.color("accent")))
font = top.font(0)
font.setBold(True)
top.setFont(0, font)
for error in report["errors"]:
child = QTreeWidgetItem([error])
child.setIcon(0, icon("warning", theme.color("danger")))
top.addChild(child)
for change in changes[:2000]:
top.addChild(QTreeWidgetItem([change]))
tree.addTopLevelItem(top)
top.setExpanded(len(reports) == 1 or bool(report["errors"]))
self.root.addWidget(tree, 1)
if total_changes == 0:
self.root.addWidget(Banner("NetBox ist bereits auf dem aktuellen Stand – es gibt nichts zu übertragen.", "success"))
buttons, ok = form_dialog_buttons(self, f"{total_changes} Änderung(en) übernehmen")
ok.setEnabled(total_changes > 0)
self.root.addWidget(buttons)
class RawDataDialog(_Dialog):
SECTIONS = {
"interfaces": "Schnittstellen", "ipv4_interfaces": "IPv4", "ipv6_interfaces": "IPv6",
"neighbors": "LLDP", "cdp_neighbors": "CDP", "lldp_status": "LLDP-Status",
}
def __init__(self, parent, items, selected_id=None):
super().__init__(parent, "SSH-Rohdaten", "Unveränderte Ausgaben der Switch-CLI – hilfreich bei der Fehlersuche.",
width=900)
self.resize(1040, 700)
self.items = items
top = QHBoxLayout()
self.switch_combo = QComboBox()
for switch, _snapshot in items:
self.switch_combo.addItem(f"{switch['name']} ({switch['host']})", switch["id"])
if selected_id:
self.switch_combo.setCurrentIndex(max(0, self.switch_combo.findData(selected_id)))
top.addWidget(self.switch_combo, 1)
top.addWidget(button("Kopieren", "copy", on_click=self.copy_current))
top.addWidget(button("Alles speichern …", "download", on_click=self.save_all))
self.root.addLayout(top)
self.tabs = QTabWidget()
self.editors = {}
for key, title in self.SECTIONS.items():
editor = QPlainTextEdit()
editor.setObjectName("LogView")
editor.setReadOnly(True)
editor.setLineWrapMode(QPlainTextEdit.NoWrap)
self.tabs.addTab(editor, title)
self.editors[key] = editor
self.root.addWidget(self.tabs, 1)
close = button("Schließen", variant="primary", on_click=self.accept)
self.root.addWidget(close, 0, Qt.AlignRight)
self.switch_combo.currentIndexChanged.connect(self.show_switch)
self.show_switch()
def _current(self):
return self.items[max(0, self.switch_combo.currentIndex())]
def show_switch(self, *_args):
_switch, snapshot = self._current()
raw = snapshot.get("raw", {})
for key, editor in self.editors.items():
editor.setPlainText(str(raw.get(key) or "(keine Ausgabe)"))
def copy_current(self):
editor = self.tabs.currentWidget()
QGuiApplication.clipboard().setText(editor.toPlainText())
def save_all(self):
path, _filter = QFileDialog.getSaveFileName(self, "SSH-Rohdaten speichern", "ssh-rohdaten.txt", "Text (*.txt)")
if not path:
return
sections = []
for switch, snapshot in self.items:
sections.append(f"{'=' * 20} {switch['name']} ({switch['host']}) {'=' * 20}")
raw = snapshot.get("raw", {})
for key, title in self.SECTIONS.items():
sections.extend((f"\n--- {title.upper()} ---", str(raw.get(key) or "(keine Ausgabe)")))
with open(path, "w", encoding="utf-8") as stream:
stream.write("\n".join(sections))
+102
View File
@@ -0,0 +1,102 @@
"""Line icons (Lucide, ISC licence) rendered in the current theme colour."""
import tempfile
from functools import lru_cache
from pathlib import Path
from PySide6.QtCore import QByteArray, QRectF, Qt
from PySide6.QtGui import QIcon, QPainter, QPixmap
from PySide6.QtSvg import QSvgRenderer
_PATHS = {
"dashboard": '<rect width="7" height="9" x="3" y="3" rx="1"/><rect width="7" height="5" x="14" y="3" rx="1"/>'
'<rect width="7" height="9" x="14" y="12" rx="1"/><rect width="7" height="5" x="3" y="16" rx="1"/>',
"plug": '<path d="M12 22v-5"/><path d="M9 8V2"/><path d="M15 8V2"/><path d="M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z"/>',
"server": '<rect width="20" height="8" x="2" y="2" rx="2"/><rect width="20" height="8" x="2" y="14" rx="2"/>'
'<path d="M6 6h.01"/><path d="M6 18h.01"/>',
"network": '<rect x="16" y="16" width="6" height="6" rx="1"/><rect x="2" y="16" width="6" height="6" rx="1"/>'
'<rect x="9" y="2" width="6" height="6" rx="1"/><path d="M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3"/>'
'<path d="M12 12V8"/>',
"globe": '<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>',
"list": '<path d="M8 6h13"/><path d="M8 12h13"/><path d="M8 18h13"/><path d="M3 6h.01"/><path d="M3 12h.01"/>'
'<path d="M3 18h.01"/>',
"settings": '<path d="M21 4h-7"/><path d="M10 4H3"/><path d="M21 12h-9"/><path d="M8 12H3"/><path d="M21 20h-5"/>'
'<path d="M12 20H3"/><path d="M14 2v4"/><path d="M8 10v4"/><path d="M16 18v4"/>',
"plus": '<path d="M5 12h14"/><path d="M12 5v14"/>',
"pencil": '<path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/>',
"trash": '<path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/>',
"refresh": '<path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/>'
'<path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/>',
"play": '<polygon points="6 3 20 12 6 21 6 3"/>',
"search": '<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>',
"check": '<path d="M20 6 9 17l-5-5"/>',
"x": '<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',
"chevron-down": '<path d="m6 9 6 6 6-6"/>',
"chevron-up": '<path d="m18 15-6-6-6 6"/>',
"chevron-right": '<path d="m9 18 6-6-6-6"/>',
"eye": '<path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/>',
"eye-off": '<path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 '
'13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/>'
'<path d="M2 2l20 20"/>',
"upload": '<path d="M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"/><path d="M12 12v9"/><path d="m16 16-4-4-4 4"/>',
"download": '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/>',
"copy": '<rect width="14" height="14" x="8" y="8" rx="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>',
"folder": '<path d="m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 '
'2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"/>',
"more": '<circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/>',
"warning": '<path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4"/>'
'<path d="M12 17h.01"/>',
"success": '<circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/>',
"error": '<circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/>',
"info": '<circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/>',
"terminal": '<path d="m4 17 6-6-6-6"/><path d="M12 19h8"/>',
"building": '<path d="M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z"/><path d="M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2"/>'
'<path d="M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"/><path d="M10 6h4"/><path d="M10 10h4"/>'
'<path d="M10 14h4"/><path d="M10 18h4"/>',
"database": '<ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5v14a9 3 0 0 0 18 0V5"/><path d="M3 12a9 3 0 0 0 18 0"/>',
"zap": '<path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 '
'.78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"/>',
"arrow-right": '<path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>',
"arrow-left": '<path d="M19 12H5"/><path d="m12 19-7-7 7-7"/>',
"link": '<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>'
'<path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>',
"stop": '<rect width="14" height="14" x="5" y="5" rx="2"/>',
"shield": '<path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 '
'6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"/>',
"dot": '<circle cx="12" cy="12" r="5" fill="currentColor"/>',
"radio-dot": '<circle cx="12" cy="12" r="5" fill="currentColor" stroke="none"/>',
}
def _svg(name, color, stroke=2.0):
body = _PATHS[name]
return (
f'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" '
f'stroke="{color}" stroke-width="{stroke}" stroke-linecap="round" stroke-linejoin="round">'
f'{body.replace("currentColor", color)}</svg>'
)
@lru_cache(maxsize=512)
def icon(name, color="#475569", stroke=2.0):
renderer = QSvgRenderer(QByteArray(_svg(name, color, stroke).encode("utf-8")))
result = QIcon()
for size in (16, 20, 24, 32, 48, 64):
pixmap = QPixmap(size, size)
pixmap.fill(Qt.transparent)
painter = QPainter(pixmap)
painter.setRenderHint(QPainter.Antialiasing)
renderer.render(painter, QRectF(0, 0, size, size))
painter.end()
result.addPixmap(pixmap)
return result
def svg_file(name, color, stroke=2.0):
"""Write an icon to a temp file so that Qt style sheets can reference it."""
folder = Path(tempfile.gettempdir()) / "netbox-synchronizer-theme"
folder.mkdir(parents=True, exist_ok=True)
path = folder / f"{name}-{color.lstrip('#')}-{stroke}.svg"
if not path.exists():
path.write_text(_svg(name, color, stroke), encoding="utf-8")
return path.as_posix()
+637
View File
@@ -0,0 +1,637 @@
"""Step-by-step VM import: target → networks → review → run."""
import ipaddress
import time
from PySide6.QtCore import Qt
from PySide6.QtWidgets import (
QComboBox,
QDialog,
QFormLayout,
QGridLayout,
QHBoxLayout,
QHeaderView,
QLabel,
QLineEdit,
QPlainTextEdit,
QProgressBar,
QStackedWidget,
QTableWidget,
QTableWidgetItem,
QVBoxLayout,
QWidget,
)
from netbox_sync.core.vm_sync import 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
from netbox_sync.ui.widgets import Banner, SearchableComboBox, button, checkbox, hline, label, repolish
NEW_VRF = "__new__"
GLOBAL_VRF = "__global__"
STEPS = ("Ziel", "Netzwerke", "Prüfen", "Import")
def _vrf_items(engine, tenant_id):
items = [(vrf_label(vrf), vrf.id) for vrf in engine.tenant_vrfs(tenant_id)]
items.append(("Global (ohne VRF)", GLOBAL_VRF))
items.append(("➕ Neue VRF anlegen …", NEW_VRF))
return items
class ImportWizard(QDialog):
def __init__(self, parent, state, tasks, vms):
super().__init__(parent)
self.state = state
self.tasks = tasks
self.engine = state.engine
self.vms = vms
self.missing_networks = []
self.network_rows = []
self.plan = None
self.running = False
self.finished_import = False
self.result_summary = None
self._vrf_chosen = False
self.target = None
self.setWindowTitle("VMs nach NetBox importieren")
self.resize(980, 680)
self.setMinimumSize(820, 560)
root = QVBoxLayout(self)
root.setContentsMargins(0, 0, 0, 0)
root.setSpacing(0)
header = QWidget()
header.setObjectName("Card")
header.setStyleSheet("#Card { border-radius: 0; border-left: none; border-right: none; border-top: none; }")
header_layout = QHBoxLayout(header)
header_layout.setContentsMargins(28, 18, 28, 18)
title_box = QVBoxLayout()
title_box.setSpacing(2)
title_box.addWidget(label("VMs nach NetBox importieren", object_name="PageTitle"))
new, existing = self.engine.classify_vms(vms)
title_box.addWidget(label(f"{len(vms)} VM(s) ausgewählt · {new} neu · {existing} bereits in NetBox", muted=True))
header_layout.addLayout(title_box, 1)
self.step_labels = []
for index, title in enumerate(STEPS):
if index:
arrow = QLabel()
arrow.setPixmap(icon("chevron-right", theme.color("text_faint")).pixmap(14, 14))
header_layout.addWidget(arrow)
step = label(f"{index + 1} {title}", object_name="WizardStep")
self.step_labels.append(step)
header_layout.addWidget(step)
root.addWidget(header)
self.pages = QStackedWidget()
self.pages.setObjectName("Pages")
body = QVBoxLayout()
body.setContentsMargins(28, 22, 28, 12)
body.addWidget(self.pages, 1)
root.addLayout(body, 1)
footer = QHBoxLayout()
footer.setContentsMargins(28, 12, 28, 20)
self.back_button = button("Zurück", "arrow-left", on_click=self.go_back)
self.cancel_button = button("Abbrechen", variant="ghost", on_click=self.reject)
self.next_button = button("Weiter", "arrow-right", "primary", on_click=self.go_next)
self.next_button.setLayoutDirection(Qt.RightToLeft)
footer.addWidget(self.cancel_button)
footer.addStretch(1)
footer.addWidget(self.back_button)
footer.addWidget(self.next_button)
root.addLayout(footer)
self.pages.addWidget(self._build_target_page())
self.pages.addWidget(self._build_network_page())
self.pages.addWidget(self._build_review_page())
self.pages.addWidget(self._build_run_page())
self._show_page(0)
# ------------------------------------------------------------------
# Page 1 – target
# ------------------------------------------------------------------
def _build_target_page(self):
page = QWidget()
layout = QVBoxLayout(page)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(16)
layout.addWidget(label("Wohin sollen die VMs?", object_name="CardTitle"))
form = QFormLayout()
form.setHorizontalSpacing(18)
form.setVerticalSpacing(8)
form.setLabelAlignment(Qt.AlignLeft | Qt.AlignVCenter)
self.cluster = SearchableComboBox("Cluster suchen …")
self.cluster.set_items(sorted(self.engine.clusters, key=str.casefold))
self.cluster.setMinimumWidth(420)
form.addRow("NetBox-Cluster", self.cluster)
self.tenant = SearchableComboBox("Mandant suchen …")
self.tenant.set_items(sorted(self.engine.tenants, key=str.casefold))
self.tenant_hint = label("", muted=True, wrap=True)
tenant_box = QVBoxLayout()
tenant_box.setSpacing(4)
tenant_box.addWidget(self.tenant)
tenant_box.addWidget(self.tenant_hint)
form.addRow("Mandant", tenant_box)
self.vrf = QComboBox()
self.new_vrf_name = QLineEdit()
self.new_vrf_name.setPlaceholderText("Name der neuen VRF")
vrf_box = QVBoxLayout()
vrf_box.setSpacing(6)
vrf_box.addWidget(self.vrf)
vrf_box.addWidget(self.new_vrf_name)
form.addRow("VRF für IP-Adressen", vrf_box)
layout.addLayout(form)
layout.addWidget(Banner(
"Der Mandant wird an VMs, IP-Adressen und Präfixen gesetzt. Hat der Cluster in NetBox einen Mandanten, "
"ist dieser vorausgewählt.", "info"))
self.target_error = Banner("", "error")
self.target_error.hide()
layout.addWidget(self.target_error)
layout.addStretch(1)
self.cluster.currentIndexChanged.connect(self._cluster_changed)
self.tenant.currentIndexChanged.connect(self._tenant_changed)
self.vrf.currentIndexChanged.connect(self._vrf_changed)
self.vrf.activated.connect(lambda _index: setattr(self, "_vrf_chosen", True))
self.cluster.lineEdit().editingFinished.connect(self._cluster_changed)
self._tenant_changed()
return page
def _cluster_changed(self, *_args):
cluster = self.cluster.valid_data()
if not cluster:
return
inherited = self.engine.cluster_tenants.get(cluster)
if inherited:
self.tenant.select_data(inherited["name"])
self.tenant_hint.setText(f"Vom Cluster „{cluster}“ übernommen.")
else:
self.tenant_hint.setText(f"Der Cluster „{cluster}“ hat keinen Mandanten – bitte auswählen.")
self._tenant_changed()
def _tenant_changed(self, *_args):
tenant = self.tenant.valid_data()
tenant_id = self.engine.tenants.get(tenant) if tenant else None
current = self.vrf.currentData()
self.vrf.blockSignals(True)
self.vrf.clear()
for text, data in _vrf_items(self.engine, tenant_id):
self.vrf.addItem(text, data)
index = self.vrf.findData(current) if self._vrf_chosen else -1
self.vrf.setCurrentIndex(index if index >= 0 else 0)
self.vrf.blockSignals(False)
if tenant and not self.new_vrf_name.isModified():
cluster = self.cluster.valid_data() or "VMs"
self.new_vrf_name.setText(f"{tenant} - {cluster}")
self._vrf_changed()
def _vrf_changed(self, *_args):
self.new_vrf_name.setVisible(self.vrf.currentData() == NEW_VRF)
def _target(self):
cluster = self.cluster.valid_data()
tenant = self.tenant.valid_data()
vrf = self.vrf.currentData()
if not cluster:
return None, "Bitte einen NetBox-Cluster auswählen."
if not tenant:
return None, "Bitte einen Mandanten auswählen."
if vrf == NEW_VRF and not self.new_vrf_name.text().strip():
return None, "Bitte einen Namen für die neue VRF eingeben."
return {
"cluster": cluster,
"cluster_id": self.engine.clusters[cluster],
"tenant": tenant,
"tenant_id": self.engine.tenants[tenant],
"vrf_mode": "new" if vrf == NEW_VRF else ("global" if vrf == GLOBAL_VRF else "existing"),
"vrf_id": vrf if isinstance(vrf, int) else None,
"vrf_name": self.new_vrf_name.text().strip() if vrf == NEW_VRF else self.vrf.currentText(),
}, None
# ------------------------------------------------------------------
# Page 2 – networks
# ------------------------------------------------------------------
def _build_network_page(self):
page = QWidget()
layout = QVBoxLayout(page)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(12)
layout.addWidget(label("Neue Netzwerke", object_name="CardTitle"))
self.network_info = label("", muted=True, wrap=True)
layout.addWidget(self.network_info)
bulk = QHBoxLayout()
bulk.addWidget(label("VRF für alle markierten Netze:", muted=True))
self.bulk_vrf = QComboBox()
self.bulk_vrf.setMinimumWidth(260)
bulk.addWidget(self.bulk_vrf)
bulk.addWidget(button("Übernehmen", on_click=self._apply_bulk_vrf))
bulk.addStretch(1)
self.bulk_row = QWidget()
self.bulk_row.setLayout(bulk)
layout.addWidget(self.bulk_row)
self.network_table = QTableWidget(0, 5)
self.network_table.setHorizontalHeaderLabels(["Anlegen", "Netzwerk", "Größe", "VRF", "Gefunden bei"])
self.network_table.verticalHeader().setVisible(False)
self.network_table.verticalHeader().setDefaultSectionSize(44)
self.network_table.setShowGrid(False)
self.network_table.setAlternatingRowColors(True)
self.network_table.setSelectionMode(QTableWidget.NoSelection)
self.network_table.setFocusPolicy(Qt.NoFocus)
header = self.network_table.horizontalHeader()
header.setDefaultAlignment(Qt.AlignLeft | Qt.AlignVCenter)
header.setSectionResizeMode(0, QHeaderView.Fixed)
header.setSectionResizeMode(4, QHeaderView.Stretch)
self.network_table.setColumnWidth(0, 76)
self.network_table.setColumnWidth(1, 190)
self.network_table.setColumnWidth(2, 90)
self.network_table.setColumnWidth(3, 330)
layout.addWidget(self.network_table, 1)
self.no_networks = Banner("Alle erkannten Netzwerke sind bereits in NetBox vorhanden – es müssen keine "
"Präfixe angelegt werden.", "success")
layout.addWidget(self.no_networks)
self.network_error = Banner("", "error")
self.network_error.hide()
layout.addWidget(self.network_error)
return page
def _fill_networks(self, missing):
target = self.target
self.missing_networks = missing
self.network_rows = []
self.network_table.setRowCount(0)
has_rows = bool(missing)
self.network_table.setVisible(has_rows)
self.bulk_row.setVisible(has_rows)
self.no_networks.setVisible(not has_rows)
self.network_info.setText(
"Für diese IP-Adressen gibt es in NetBox noch kein passendes Präfix. Größe und VRF prüfen; "
"nicht markierte Netze werden nicht angelegt." if has_rows else ""
)
vrf_items = _vrf_items(self.engine, target["tenant_id"])
if target["vrf_mode"] == "new":
vrf_items.insert(0, (f"{target['vrf_name']} (neu)", "__target_new__"))
default = {"new": "__target_new__", "global": GLOBAL_VRF}.get(target["vrf_mode"], target["vrf_id"])
self.bulk_vrf.clear()
for text, data in vrf_items:
self.bulk_vrf.addItem(text, data)
self.bulk_vrf.setCurrentIndex(max(0, self.bulk_vrf.findData(default)))
for row_index, item in enumerate(missing):
self.network_table.insertRow(row_index)
enabled = checkbox("")
enabled.setChecked(True)
holder = QWidget()
holder_layout = QHBoxLayout(holder)
holder_layout.setContentsMargins(18, 0, 0, 0)
holder_layout.addWidget(enabled)
self.network_table.setCellWidget(row_index, 0, holder)
network_item = QTableWidgetItem()
self.network_table.setItem(row_index, 1, network_item)
size = QComboBox()
for length in prefix_choices(item["host_address"], item["detected_prefixlen"]):
size.addItem(f"/{length}", length)
size.setCurrentIndex(max(0, size.findData(item["suggested_prefixlen"])))
self.network_table.setCellWidget(row_index, 2, size)
vrf_widget = QWidget()
vrf_layout = QHBoxLayout(vrf_widget)
vrf_layout.setContentsMargins(0, 3, 6, 3)
vrf_layout.setSpacing(6)
vrf = QComboBox()
for text, data in vrf_items:
vrf.addItem(text, data)
vrf.setCurrentIndex(max(0, vrf.findData(default)))
new_name = QLineEdit(f"{target['tenant']} - {item['suggested_network'].network_address}")
new_name.setPlaceholderText("Name der neuen VRF")
vrf_layout.addWidget(vrf, 1)
vrf_layout.addWidget(new_name, 1)
self.network_table.setCellWidget(row_index, 3, vrf_widget)
vms = sorted(item["vms"], key=str.casefold)
found = QTableWidgetItem(", ".join(vms[:4]) + (f" +{len(vms) - 4}" if len(vms) > 4 else ""))
found.setToolTip("\n".join(vms))
self.network_table.setItem(row_index, 4, found)
row = {"item": item, "enabled": enabled, "size": size, "vrf": vrf, "new_name": new_name,
"network_item": network_item}
self.network_rows.append(row)
size.currentIndexChanged.connect(lambda _i, r=row: self._update_network_row(r))
vrf.currentIndexChanged.connect(lambda _i, r=row: self._update_network_row(r))
enabled.toggled.connect(lambda _c, r=row: self._update_network_row(r))
self._update_network_row(row)
def _update_network_row(self, row):
network = ipaddress.ip_network(f"{row['item']['host_address']}/{row['size'].currentData()}", strict=False)
row["network"] = str(network)
row["network_item"].setText(str(network))
row["new_name"].setVisible(row["vrf"].currentData() == NEW_VRF)
active = row["enabled"].isChecked()
for widget in (row["size"], row["vrf"], row["new_name"]):
widget.setEnabled(active)
def _apply_bulk_vrf(self):
data = self.bulk_vrf.currentData()
for row in self.network_rows:
if row["enabled"].isChecked():
row["vrf"].setCurrentIndex(max(0, row["vrf"].findData(data)))
def _network_plan(self):
decisions = {}
for row in self.network_rows:
if not row["enabled"].isChecked():
continue
data = row["vrf"].currentData()
network = row["network"]
if data == NEW_VRF:
name = row["new_name"].text().strip()
if not name:
return None, f"Bitte für {network} einen VRF-Namen eingeben."
decision = {"network": network, "vrf_id": None, "create_vrf": True, "vrf_name": name}
elif data == "__target_new__":
decision = {"network": network, "vrf_id": None, "create_vrf": True, "vrf_name": self.target["vrf_name"]}
elif data == GLOBAL_VRF:
decision = {"network": network, "vrf_id": None, "create_vrf": False, "vrf_name": None}
else:
decision = {"network": network, "vrf_id": data, "create_vrf": False, "vrf_name": None}
existing = decisions.get(network)
if existing and existing != decision:
return None, f"{network} wurde mehrfach mit unterschiedlichen VRFs ausgewählt."
decisions[network] = decision
return list(decisions.values()), None
# ------------------------------------------------------------------
# Page 3 – review
# ------------------------------------------------------------------
def _build_review_page(self):
page = QWidget()
layout = QVBoxLayout(page)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(14)
layout.addWidget(label("Bitte prüfen", object_name="CardTitle"))
layout.addWidget(label("Mit „Import starten“ werden die folgenden Änderungen in NetBox geschrieben.", muted=True))
self.review_grid = QGridLayout()
self.review_grid.setHorizontalSpacing(24)
self.review_grid.setVerticalSpacing(10)
layout.addLayout(self.review_grid)
layout.addWidget(hline())
self.review_networks = label("", muted=True, wrap=True, selectable=True)
layout.addWidget(self.review_networks)
self.tenant_warning = Banner("", "warning")
layout.addWidget(self.tenant_warning)
layout.addStretch(1)
return page
def _fill_review(self):
while self.review_grid.count():
item = self.review_grid.takeAt(0)
if item.widget():
item.widget().deleteLater()
target = self.target
new, existing = self.engine.classify_vms(self.vms)
vrf_text = {"new": f"{target['vrf_name']} (wird angelegt)", "global": "Global (ohne VRF)"}.get(
target["vrf_mode"], target["vrf_name"])
new_vrfs = sorted({decision["vrf_name"] for decision in self.plan if decision.get("create_vrf")}
- {target["vrf_name"] if target["vrf_mode"] == "new" else None})
rows = [
("Cluster", target["cluster"]),
("Mandant", target["tenant"]),
("Standard-VRF", vrf_text),
("Virtuelle Maschinen", f"{len(self.vms)} gesamt · {new} werden angelegt · {existing} aktualisiert"),
("Neue Präfixe", str(len(self.plan)) if self.plan else "keine"),
]
if new_vrfs:
rows.append(("Zusätzliche neue VRFs", ", ".join(new_vrfs)))
for index, (key, value) in enumerate(rows):
key_label = label(key, object_name="SummaryKey")
value_label = label(value, object_name="SummaryValue", wrap=True, selectable=True)
self.review_grid.addWidget(key_label, index, 0, Qt.AlignTop)
self.review_grid.addWidget(value_label, index, 1)
self.review_grid.setColumnStretch(1, 1)
if self.plan:
networks = ", ".join(f"{decision['network']}" for decision in self.plan[:12])
more = f" und {len(self.plan) - 12} weitere" if len(self.plan) > 12 else ""
self.review_networks.setText(f"Neue Präfixe: {networks}{more}")
else:
self.review_networks.setText("Es werden keine neuen Präfixe angelegt.")
inherited = self.engine.cluster_tenants.get(target["cluster"], {}).get("name")
if inherited and inherited != target["tenant"]:
self.tenant_warning.set(
f"Achtung: Der Cluster gehört in NetBox zum Mandanten <b>{inherited}</b>, "
f"importiert wird aber für <b>{target['tenant']}</b>.", "warning")
self.tenant_warning.show()
else:
self.tenant_warning.hide()
# ------------------------------------------------------------------
# Page 4 – run
# ------------------------------------------------------------------
def _build_run_page(self):
page = QWidget()
layout = QVBoxLayout(page)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(12)
self.run_title = label("Import läuft …", object_name="CardTitle")
layout.addWidget(self.run_title)
self.run_status = label("", muted=True)
layout.addWidget(self.run_status)
self.run_progress = QProgressBar()
layout.addWidget(self.run_progress)
self.run_log = QPlainTextEdit()
self.run_log.setObjectName("LogView")
self.run_log.setReadOnly(True)
layout.addWidget(self.run_log, 1)
self.run_result = Banner("", "success")
self.run_result.hide()
layout.addWidget(self.run_result)
return page
def _append_log(self, entry):
if not self.running or entry.area != "vm" or entry.level == "debug":
return
stamp = time.strftime("%H:%M:%S", time.localtime(entry.timestamp))
prefix = {"warning": "⚠ ", "error": "✖ ", "success": "✔ "}.get(entry.level, " ")
self.run_log.appendPlainText(f"{stamp} {prefix}{entry.text}")
def _start_import(self):
target = self.target
plan = self.plan
vms = list(self.vms)
engine = self.engine
self.running = True
log_bus.entry.connect(self._append_log)
self.run_progress.setRange(0, len(vms))
self.run_progress.setValue(0)
def work(ctx):
vrf_id = target["vrf_id"]
if target["vrf_mode"] == "new":
vrf_id = engine.get_or_create_tenant_vrf(target["vrf_name"], target["tenant_id"])
for decision in plan:
if decision.get("create_vrf") and decision["vrf_name"] == target["vrf_name"] and vrf_id:
decision.update(vrf_id=vrf_id, create_vrf=False)
engine.apply_network_plan(plan, target["tenant_id"])
results = {"created": 0, "updated": 0, "failed": []}
for index, vm in enumerate(vms):
if ctx.cancelled:
results["cancelled"] = True
break
ctx.progress(index, len(vms), vm["name"])
try:
outcome = engine.sync_vm(vm, target["cluster_id"], target["tenant_id"], vrf_id)
results[outcome] += 1
except Exception as error: # noqa: BLE001
results["failed"].append(f"{vm['name']}: {error}")
ctx.log(f"{vm['name']}: {error}", "error")
ctx.progress(len(vms), len(vms), "")
return results
self.tasks.run(work, title="VM-Import", area="vm", on_success=self._import_done,
on_error=self._import_failed, on_progress=self._import_progress, on_finished=self._import_finished)
def _import_progress(self, value, maximum, text):
self.run_progress.setMaximum(max(1, maximum))
self.run_progress.setValue(value)
self.run_status.setText(f"{value} von {maximum} · {text}" if text else f"{value} von {maximum}")
def _import_done(self, results):
failed = results["failed"]
summary = f"{results['created']} VM(s) angelegt, {results['updated']} aktualisiert"
if results.get("cancelled"):
self.run_title.setText("Import abgebrochen")
self.run_result.set(summary + ". Der Import wurde nach der laufenden VM beendet.", "warning")
elif failed:
self.run_title.setText("Import mit Fehlern abgeschlossen")
self.run_result.set(summary + f", <b>{len(failed)} fehlgeschlagen</b>:<br>" + "<br>".join(failed[:8]), "warning")
else:
self.run_title.setText("Import abgeschlossen")
self.run_result.set(summary + ".", "success")
self.run_result.show()
self.state.vms_changed.emit()
self.result_summary = (summary, "warning" if failed else "success")
def _import_failed(self, error):
self.run_title.setText("Import fehlgeschlagen")
self.run_result.set(str(error), "error")
self.run_result.show()
def _import_finished(self):
self.running = False
self.finished_import = True
try:
log_bus.entry.disconnect(self._append_log)
except (RuntimeError, TypeError):
pass
self.next_button.setText("Fertig")
self.next_button.setIcon(icon("check", "#FFFFFF"))
self.next_button.setEnabled(True)
self.cancel_button.hide()
# ------------------------------------------------------------------
# Navigation
# ------------------------------------------------------------------
def _show_page(self, index):
self.pages.setCurrentIndex(index)
for step, widget in enumerate(self.step_labels):
widget.setProperty("active", step == index)
widget.setProperty("done", step < index)
repolish(widget)
self.back_button.setVisible(0 < index < 3)
self.next_button.setText({2: "Import starten", 3: "Abbrechen"}.get(index, "Weiter"))
self.next_button.setIcon(icon({2: "play", 3: "stop"}.get(index, "arrow-right"), "#FFFFFF"))
self.next_button.setLayoutDirection(Qt.LeftToRight if index >= 2 else Qt.RightToLeft)
self.cancel_button.setVisible(index < 3)
def go_back(self):
index = self.pages.currentIndex()
if index == 2 and not self.missing_networks:
index = 1
self._show_page(max(0, index - 1))
def go_next(self):
index = self.pages.currentIndex()
if index == 0:
target, problem = self._target()
if problem:
self.target_error.set(problem, "error")
self.target_error.show()
return
self.target_error.hide()
self.target = target
self._detect_networks()
elif index == 1:
plan, problem = self._network_plan()
if problem:
self.network_error.set(problem, "error")
self.network_error.show()
return
self.network_error.hide()
self.plan = plan
self._fill_review()
self._show_page(2)
elif index == 2:
self._show_page(3)
self._start_import()
elif index == 3:
if self.finished_import:
self.accept()
else:
self.tasks.cancel()
self.next_button.setEnabled(False)
self.run_status.setText("Wird nach der aktuellen VM beendet …")
def _detect_networks(self):
target = self.target
engine = self.engine
vms = list(self.vms)
# A VRF that does not exist yet cannot contain prefixes; -1 keeps global
# prefixes from being mistaken for prefixes of the new VRF.
default_vrf = -1 if target["vrf_mode"] == "new" else target["vrf_id"]
self.next_button.setEnabled(False)
self.next_button.setText("Prüfe Netzwerke …")
def work(_ctx):
return engine.detect_missing_networks(vms, target["tenant_id"], default_vrf)
def done(missing):
self._fill_networks(missing)
if missing:
self._show_page(1)
else:
self.plan = []
self._fill_review()
self._show_page(2)
def failed(error):
self.target_error.set(f"Netzwerkprüfung fehlgeschlagen: {error}", "error")
self.target_error.show()
self._show_page(0)
def finished():
self.next_button.setEnabled(True)
if self.pages.currentIndex() == 0:
self._show_page(0)
self.tasks.run(work, title="Netzwerkprüfung", area="vm", on_success=done, on_error=failed,
on_finished=finished, cancellable=False)
def reject(self):
if self.running:
return
super().reject()
def closeEvent(self, event):
if self.running:
event.ignore()
return
super().closeEvent(event)
+418
View File
@@ -0,0 +1,418 @@
"""Main window: sidebar navigation, profile switcher, pages and status bar."""
from PySide6.QtCore import QSettings, QSize, Qt
from PySide6.QtGui import QAction, QKeySequence, QPixmap, QShortcut
from PySide6.QtWidgets import (
QButtonGroup,
QComboBox,
QFrame,
QHBoxLayout,
QLabel,
QMainWindow,
QMenu,
QProgressBar,
QPushButton,
QStackedWidget,
QToolButton,
QVBoxLayout,
QWidget,
)
from netbox_sync import APP_NAME, APP_VERSION
from netbox_sync.ui import widgets
from netbox_sync.ui.actions import Actions
from netbox_sync.ui.dialogs import ask_text
from netbox_sync.ui.icons import icon
from netbox_sync.ui.pages.connections import ConnectionsPage
from netbox_sync.ui.pages.ipam import IpamPage
from netbox_sync.ui.pages.log import LogPage
from netbox_sync.ui.pages.overview import OverviewPage
from netbox_sync.ui.pages.settings import SettingsPage
from netbox_sync.ui.pages.switches import SwitchesPage
from netbox_sync.ui.pages.vms import VMsPage
from netbox_sync.ui.resources import resource_path
from netbox_sync.ui.state import AppState
from netbox_sync.ui.tasks import TaskManager, log_bus
from netbox_sync.ui.theme import theme
from netbox_sync.ui.widgets import Badge, Toast, button, label
NAVIGATION = (
("overview", "Übersicht", "dashboard"),
("connections", "Verbindungen", "plug"),
("vms", "Virtuelle Maschinen", "server"),
("switches", "Switche", "network"),
("ipam", "VRFs && Netze", "globe"),
("log", "Protokoll", "list"),
)
class NavButton(QPushButton):
def __init__(self, text, icon_name):
super().__init__(text)
self.setProperty("nav", True)
self.setCheckable(True)
self.setCursor(Qt.PointingHandCursor)
self.setIconSize(QSize(18, 18))
self.icon_name = icon_name
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 0, 10, 0)
layout.addStretch(1)
self.badge = Badge("", "error")
self.badge.hide()
layout.addWidget(self.badge)
self.toggled.connect(self.update_icon)
self.update_icon()
def update_icon(self, *_args):
color = "#FFFFFF" if self.isChecked() else theme.color("sidebar_text")
self.setIcon(icon(self.icon_name, color))
def set_badge(self, count):
self.badge.set(str(count) if count else "", "error")
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle(APP_NAME)
self.setMinimumSize(1080, 700)
self.state = AppState()
self.tasks = TaskManager()
self.actions = Actions(self)
self.pages = {}
self.nav_buttons = {}
self.unseen_errors = 0
central = QWidget()
root = QHBoxLayout(central)
root.setContentsMargins(0, 0, 0, 0)
root.setSpacing(0)
root.addWidget(self._build_sidebar())
right = QVBoxLayout()
right.setContentsMargins(0, 0, 0, 0)
right.setSpacing(0)
self.stack = QStackedWidget()
self.stack.setObjectName("Pages")
right.addWidget(self.stack, 1)
right.addWidget(self._build_status_bar())
root.addLayout(right, 1)
self.setCentralWidget(central)
self.toast_widget = Toast(central)
for key, page_class in (("overview", OverviewPage), ("connections", ConnectionsPage), ("vms", VMsPage),
("switches", SwitchesPage), ("ipam", IpamPage), ("log", LogPage),
("settings", SettingsPage)):
page = page_class(self)
self.pages[key] = page
self.stack.addWidget(page)
self.tasks.busy_changed.connect(self._busy_changed)
self.tasks.progress.connect(self._progress)
self.tasks.started.connect(lambda title: self.task_label.setText(title + " …"))
log_bus.entry.connect(self._log_entry)
self.state.profiles_changed.connect(self._refresh_profiles)
self.state.profile_switched.connect(self._refresh_profiles)
self.state.netbox_changed.connect(self._refresh_netbox_pill)
self.state.profile_edited.connect(self._refresh_netbox_pill)
self.state.save_failed.connect(lambda text: self.toast(f"Speichern fehlgeschlagen: {text}", "error", 8000))
theme.changed.connect(self._theme_changed)
for index, (key, _title, _icon) in enumerate((*NAVIGATION, ("settings", "", ""))):
QShortcut(QKeySequence(f"Ctrl+{index + 1}"), self, activated=lambda k=key: self.navigate(k))
QShortcut(QKeySequence("F5"), self, activated=self._reload_current)
QShortcut(QKeySequence("Ctrl+F"), self, activated=self._focus_search)
self._restore_geometry()
self.state.load()
self.navigate("overview" if self.state.profile is None or not self.state.netbox_configured() else "vms")
self._busy_changed(False)
# ------------------------------------------------------------------
# Layout
# ------------------------------------------------------------------
def _build_sidebar(self):
sidebar = QFrame()
sidebar.setObjectName("Sidebar")
sidebar.setFixedWidth(250)
layout = QVBoxLayout(sidebar)
layout.setContentsMargins(14, 18, 14, 14)
layout.setSpacing(4)
brand = QHBoxLayout()
brand.setSpacing(10)
logo = QLabel()
logo.setPixmap(QPixmap(str(resource_path("app.png"))).scaled(
34, 34, Qt.KeepAspectRatio, Qt.SmoothTransformation))
logo.setStyleSheet("background: #FFFFFF; border-radius: 9px; padding: 3px;")
logo.setFixedSize(40, 40)
logo.setAlignment(Qt.AlignCenter)
brand.addWidget(logo)
titles = QVBoxLayout()
titles.setSpacing(0)
titles.addWidget(label("NetBox Synchronizer", object_name="AppTitle"))
titles.addWidget(label("VMs & Switche → NetBox", object_name="AppSubtitle"))
brand.addLayout(titles, 1)
layout.addLayout(brand)
layout.addSpacing(22)
layout.addWidget(label("KUNDENPROFIL", object_name="SectionLabel"))
profile_row = QHBoxLayout()
profile_row.setSpacing(6)
self.profile_combo = QComboBox()
self.profile_combo.setMinimumHeight(34)
self.profile_combo.currentTextChanged.connect(self._profile_selected)
profile_row.addWidget(self.profile_combo, 1)
self.profile_menu_button = QToolButton()
self.profile_menu_button.setIcon(icon("more", "#B6C3D6"))
self.profile_menu_button.setToolTip("Profil verwalten")
self.profile_menu_button.setFixedSize(34, 34)
self.profile_menu_button.setPopupMode(QToolButton.InstantPopup)
self.profile_menu_button.setCursor(Qt.PointingHandCursor)
menu = QMenu(self)
self.profile_actions = {
"new": QAction("Neues Profil …", self, triggered=self.new_profile),
"duplicate": QAction("Duplizieren …", self, triggered=self.duplicate_profile),
"rename": QAction("Umbenennen …", self, triggered=self.rename_profile),
"delete": QAction("Löschen …", self, triggered=self.delete_profile),
}
menu.addAction(self.profile_actions["new"])
menu.addAction(self.profile_actions["duplicate"])
menu.addAction(self.profile_actions["rename"])
menu.addSeparator()
menu.addAction(self.profile_actions["delete"])
self.profile_menu = menu
self.profile_menu_button.setMenu(menu)
profile_row.addWidget(self.profile_menu_button)
layout.addLayout(profile_row)
layout.addSpacing(20)
self.nav_group = QButtonGroup(self)
self.nav_group.setExclusive(True)
for key, text, icon_name in NAVIGATION:
nav = NavButton(text, icon_name)
nav.clicked.connect(lambda _checked=False, k=key: self.navigate(k))
self.nav_group.addButton(nav)
self.nav_buttons[key] = nav
layout.addWidget(nav)
layout.addStretch(1)
settings = NavButton("Einstellungen", "settings")
settings.clicked.connect(lambda: self.navigate("settings"))
self.nav_group.addButton(settings)
self.nav_buttons["settings"] = settings
layout.addWidget(settings)
layout.addSpacing(6)
layout.addWidget(label(f"Version {APP_VERSION}", object_name="VersionLabel"))
return sidebar
def _build_status_bar(self):
bar = QFrame()
bar.setObjectName("StatusBar")
bar.setFixedHeight(38)
layout = QHBoxLayout(bar)
layout.setContentsMargins(16, 0, 10, 0)
layout.setSpacing(10)
self.status_icon = QLabel()
self.status_icon.setFixedSize(14, 14)
layout.addWidget(self.status_icon)
self.status_message = QLabel("Bereit")
self.status_message.setMinimumWidth(200)
layout.addWidget(self.status_message, 1)
self.task_label = QLabel("")
layout.addWidget(self.task_label)
self.progress_bar = QProgressBar()
self.progress_bar.setFixedWidth(180)
layout.addWidget(self.progress_bar)
self.cancel_button = button("Abbrechen", "stop", "ghost", on_click=self._cancel_task)
layout.addWidget(self.cancel_button)
self.netbox_pill = Badge("", "neutral")
self.netbox_pill.setCursor(Qt.PointingHandCursor)
self.netbox_pill.mousePressEvent = lambda _event: self.navigate("connections")
layout.addWidget(self.netbox_pill)
return bar
# ------------------------------------------------------------------
# Navigation & feedback
# ------------------------------------------------------------------
def navigate(self, key):
page = self.pages[key]
self.stack.setCurrentWidget(page)
self.nav_buttons[key].setChecked(True)
for nav in self.nav_buttons.values():
nav.update_icon()
if key == "log":
self.unseen_errors = 0
self.nav_buttons["log"].set_badge(0)
page.on_show()
def current_page(self):
return self.stack.currentWidget()
def toast(self, text, kind="success", duration=4500):
self.toast_widget.show_message(text, kind, duration)
def _reload_current(self):
page = self.current_page()
if page is self.pages["vms"] and not self.tasks.busy:
page.load()
elif page is self.pages["switches"] and not self.tasks.busy:
page.discover()
def _focus_search(self):
search = getattr(self.current_page(), "search", None)
if search is not None:
search.setFocus()
search.selectAll()
def _log_entry(self, entry):
if entry.level == "debug":
return
tokens = {"error": "danger", "warning": "warning", "success": "success"}
self.status_icon.setPixmap(icon({"error": "error", "warning": "warning", "success": "success"}.get(
entry.level, "info"), theme.color(tokens.get(entry.level, "text_faint"))).pixmap(14, 14))
metrics = self.status_message.fontMetrics()
self.status_message.setText(metrics.elidedText(entry.text, Qt.ElideRight, max(200, self.status_message.width())))
self.status_message.setToolTip(entry.text)
if entry.level == "error" and self.current_page() is not self.pages["log"]:
self.unseen_errors += 1
self.nav_buttons["log"].set_badge(self.unseen_errors)
def _busy_changed(self, busy):
self.progress_bar.setVisible(busy)
self.cancel_button.setVisible(busy and getattr(self.tasks.current, "cancellable", False))
self.cancel_button.setEnabled(True)
self.task_label.setVisible(busy)
if busy:
self.progress_bar.setRange(0, 0)
for page in self.pages.values():
page.set_busy(busy)
for action in self.profile_actions.values():
action.setEnabled(not busy)
self.profile_combo.setEnabled(not busy)
def _progress(self, value, maximum, text):
if maximum:
self.progress_bar.setRange(0, maximum)
self.progress_bar.setValue(value)
if self.tasks.current:
suffix = f" ({value}/{maximum})" if maximum else ""
self.task_label.setText(f"{self.tasks.current.title}{suffix}")
def _cancel_task(self):
self.tasks.cancel()
self.cancel_button.setEnabled(False)
self.task_label.setText("Wird abgebrochen …")
def _refresh_netbox_pill(self):
if self.state.profile is None or not self.state.netbox_configured():
self.netbox_pill.set("NetBox: nicht eingerichtet", "warning")
elif self.state.netbox_status == "ok":
self.netbox_pill.set(f"NetBox {self.state.netbox_version} · verbunden", "success")
elif self.state.netbox_status == "error":
self.netbox_pill.set("NetBox: Fehler", "error")
self.netbox_pill.setToolTip(self.state.netbox_message)
else:
self.netbox_pill.set("NetBox: nicht verbunden", "neutral")
def apply_theme(self):
theme.apply(self.state.settings.get("theme", "system"))
def _theme_changed(self):
for nav in self.nav_buttons.values():
nav.update_icon()
# ------------------------------------------------------------------
# Profiles
# ------------------------------------------------------------------
def _refresh_profiles(self):
names = self.state.profile_names()
self.profile_combo.blockSignals(True)
self.profile_combo.clear()
self.profile_combo.addItems(names)
if not names:
self.profile_combo.setPlaceholderText("Kein Profil")
self.profile_combo.setCurrentText(self.state.active)
self.profile_combo.blockSignals(False)
has_profile = self.state.profile is not None
for key in ("duplicate", "rename", "delete"):
self.profile_actions[key].setEnabled(has_profile)
for key in ("connections", "vms", "switches", "ipam"):
self.nav_buttons[key].setEnabled(has_profile)
self.setWindowTitle(f"{self.state.active} – {APP_NAME}" if has_profile else APP_NAME)
self._refresh_netbox_pill()
def _profile_selected(self, name):
if name and name != self.state.active:
self.state.switch_profile(name)
self.toast(f"Profil „{name}“ geöffnet", "info", 2500)
def _validate_name(self, current=None):
def check(value):
if value != current and value in self.state.profiles:
return "Ein Profil mit diesem Namen existiert bereits."
return None
return check
def new_profile(self):
name = ask_text(self, "Neues Kundenprofil", "Name des Kunden oder der Umgebung, z. B. „Muster GmbH“.",
validator=self._validate_name(), ok_text="Anlegen")
if name:
self.state.create_profile(name)
self.navigate("connections")
self.toast(f"Profil „{name}“ angelegt – jetzt NetBox-Zugang eintragen", "info")
def duplicate_profile(self):
source = self.state.active
if not source:
return
name = ask_text(self, "Profil duplizieren", f"Kopie von „{source}“ inklusive aller Zugänge anlegen.",
f"{source} (Kopie)", validator=self._validate_name(), ok_text="Duplizieren")
if name:
self.state.create_profile(name, copy_from=source)
def rename_profile(self):
current = self.state.active
if not current:
return
name = ask_text(self, "Profil umbenennen", "Neuer Name für das Kundenprofil.", current,
validator=self._validate_name(current), ok_text="Umbenennen")
if name and name != current:
self.state.rename_profile(current, name)
def delete_profile(self):
name = self.state.active
if name and widgets.confirm(self, "Profil löschen",
f"Kundenprofil „{name}“ mit allen gespeicherten Zugängen endgültig löschen?",
ok_text="Löschen", destructive=True):
self.state.delete_profile(name)
self.toast(f"Profil „{name}“ gelöscht", "info")
# ------------------------------------------------------------------
# Window state
# ------------------------------------------------------------------
def _restore_geometry(self):
settings = QSettings()
geometry = settings.value("window/geometry")
if geometry is not None:
self.restoreGeometry(geometry)
else:
self.resize(1320, 860)
def resizeEvent(self, event):
super().resizeEvent(event)
if self.toast_widget.isVisible():
self.toast_widget.reposition()
def closeEvent(self, event):
if self.tasks.busy and not widgets.confirm(
self, "Vorgang läuft noch", f"„{self.tasks.current.title}“ ist noch nicht abgeschlossen. "
"Trotzdem beenden?", ok_text="Beenden", destructive=True):
event.ignore()
return
self.tasks.cancel()
self.state.save_now()
QSettings().setValue("window/geometry", self.saveGeometry())
super().closeEvent(event)
+185
View File
@@ -0,0 +1,185 @@
"""Table models with check boxes, natural sorting and multi-criteria filtering."""
import re
from dataclasses import dataclass, field
from typing import Any, Callable
from PySide6.QtCore import QAbstractTableModel, QModelIndex, QSortFilterProxyModel, Qt, Signal
from PySide6.QtGui import QColor
from netbox_sync.ui.icons import icon
from netbox_sync.ui.theme import theme
SORT_ROLE = Qt.UserRole + 1
ROW_ROLE = Qt.UserRole + 2
def natural_key(value):
"""Sort key Qt can compare: numbers stay numbers, text gets zero-padded digits (1/1/2 < 1/1/10)."""
if value is None or value == "":
return ""
if isinstance(value, bool):
return int(value)
if isinstance(value, (int, float)):
return float(value)
return re.sub(r"\d+", lambda match: match.group(0).zfill(12), str(value).casefold())
@dataclass
class Column:
key: str
title: str
width: int = 120
align: str = "left"
value: Callable[[dict], Any] = None
color: Callable[[dict], str] = None # theme token
dot: Callable[[dict], str] = None # theme token for a status dot
tooltip: Callable[[dict], str] = None
sort: Callable[[dict], Any] = None
extra: dict = field(default_factory=dict)
def display(self, row):
return self.value(row) if self.value else row.get(self.key, "")
class RowTableModel(QAbstractTableModel):
"""List-of-dicts model. With ``checkable`` the first column gets a check box."""
checked_changed = Signal()
def __init__(self, columns, checkable=False, row_id=lambda row: id(row)):
super().__init__()
self.columns = columns
self.checkable = checkable
self.row_id = row_id
self.rows = []
self.checked = set()
theme.changed.connect(self._repaint)
def _repaint(self):
if self.rows:
self.dataChanged.emit(self.index(0, 0), self.index(len(self.rows) - 1, len(self.columns) - 1))
def set_rows(self, rows, keep_checked=True):
self.beginResetModel()
self.rows = list(rows)
valid = {self.row_id(row) for row in self.rows}
self.checked = (self.checked & valid) if keep_checked else set()
self.endResetModel()
self.checked_changed.emit()
def refresh(self):
self._repaint()
def rowCount(self, parent=QModelIndex()):
return 0 if parent.isValid() else len(self.rows)
def columnCount(self, parent=QModelIndex()):
return 0 if parent.isValid() else len(self.columns)
def headerData(self, section, orientation, role=Qt.DisplayRole):
if orientation != Qt.Horizontal:
return None
column = self.columns[section]
if role == Qt.DisplayRole:
return column.title
if role == Qt.TextAlignmentRole:
return (Qt.AlignRight if column.align == "right" else Qt.AlignLeft) | Qt.AlignVCenter
return None
def flags(self, index):
flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable
if self.checkable and index.column() == 0:
flags |= Qt.ItemIsUserCheckable
return flags
def data(self, index, role=Qt.DisplayRole):
if not index.isValid():
return None
row = self.rows[index.row()]
column = self.columns[index.column()]
if role == Qt.DisplayRole:
value = column.display(row)
return "" if value is None else str(value)
if role == SORT_ROLE:
return natural_key(column.sort(row) if column.sort else column.display(row))
if role == ROW_ROLE:
return row
if role == Qt.CheckStateRole and self.checkable and index.column() == 0:
return Qt.Checked if self.row_id(row) in self.checked else Qt.Unchecked
if role == Qt.TextAlignmentRole:
return (Qt.AlignRight if column.align == "right" else Qt.AlignLeft) | Qt.AlignVCenter
if role == Qt.ForegroundRole and column.color:
token = column.color(row)
return QColor(theme.color(token)) if token else None
if role == Qt.DecorationRole and column.dot:
token = column.dot(row)
return icon("dot", theme.color(token)) if token else None
if role == Qt.ToolTipRole and column.tooltip:
return column.tooltip(row)
return None
def setData(self, index, value, role=Qt.EditRole):
if role == Qt.CheckStateRole and self.checkable and index.column() == 0:
row_id = self.row_id(self.rows[index.row()])
if Qt.CheckState(value) == Qt.Checked:
self.checked.add(row_id)
else:
self.checked.discard(row_id)
self.dataChanged.emit(index, index, [Qt.CheckStateRole])
self.checked_changed.emit()
return True
return False
def set_checked(self, row_ids, checked=True):
row_ids = set(row_ids)
if checked:
self.checked |= row_ids
else:
self.checked -= row_ids
if self.rows:
self.dataChanged.emit(self.index(0, 0), self.index(len(self.rows) - 1, 0), [Qt.CheckStateRole])
self.checked_changed.emit()
def checked_rows(self):
return [row for row in self.rows if self.row_id(row) in self.checked]
class FilterProxy(QSortFilterProxyModel):
"""Free-text search across all columns plus arbitrary row predicates."""
def __init__(self, source):
super().__init__()
self.setSourceModel(source)
self.setSortRole(SORT_ROLE)
self.setFilterCaseSensitivity(Qt.CaseInsensitive)
self.text = ""
self.predicates = {}
def set_text(self, text):
self.text = text.strip().casefold()
self.invalidateFilter()
def set_predicate(self, name, predicate):
if predicate is None:
self.predicates.pop(name, None)
else:
self.predicates[name] = predicate
self.invalidateFilter()
def filterAcceptsRow(self, source_row, source_parent):
model = self.sourceModel()
row = model.rows[source_row]
if any(not predicate(row) for predicate in self.predicates.values()):
return False
if not self.text:
return True
haystack = " ".join(str(column.display(row) or "") for column in model.columns).casefold()
return all(term in haystack for term in self.text.split())
def visible_rows(self):
model = self.sourceModel()
return [model.rows[self.mapToSource(self.index(row, 0)).row()] for row in range(self.rowCount())]
def row_at(self, proxy_index):
return self.sourceModel().rows[self.mapToSource(proxy_index).row()]
+46
View File
@@ -0,0 +1,46 @@
"""Main window pages."""
from PySide6.QtWidgets import QFrame, QScrollArea, QVBoxLayout, QWidget
from netbox_sync.ui.widgets import PageHeader
class Page(QWidget):
"""Common page frame: header plus content area, optionally scrollable."""
title = ""
subtitle = ""
def __init__(self, window, scrollable=False):
super().__init__()
self.window = window
self.state = window.state
self.tasks = window.tasks
self.actions = window.actions
self.setObjectName("PageRoot")
outer = QVBoxLayout(self)
outer.setContentsMargins(0, 0, 0, 0)
if scrollable:
scroll = QScrollArea()
scroll.setWidgetResizable(True)
scroll.setFrameShape(QFrame.NoFrame)
inner = QWidget()
inner.setObjectName("PageRoot")
scroll.setWidget(inner)
outer.addWidget(scroll)
host = inner
else:
host = self
self.body = QVBoxLayout() if host is self else QVBoxLayout(host)
if host is self:
outer.addLayout(self.body)
self.body.setContentsMargins(32, 26, 32, 24)
self.body.setSpacing(18)
self.header = PageHeader(self.title, self.subtitle)
self.body.addWidget(self.header)
def on_show(self):
"""Called whenever the page becomes visible."""
def set_busy(self, busy):
"""Disable actions that would conflict with a running task."""
+253
View File
@@ -0,0 +1,253 @@
import copy
import uuid
from PySide6.QtCore import Qt, QTimer
from PySide6.QtWidgets import QFormLayout, QHBoxLayout, QLineEdit, QMenu, QStackedWidget
from netbox_sync.core.virtualization import SOURCE_TYPES, source_endpoint
from netbox_sync.ui import widgets
from netbox_sync.ui.dialogs import SourceDialog
from netbox_sync.ui.icons import icon
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
from netbox_sync.ui.pages import Page
from netbox_sync.ui.theme import theme
from netbox_sync.ui.widgets import Badge, Card, EmptyState, PasswordField, Table, button, checkbox, label
class ConnectionsPage(Page):
title = "Verbindungen"
subtitle = "NetBox-Ziel und Virtualisierungsquellen des Kundenprofils. Änderungen werden automatisch gespeichert."
def __init__(self, window):
super().__init__(window)
self._loading = False
# NetBox ----------------------------------------------------------
netbox_card = Card("NetBox", "Ziel aller Synchronisierungen. Benötigt einen API-Token mit Schreibrechten.")
self.status_badge = Badge()
netbox_card.add_action(self.status_badge)
form = QFormLayout()
form.setHorizontalSpacing(18)
form.setVerticalSpacing(10)
form.setLabelAlignment(Qt.AlignLeft | Qt.AlignVCenter)
self.url = QLineEdit()
self.url.setPlaceholderText("https://netbox.example.de")
self.token = PasswordField("API-Token")
self.ignore_ssl = checkbox("Selbstsigniertes Zertifikat akzeptieren (TLS-Prüfung deaktivieren)")
form.addRow("URL", self.url)
form.addRow("API-Token", self.token)
form.addRow("", self.ignore_ssl)
netbox_card.add(form)
test_row = QHBoxLayout()
self.test_button = button("Verbindung testen", "zap", on_click=self.test_netbox)
self.status_text = label("", muted=True, wrap=True)
test_row.addWidget(self.test_button)
test_row.addWidget(self.status_text, 1)
netbox_card.add(test_row)
self.body.addWidget(netbox_card)
# Sources ---------------------------------------------------------
sources_card = Card("Virtualisierungsquellen", "VMware vCenter/ESXi und Proxmox VE – beliebig viele pro Profil.")
self.add_button = sources_card.add_action(button("Quelle hinzufügen", "plus", "primary", on_click=self.add_source))
self.sources_card = sources_card
columns = [
Column("enabled", "Aktiv", 70, value=lambda row: ""),
Column("name", "Name", 220),
Column("type", "Typ", 140, value=lambda row: SOURCE_TYPES.get(row.get("type"), row.get("type"))),
Column("endpoint", "Endpunkt", 320, value=source_endpoint),
Column("tls", "TLS", 140, value=lambda row: "nicht geprüft" if row.get("ignore_ssl") else "geprüft",
color=lambda row: "warning" if row.get("ignore_ssl") else "text_muted"),
]
self.model = RowTableModel(columns, checkable=True, row_id=lambda row: row["id"])
self.model.checked_changed.connect(self._enabled_changed)
self.proxy = FilterProxy(self.model)
self.table = Table(stretch_column=3)
self.table.setModel(self.proxy)
for index, column in enumerate(columns):
self.table.setColumnWidth(index, column.width)
self.table.doubleClicked.connect(lambda _index: self.edit_source())
self.table.setContextMenuPolicy(Qt.CustomContextMenu)
self.table.customContextMenuRequested.connect(self._context_menu)
self.table.selectionModel().selectionChanged.connect(self._update_buttons)
self.sources_stack = QStackedWidget()
self.sources_empty = EmptyState("server", "Noch keine Quelle",
"Füge einen vCenter-, ESXi- oder Proxmox-Zugang hinzu, um VMs zu laden.",
"Quelle hinzufügen", self.add_source)
self.sources_stack.addWidget(self.sources_empty)
self.sources_stack.addWidget(self.table)
sources_card.add(self.sources_stack, 1)
toolbar = QHBoxLayout()
self.edit_button = button("Bearbeiten", "pencil", on_click=self.edit_source)
self.duplicate_button = button("Duplizieren", "copy", on_click=self.duplicate_source)
self.remove_button = button("Entfernen", "trash", "danger", on_click=self.remove_source)
toolbar.addWidget(self.edit_button)
toolbar.addWidget(self.duplicate_button)
toolbar.addStretch(1)
toolbar.addWidget(self.remove_button)
self.source_toolbar = toolbar
sources_card.add(toolbar)
self.body.addWidget(sources_card, 1)
self._save_timer = QTimer(self)
self._save_timer.setSingleShot(True)
self._save_timer.setInterval(400)
self._save_timer.timeout.connect(self._store_netbox)
self.url.textEdited.connect(self._save_timer.start)
self.token.textEdited.connect(self._save_timer.start)
self.ignore_ssl.toggled.connect(self._store_netbox)
self.url.editingFinished.connect(self._normalize_url)
self.state.profile_switched.connect(self.load_profile)
self.state.netbox_changed.connect(self.update_status)
self.load_profile()
# ------------------------------------------------------------------
def load_profile(self):
profile = self.state.profile
self._loading = True
self.setEnabled(profile is not None)
self.url.setText(profile.get("netbox_url", "") if profile else "")
self.token.setText(profile.get("netbox_token", "") if profile else "")
self.ignore_ssl.setChecked(bool(profile.get("netbox_ignore_ssl")) if profile else False)
self._loading = False
self.refresh_sources()
self.update_status()
def _normalize_url(self):
text = self.url.text().strip().rstrip("/")
if text and not text.startswith(("http://", "https://")):
text = f"https://{text}"
if text.endswith("/api"):
text = text[:-4]
if text != self.url.text():
self.url.setText(text)
self._store_netbox()
def _store_netbox(self, *_args):
if self._loading:
return
self._save_timer.stop()
self.state.edit_profile(
netbox_url=self.url.text().strip(),
netbox_token=self.token.text().strip(),
netbox_ignore_ssl=self.ignore_ssl.isChecked(),
)
def update_status(self):
status = self.state.netbox_status
configured = self.state.netbox_configured()
if not configured:
self.status_badge.set("Nicht eingerichtet", "warning")
self.status_text.setText("")
elif status == "ok":
self.status_badge.set(f"Verbunden · {self.state.netbox_version}", "success")
self.status_text.setText("")
elif status == "error":
self.status_badge.set("Fehler", "error")
self.status_text.setText(self.state.netbox_message)
else:
self.status_badge.set("Nicht getestet", "neutral")
self.status_text.setText("")
self.status_text.setProperty("muted", status != "error")
self.status_text.setStyleSheet(f"color: {theme.color('danger')};" if status == "error" else "")
def test_netbox(self):
self._store_netbox()
if not self.state.netbox_configured():
self.status_text.setText("Bitte URL und API-Token eintragen.")
return
self.status_badge.set("Teste …", "neutral")
self.actions.test_netbox()
def set_busy(self, busy):
self.test_button.setEnabled(not busy)
# ------------------------------------------------------------------
# Sources
# ------------------------------------------------------------------
def refresh_sources(self):
sources = self.state.sources
self.model.checked = {source["id"] for source in sources if source.get("enabled", True)}
self.model.set_rows(sources)
has_sources = bool(sources)
self.sources_stack.setCurrentIndex(1 if has_sources else 0)
self.add_button.setVisible(has_sources)
for widget in (self.edit_button, self.duplicate_button, self.remove_button):
widget.setVisible(has_sources)
self._update_buttons()
def _enabled_changed(self):
changed = False
for source in self.state.sources:
enabled = source["id"] in self.model.checked
if source.get("enabled", True) != enabled:
source["enabled"] = enabled
changed = True
if changed:
self.state.touch()
def _selected(self):
rows = self.table.selectionModel().selectedRows()
return self.proxy.row_at(rows[0]) if rows else None
def _update_buttons(self, *_args):
selected = self._selected() is not None
for widget in (self.edit_button, self.duplicate_button, self.remove_button):
widgets.set_enabled(widget, selected, "Bitte zuerst eine Quelle in der Tabelle auswählen.")
def add_source(self):
if self.state.profile is None:
return
dialog = SourceDialog(self.window)
if dialog.exec() and dialog.result:
self.state.sources.append(dialog.result)
self.state.touch()
self.refresh_sources()
self.window.toast(f"Quelle „{dialog.result['name']}“ hinzugefügt")
def edit_source(self):
source = self._selected()
if not source:
return
dialog = SourceDialog(self.window, source)
if dialog.exec() and dialog.result:
index = self.state.sources.index(source)
self.state.sources[index] = dialog.result
self.state.touch()
self.refresh_sources()
def duplicate_source(self):
source = self._selected()
if not source:
return
clone = copy.deepcopy(source)
clone["id"] = uuid.uuid4().hex
clone["name"] = f"{source['name']} (Kopie)"
dialog = SourceDialog(self.window, clone)
if dialog.exec() and dialog.result:
self.state.sources.append(dialog.result)
self.state.touch()
self.refresh_sources()
def remove_source(self):
source = self._selected()
if not source:
return
if widgets.confirm(self.window, "Quelle entfernen", f"Quelle „{source['name']}“ aus dem Profil entfernen?",
ok_text="Entfernen", destructive=True):
self.state.sources.remove(source)
self.state.touch()
self.refresh_sources()
def _context_menu(self, position):
if not self._selected():
return
menu = QMenu(self)
menu.addAction(icon("pencil", theme.color("text_muted")), "Bearbeiten …", self.edit_source)
menu.addAction(icon("copy", theme.color("text_muted")), "Duplizieren …", self.duplicate_source)
menu.addSeparator()
menu.addAction(icon("trash", theme.color("danger")), "Entfernen", self.remove_source)
menu.exec(self.table.viewport().mapToGlobal(position))
+183
View File
@@ -0,0 +1,183 @@
import ipaddress
from PySide6.QtWidgets import (
QComboBox,
QFormLayout,
QHBoxLayout,
QPlainTextEdit,
QStackedWidget,
QVBoxLayout,
QWidget,
)
from netbox_sync.core.vm_sync import vrf_label
from netbox_sync.ui import widgets
from netbox_sync.ui.pages import Page
from netbox_sync.ui.widgets import Banner, Card, EmptyState, SearchableComboBox, button, label
GLOBAL = "__global__"
class IpamPage(Page):
title = "VRFs & Netze"
subtitle = "Mehrere VRFs oder Präfixe für einen Mandanten in einem Schritt in NetBox anlegen."
def __init__(self, window):
super().__init__(window)
self.stack = QStackedWidget()
self.empty = EmptyState("globe", "NetBox-Daten werden benötigt",
"Für dieses Werkzeug werden Mandanten und VRFs aus NetBox geladen.",
"NetBox-Daten laden", lambda: self.actions.load_targets())
self.stack.addWidget(self.empty)
content = QWidget()
layout = QHBoxLayout(content)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(18)
tenant_row = QFormLayout()
self.tenant = SearchableComboBox("Mandant suchen …")
self.tenant.setMinimumWidth(320)
tenant_row.addRow("Mandant", self.tenant)
vrf_card = Card("VRFs anlegen", "Ein Name pro Zeile. Bereits vorhandene VRFs des Mandanten werden übersprungen.")
self.vrf_names = QPlainTextEdit()
self.vrf_names.setPlaceholderText("Kunde - Produktion\nKunde - DMZ\nKunde - Management")
vrf_card.add(self.vrf_names, 1)
self.vrf_button = button("VRFs anlegen", "plus", "primary", on_click=self.create_vrfs)
vrf_card.add(self.vrf_button)
prefix_card = Card("Präfixe anlegen", "Ein Netz pro Zeile, z. B. 10.10.100.0/24 oder 2001:db8:10::/64.")
form = QFormLayout()
self.vrf = QComboBox()
form.addRow("Ziel-VRF", self.vrf)
prefix_card.add(form)
self.prefixes = QPlainTextEdit()
self.prefixes.setPlaceholderText("10.10.100.0/24\n10.10.101.0/24")
prefix_card.add(self.prefixes, 1)
self.prefix_hint = label("", muted=True, wrap=True)
prefix_card.add(self.prefix_hint)
self.prefix_button = button("Präfixe anlegen", "plus", "primary", on_click=self.create_prefixes)
prefix_card.add(self.prefix_button)
layout.addWidget(vrf_card, 1)
layout.addWidget(prefix_card, 1)
outer = QWidget()
outer_layout = QVBoxLayout(outer)
outer_layout.setContentsMargins(0, 0, 0, 0)
outer_layout.setSpacing(16)
outer_layout.addLayout(tenant_row)
self.result = Banner("", "success", closable=True)
self.result.hide()
outer_layout.addWidget(self.result)
outer_layout.addWidget(content, 1)
self.stack.addWidget(outer)
self.body.addWidget(self.stack, 1)
self.tenant.currentIndexChanged.connect(self.refresh_vrfs)
self.prefixes.textChanged.connect(self._validate_prefixes)
self.state.netbox_changed.connect(self.refresh)
self.state.profile_switched.connect(self.refresh)
self.refresh()
def on_show(self):
if self.state.engine is None and self.state.netbox_configured() and not self.tasks.busy:
self.actions.load_targets()
def refresh(self):
engine = self.state.engine
self.stack.setCurrentIndex(1 if engine else 0)
if not engine:
return
current = self.tenant.valid_data()
self.tenant.set_items(sorted(engine.tenants, key=str.casefold), current)
self.refresh_vrfs()
def refresh_vrfs(self, *_args):
engine = self.state.engine
tenant = self.tenant.valid_data()
current = self.vrf.currentData()
self.vrf.clear()
if engine and tenant:
for vrf in engine.tenant_vrfs(engine.tenants[tenant]):
self.vrf.addItem(vrf_label(vrf), vrf.id)
self.vrf.addItem("Global (ohne VRF)", GLOBAL)
self.vrf.setCurrentIndex(max(0, self.vrf.findData(current)))
@staticmethod
def _lines(widget):
return list(dict.fromkeys(line.strip() for line in widget.toPlainText().splitlines() if line.strip()))
def _validate_prefixes(self):
invalid, adjusted = [], []
for line in self._lines(self.prefixes):
try:
network = ipaddress.ip_network(line, strict=False)
if str(network) != line:
adjusted.append(f"{line} → {network}")
except ValueError:
invalid.append(line)
parts = []
if invalid:
parts.append("Ungültig: " + ", ".join(invalid[:5]))
if adjusted:
parts.append("Wird korrigiert: " + ", ".join(adjusted[:5]))
self.prefix_hint.setText(" · ".join(parts))
def set_busy(self, busy):
self.vrf_button.setEnabled(not busy)
self.prefix_button.setEnabled(not busy)
def _tenant_or_warn(self):
tenant = self.tenant.valid_data()
if not tenant:
widgets.message(self.window, "Mandant fehlt", "Bitte zuerst einen Mandanten auswählen.", "info")
return tenant
def create_vrfs(self):
tenant = self._tenant_or_warn()
names = self._lines(self.vrf_names)
if not tenant or not names:
return
engine = self.state.engine
def done(result):
created, reused, errors = result
self.refresh_vrfs()
text = f"VRFs für {tenant}: {created} angelegt, {reused} bereits vorhanden."
if errors:
self.result.set(text + "<br>" + "<br>".join(errors), "warning")
else:
self.vrf_names.clear()
self.result.set(text, "success")
self.result.show()
self.tasks.run(lambda _ctx: engine.create_vrfs_batch(tenant, names), title="VRFs anlegen", area="ipam",
on_success=done)
def create_prefixes(self):
tenant = self._tenant_or_warn()
networks = self._lines(self.prefixes)
if not tenant or not networks:
return
vrf_data = self.vrf.currentData()
vrf_id = None if vrf_data == GLOBAL else vrf_data
vrf_name = self.vrf.currentText()
if not widgets.confirm(self.window, "Präfixe anlegen",
f"{len(networks)} Präfix(e) für {tenant} in „{vrf_name}“ anlegen?", ok_text="Anlegen"):
return
engine = self.state.engine
def done(result):
created, reused, canonical, errors = result
text = f"Präfixe: {created} angelegt, {reused} bereits vorhanden (Mandant aktualisiert)."
if errors:
self.prefixes.setPlainText("\n".join(error.split(":")[0] for error in errors))
self.result.set(text + "<br>Fehler:<br>" + "<br>".join(errors), "warning")
else:
self.prefixes.clear()
self.result.set(text, "success")
self.result.show()
self.tasks.run(lambda _ctx: engine.create_prefixes_batch(tenant, vrf_id, networks), title="Präfixe anlegen",
area="ipam", on_success=done)
+121
View File
@@ -0,0 +1,121 @@
import html
import os
import time
from PySide6.QtGui import QGuiApplication
from PySide6.QtWidgets import QComboBox, QFileDialog, QHBoxLayout, QPlainTextEdit
from netbox_sync.core.config import log_dir
from netbox_sync.ui.pages import Page
from netbox_sync.ui.tasks import AREAS, log_bus
from netbox_sync.ui.theme import theme
from netbox_sync.ui.widgets import Card, SearchField, button
MAX_ENTRIES = 10000
LEVEL_RANK = {"debug": 0, "info": 1, "success": 1, "warning": 2, "error": 3}
LEVEL_TEXT = {"info": "INFO", "success": "OK", "warning": "WARNUNG", "error": "FEHLER", "debug": "DEBUG"}
class LogPage(Page):
title = "Protokoll"
subtitle = "Alle Aktivitäten dieser Sitzung. Zusätzlich wird ein Logfile im Benutzerprofil geschrieben."
def __init__(self, window):
super().__init__(window)
self.entries = []
card = Card(padding=0, spacing=0)
toolbar = QHBoxLayout()
toolbar.setContentsMargins(16, 14, 16, 12)
toolbar.setSpacing(8)
self.search = SearchField("Protokoll durchsuchen …")
self.level = QComboBox()
for text, value in (("Alle Meldungen", 0), ("Nur Warnungen und Fehler", 2), ("Nur Fehler", 3)):
self.level.addItem(text, value)
self.area = QComboBox()
self.area.addItem("Alle Bereiche", None)
for key, text in AREAS.items():
self.area.addItem(text, key)
toolbar.addWidget(self.search, 2)
toolbar.addWidget(self.level)
toolbar.addWidget(self.area)
toolbar.addStretch(1)
toolbar.addWidget(button("Kopieren", "copy", on_click=self.copy))
toolbar.addWidget(button("Exportieren …", "download", on_click=self.export))
toolbar.addWidget(button("Log-Ordner", "folder", on_click=self.open_folder))
toolbar.addWidget(button("Leeren", "trash", "ghost", on_click=self.clear))
card.add(toolbar)
self.view = QPlainTextEdit()
self.view.setObjectName("LogView")
self.view.setReadOnly(True)
self.view.setMaximumBlockCount(MAX_ENTRIES)
card.add(self.view, 1)
self.body.addWidget(card, 1)
self.search.textChanged.connect(self.render)
self.level.currentIndexChanged.connect(self.render)
self.area.currentIndexChanged.connect(self.render)
log_bus.entry.connect(self.add)
theme.changed.connect(self.render)
def _accepts(self, entry):
if LEVEL_RANK.get(entry.level, 1) < self.level.currentData():
return False
area = self.area.currentData()
if area and entry.area != area:
return False
query = self.search.text().strip().casefold()
return not query or query in entry.text.casefold()
def _html(self, entry):
colors = {"warning": theme.color("warning"), "error": theme.color("danger"), "success": theme.color("success")}
stamp = time.strftime("%H:%M:%S", time.localtime(entry.timestamp))
level = LEVEL_TEXT.get(entry.level, entry.level.upper())
color = colors.get(entry.level, theme.color("text"))
muted = theme.color("text_faint")
area = AREAS.get(entry.area, entry.area)
return (f'<span style="color:{muted}">{stamp}</span>&nbsp;&nbsp;'
f'<span style="color:{color}; font-weight:600">{level:<8}</span>&nbsp;'
f'<span style="color:{muted}">[{html.escape(area)}]</span>&nbsp;'
f'<span style="color:{color}">{html.escape(entry.text)}</span>')
def add(self, entry):
self.entries.append(entry)
if len(self.entries) > MAX_ENTRIES:
del self.entries[: len(self.entries) - MAX_ENTRIES]
if self._accepts(entry):
self.view.appendHtml(self._html(entry))
def render(self, *_args):
self.view.clear()
self.view.appendHtml("<br>".join(self._html(entry) for entry in self.entries if self._accepts(entry)))
self.view.verticalScrollBar().setValue(self.view.verticalScrollBar().maximum())
def _plain(self):
lines = []
for entry in self.entries:
if self._accepts(entry):
stamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(entry.timestamp))
lines.append(f"{stamp} {LEVEL_TEXT.get(entry.level, entry.level):<8} [{AREAS.get(entry.area, entry.area)}] "
f"{entry.text}")
return "\n".join(lines)
def copy(self):
QGuiApplication.clipboard().setText(self._plain())
self.window.toast("Protokoll in die Zwischenablage kopiert", "info")
def export(self):
name = time.strftime("netbox-sync-protokoll-%Y%m%d-%H%M.txt")
path, _filter = QFileDialog.getSaveFileName(self, "Protokoll exportieren", name, "Text (*.txt)")
if path:
with open(path, "w", encoding="utf-8") as stream:
stream.write(self._plain())
self.window.toast("Protokoll gespeichert")
def open_folder(self):
folder = log_dir()
folder.mkdir(parents=True, exist_ok=True)
os.startfile(folder) # noqa: S606 - Windows Explorer
def clear(self):
self.entries.clear()
self.view.clear()
+187
View File
@@ -0,0 +1,187 @@
import time
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QGridLayout, QHBoxLayout, QLabel, QVBoxLayout, QWidget
from netbox_sync.ui.icons import icon
from netbox_sync.ui.pages import Page
from netbox_sync.ui.theme import theme
from netbox_sync.ui.widgets import Card, EmptyState, StatTile, button, hline, label
def _ago(timestamp):
if not timestamp:
return ""
minutes = int((time.time() - timestamp) / 60)
if minutes < 1:
return "gerade eben"
if minutes < 60:
return f"vor {minutes} min"
return time.strftime("um %H:%M Uhr", time.localtime(timestamp))
class Step(QWidget):
def __init__(self, number, title, text, action_text, on_action, optional=False):
super().__init__()
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 6, 0, 6)
layout.setSpacing(14)
self.circle = QLabel(str(number))
self.circle.setObjectName("StepCircle")
self.circle.setAlignment(Qt.AlignCenter)
self.number = number
layout.addWidget(self.circle, 0, Qt.AlignTop)
texts = QVBoxLayout()
texts.setSpacing(2)
heading = title + (" <span style='font-weight:400'>(optional)</span>" if optional else "")
self.title = label(heading)
self.title.setTextFormat(Qt.RichText)
self.title.setStyleSheet("font-weight: 600;")
texts.addWidget(self.title)
self.text = label(text, muted=True, wrap=True)
texts.addWidget(self.text)
layout.addLayout(texts, 1)
self.action = button(action_text, on_click=on_action)
layout.addWidget(self.action, 0, Qt.AlignVCenter)
self.done = False
theme.changed.connect(self._render)
def set_done(self, done, primary=False):
self.done = done
self.action.setProperty("variant", "primary" if primary and not done else None)
self.action.style().unpolish(self.action)
self.action.style().polish(self.action)
self._render()
def _render(self):
self.circle.setProperty("done", self.done)
if self.done:
self.circle.setText("")
self.circle.setPixmap(icon("check", theme.color("success"), 2.6).pixmap(16, 16))
else:
self.circle.clear()
self.circle.setText(str(self.number))
self.circle.style().unpolish(self.circle)
self.circle.style().polish(self.circle)
class OverviewPage(Page):
title = "Übersicht"
subtitle = "Status des aktiven Kundenprofils und die nächsten Schritte."
def __init__(self, window):
super().__init__(window, scrollable=True)
self.empty = EmptyState(
"building", "Willkommen beim NetBox Synchronizer",
"Lege zuerst ein Kundenprofil an. Darin werden die NetBox-Instanz, VMware-/Proxmox-Quellen und "
"Switch-Zugänge eines Kunden gespeichert – Passwörter verschlüsselt mit Windows DPAPI.",
"Erstes Kundenprofil anlegen", window.new_profile,
)
self.body.addWidget(self.empty, 1)
self.content = QWidget()
content = QVBoxLayout(self.content)
content.setContentsMargins(0, 0, 0, 0)
content.setSpacing(18)
tiles = QGridLayout()
tiles.setSpacing(16)
self.netbox_tile = StatTile("database", "NetBox")
self.vm_tile = StatTile("server", "Virtualisierung")
self.switch_tile = StatTile("network", "Switche")
self.netbox_tile.clicked.connect(lambda: window.navigate("connections"))
self.vm_tile.clicked.connect(lambda: window.navigate("vms"))
self.switch_tile.clicked.connect(lambda: window.navigate("switches"))
for column, tile in enumerate((self.netbox_tile, self.vm_tile, self.switch_tile)):
tiles.addWidget(tile, 0, column)
tiles.setColumnStretch(column, 1)
content.addLayout(tiles)
steps = Card("Erste Schritte", "In vier Schritten von der leeren NetBox zur gepflegten Dokumentation.")
self.steps = [
Step(1, "NetBox verbinden", "URL und API-Token hinterlegen und die Verbindung testen.",
"Einrichten", lambda: window.navigate("connections")),
Step(2, "Virtualisierungsquelle hinzufügen", "vCenter, ESXi-Host oder Proxmox-Cluster anbinden.",
"Quelle hinzufügen", self._add_source),
Step(3, "VMs laden und importieren",
"VMs auswählen, Cluster und Mandant festlegen – neue Netze werden vor dem Anlegen angezeigt.",
"Zu den VMs", lambda: window.navigate("vms")),
Step(4, "Switche dokumentieren",
"Bestehende NetBox-Geräte per SSH auslesen: Schnittstellen, IP-Adressen und LLDP-Verkabelung.",
"Zu den Switchen", lambda: window.navigate("switches"), optional=True),
]
for index, step in enumerate(self.steps):
if index:
steps.add(hline())
steps.add(step)
content.addWidget(steps)
tips = Card("Gut zu wissen")
for text in (
"Alle Eingaben werden automatisch gespeichert – es gibt keinen Speichern-Knopf mehr.",
"Lange Vorgänge laufen im Hintergrund. Das Fenster bleibt bedienbar, unten rechts lässt sich abbrechen.",
"Vor jedem Schreibvorgang zeigt die Anwendung eine Zusammenfassung der Änderungen.",
"Das Protokoll enthält alle Details und wird zusätzlich als Datei gespeichert.",
):
row = QHBoxLayout()
dot = QLabel("•")
dot.setProperty("muted", True)
row.addWidget(dot, 0, Qt.AlignTop)
row.addWidget(label(text, muted=True, wrap=True), 1)
tips.add(row)
content.addWidget(tips)
content.addStretch(1)
self.body.addWidget(self.content, 1)
for signal in (self.state.profile_switched, self.state.profile_edited, self.state.netbox_changed,
self.state.vms_changed, self.state.switches_changed):
signal.connect(self.refresh)
self.refresh()
def _add_source(self):
self.window.navigate("connections")
self.window.pages["connections"].add_source()
def on_show(self):
self.refresh()
def refresh(self):
profile = self.state.profile
self.empty.setVisible(profile is None)
self.content.setVisible(profile is not None)
if profile is None:
self.header.subtitle.setText("Noch kein Kundenprofil vorhanden.")
return
self.header.subtitle.setText(f"Kundenprofil „{profile['name']}“")
configured = self.state.netbox_configured()
status = self.state.netbox_status
if not configured:
self.netbox_tile.set("Nicht eingerichtet", "URL und API-Token fehlen.", "Einrichten", "warning")
elif status == "ok":
self.netbox_tile.set(f"NetBox {self.state.netbox_version}", profile["netbox_url"], "Verbunden", "success")
elif status == "error":
self.netbox_tile.set("Fehler", self.state.netbox_message, "Fehler", "error")
else:
self.netbox_tile.set("Bereit", profile["netbox_url"], "Nicht getestet", "neutral")
sources = self.state.sources
active = sum(1 for source in sources if source.get("enabled", True))
if self.state.vms:
new = sum(1 for vm in self.state.vms if self.state.engine and vm["name"] not in self.state.engine.existing_vms)
self.vm_tile.set(f"{len(self.state.vms)} VMs", f"{new} noch nicht in NetBox · geladen {_ago(self.state.vms_loaded_at)}",
f"{active} Quelle(n)", "info")
else:
self.vm_tile.set(f"{len(sources)} Quelle(n)", "VMs noch nicht geladen." if sources else "Noch keine Quelle.",
"", "neutral")
switches = self.state.switches
scanned = len([key for key in self.state.switch_snapshots if any(s["id"] == key for s in switches)])
errors = sum(1 for status_, _text in self.state.switch_status.values() if status_ == "error")
detail = f"{scanned} ausgelesen" if scanned else ("Noch nicht ausgelesen." if switches else "Noch keine Switche.")
self.switch_tile.set(f"{len(switches)} Switch(e)", detail,
f"{errors} Fehler" if errors else "", "error" if errors else "neutral")
done = [configured and status != "error", bool(sources), bool(self.state.vms), bool(switches)]
first_open = next((index for index, value in enumerate(done) if not value), None)
for index, step in enumerate(self.steps):
step.set_done(done[index], primary=index == first_open)
+111
View File
@@ -0,0 +1,111 @@
import os
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QButtonGroup, QFormLayout, QHBoxLayout, QRadioButton, QSpinBox
from netbox_sync import APP_NAME, APP_PUBLISHER, APP_VERSION
from netbox_sync.core.config import config_dir, config_path, known_hosts_path, log_dir
from netbox_sync.ui import widgets
from netbox_sync.ui.pages import Page
from netbox_sync.ui.widgets import Card, button, checkbox, label
class SettingsPage(Page):
title = "Einstellungen"
subtitle = "Gelten für alle Kundenprofile."
def __init__(self, window):
super().__init__(window, scrollable=True)
appearance = Card("Darstellung")
row = QHBoxLayout()
self.theme_group = QButtonGroup(self)
self.theme_buttons = {}
for key, text in (("system", "Wie Windows"), ("light", "Hell"), ("dark", "Dunkel")):
radio = QRadioButton(text)
radio.setCursor(Qt.PointingHandCursor)
self.theme_group.addButton(radio)
self.theme_buttons[key] = radio
row.addWidget(radio)
radio.toggled.connect(lambda checked, k=key: checked and self._set_theme(k))
row.addStretch(1)
appearance.add(row)
self.body.addWidget(appearance)
switches = Card("Switche", "Verhalten beim Auslesen per SSH.")
form = QFormLayout()
form.setHorizontalSpacing(18)
self.parallel = QSpinBox()
self.parallel.setRange(1, 16)
self.parallel.setSuffix(" gleichzeitig")
self.parallel.setFixedWidth(160)
form.addRow("SSH-Sitzungen", self.parallel)
switches.add(form)
self.enable_lldp = checkbox("LLDP automatisch aktivieren, wenn es auf einem Switch deaktiviert ist",
tooltip="Ändert die laufende Konfiguration des Switches.")
switches.add(self.enable_lldp)
switches.add(label("Ohne diese Option wird die Switch-Konfiguration nie verändert; es werden nur "
"„show“-/„display“-Befehle ausgeführt.", muted=True, wrap=True))
keys = QHBoxLayout()
keys.addWidget(label("SSH-Hostschlüssel werden beim ersten Kontakt gespeichert und danach geprüft.",
muted=True, wrap=True), 1)
keys.addWidget(button("Alle vergessen", "trash", "danger", on_click=self.forget_keys))
switches.add(keys)
self.body.addWidget(switches)
data = Card("Daten & Dateien")
for caption, path, opener in (
("Konfiguration", config_path(), config_dir()),
("Protokolle", log_dir(), log_dir()),
):
line = QHBoxLayout()
line.addWidget(label(caption), 0)
line.addSpacing(12)
line.addWidget(label(str(path), muted=True, selectable=True), 1)
line.addWidget(button("Öffnen", "folder", on_click=lambda _c=False, p=opener: self._open(p)))
data.add(line)
data.add(label("Passwörter und Tokens sind mit Windows DPAPI an dieses Benutzerkonto gebunden und können "
"nicht auf einem anderen Rechner entschlüsselt werden.", muted=True, wrap=True))
self.body.addWidget(data)
about = Card("Über")
about.add(label(f"<b>{APP_NAME}</b> Version {APP_VERSION}"))
about.add(label(f"© {APP_PUBLISHER}", muted=True))
self.body.addWidget(about)
self.body.addStretch(1)
self.parallel.valueChanged.connect(lambda value: self.state.update_settings(parallel_ssh=value))
self.enable_lldp.toggled.connect(lambda value: self.state.update_settings(enable_lldp=value))
self.state.settings_changed.connect(self.load)
self.load()
def load(self):
settings = self.state.settings
for widget in (self.parallel, self.enable_lldp, *self.theme_buttons.values()):
widget.blockSignals(True)
self.parallel.setValue(int(settings.get("parallel_ssh", 4)))
self.enable_lldp.setChecked(bool(settings.get("enable_lldp")))
self.theme_buttons.get(settings.get("theme", "system"), self.theme_buttons["system"]).setChecked(True)
for widget in (self.parallel, self.enable_lldp, *self.theme_buttons.values()):
widget.blockSignals(False)
def _set_theme(self, mode):
if self.state.settings.get("theme") != mode:
self.state.update_settings(theme=mode)
self.window.apply_theme()
@staticmethod
def _open(path):
path.mkdir(parents=True, exist_ok=True)
os.startfile(path) # noqa: S606 - Windows Explorer
def forget_keys(self):
path = known_hosts_path()
if not path.exists():
self.window.toast("Es sind keine Hostschlüssel gespeichert.", "info")
return
if widgets.confirm(self.window, "Hostschlüssel vergessen",
"Alle gespeicherten SSH-Hostschlüssel löschen? Beim nächsten Auslesen werden sie ohne "
"Prüfung neu übernommen.", ok_text="Löschen", destructive=True):
path.unlink()
self.window.toast("Gespeicherte Hostschlüssel gelöscht")
+340
View File
@@ -0,0 +1,340 @@
import time
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QComboBox, QHBoxLayout, QMenu, QSplitter, QStackedWidget
from netbox_sync.core.switches import PLATFORMS
from netbox_sync.ui import widgets
from netbox_sync.ui.dialogs import AddSwitchesDialog, RawDataDialog, SwitchDialog
from netbox_sync.ui.icons import icon
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
from netbox_sync.ui.pages import Page
from netbox_sync.ui.theme import theme
from netbox_sync.ui.widgets import Card, EmptyState, SearchField, Table, button, checkbox, label
def _speed(value):
if not value:
return ""
return f"{value / 1000:g} Gbit/s" if value >= 1000 else f"{value} Mbit/s"
class SwitchesPage(Page):
title = "Switche"
subtitle = ("Bestehende NetBox-Geräte per SSH auslesen und Schnittstellen, IP-Adressen und LLDP/CDP-Verkabelung "
"dokumentieren. Unterstützt Aruba CX, ArubaOS-Switch/ProCurve und HPE Comware.")
def __init__(self, window):
super().__init__(window)
splitter = QSplitter(Qt.Vertical)
splitter.setChildrenCollapsible(False)
# Switch list -------------------------------------------------------
list_card = Card("Switch-Zugänge", "Haken setzen, um Switche auszulesen oder zu synchronisieren.")
self.add_button = list_card.add_action(button("Switche hinzufügen …", "plus", on_click=self.add_switches))
self.discover_button = list_card.add_action(button("Auslesen", "play", "primary", on_click=self.discover))
columns = [
Column("name", "NetBox-Gerät", 200),
Column("platform", "Plattform", 180, value=lambda row: PLATFORMS.get(row.get("platform"), row.get("platform"))),
Column("host", "SSH-Host", 150, value=lambda row: f"{row.get('host', '')}:{row.get('port', 22)}"),
Column("enabled", "Aktiv", 70, value=lambda row: "ja" if row.get("enabled", True) else "nein",
color=lambda row: None if row.get("enabled", True) else "text_faint"),
Column("status", "Letztes Auslesen", 300, value=self._status_text, dot=self._status_dot,
tooltip=self._status_text),
]
self.switch_model = RowTableModel(columns, checkable=True, row_id=lambda row: row["id"])
self.switch_proxy = FilterProxy(self.switch_model)
self.switch_table = Table()
self.switch_table.setModel(self.switch_proxy)
for index, column in enumerate(columns):
self.switch_table.setColumnWidth(index, column.width)
self.switch_table.doubleClicked.connect(lambda _index: self.edit_switch())
self.switch_table.setContextMenuPolicy(Qt.CustomContextMenu)
self.switch_table.customContextMenuRequested.connect(self._context_menu)
self.switch_stack = QStackedWidget()
self.switch_empty = EmptyState("network", "Noch keine Switche im Profil",
"Wähle vorhandene Geräte aus NetBox aus und hinterlege den SSH-Zugang – "
"mehrere Switche lassen sich in einem Schritt hinzufügen.",
"Switche hinzufügen", self.add_switches)
self.switch_stack.addWidget(self.switch_empty)
self.switch_stack.addWidget(self.switch_table)
list_card.add(self.switch_stack, 1)
toolbar = QHBoxLayout()
self.select_all_button = button("Alle auswählen", variant="ghost", on_click=self.select_all)
self.edit_button = button("Bearbeiten", "pencil", on_click=self.edit_switch)
self.remove_button = button("Entfernen", "trash", "danger", on_click=self.remove_switches)
toolbar.addWidget(self.select_all_button)
toolbar.addStretch(1)
self.lldp_option = checkbox("LLDP bei Bedarf aktivieren",
tooltip="Ist LLDP auf einem Switch global deaktiviert, wird es per Konfigurations"
"befehl eingeschaltet. Das ändert die laufende Konfiguration des Switches!")
toolbar.addWidget(self.lldp_option)
toolbar.addSpacing(12)
toolbar.addWidget(self.edit_button)
toolbar.addWidget(self.remove_button)
list_card.add(toolbar)
splitter.addWidget(list_card)
# Results -------------------------------------------------------------
result_card = Card("Ergebnisse", "Erkannte Schnittstellen und Nachbarn der ausgelesenen Switche.")
self.raw_button = result_card.add_action(button("SSH-Rohdaten", "terminal", on_click=self.show_raw))
self.sync_button = result_card.add_action(button("Nach NetBox übertragen …", "upload", "primary",
on_click=self.sync))
filters = QHBoxLayout()
self.search = SearchField("Schnittstelle, IP, Nachbar …")
self.switch_filter = QComboBox()
self.switch_filter.setMinimumWidth(200)
self.only_neighbors = checkbox("Nur mit Nachbar")
self.only_up = checkbox("Nur aktive Ports")
self.cables_option = checkbox("Kabel aus LLDP/CDP anlegen",
tooltip="Legt Kabel zwischen Schnittstellen an, deren Gegenstelle in NetBox "
"eindeutig gefunden wird. Bestehende Kabel werden nie verändert.")
filters.addWidget(self.search, 2)
filters.addWidget(self.switch_filter, 1)
filters.addWidget(self.only_up)
filters.addWidget(self.only_neighbors)
filters.addStretch(1)
filters.addWidget(self.cables_option)
result_card.add(filters)
result_columns = [
Column("switch", "Switch", 140),
Column("name", "Schnittstelle", 150),
Column("state", "Status", 125, value=lambda row: ("Up" if row["connected"] else "Down")
if row["enabled"] else "Deaktiviert",
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("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", "")),
Column("protocol", "Quelle", 70, value=lambda row: (row.get("neighbor") or {}).get("protocol", ""),
color=lambda row: "text_muted"),
]
self.result_model = RowTableModel(result_columns)
self.result_proxy = FilterProxy(self.result_model)
self.result_table = Table()
self.result_table.setModel(self.result_proxy)
for index, column in enumerate(result_columns):
self.result_table.setColumnWidth(index, column.width)
self.result_stack = QStackedWidget()
self.result_empty = EmptyState("terminal", "Noch nichts ausgelesen",
"Switche oben anhaken und „Auslesen“ wählen. Mehrere Switche werden parallel "
"abgefragt.")
self.result_stack.addWidget(self.result_empty)
self.result_stack.addWidget(self.result_table)
result_card.add(self.result_stack, 1)
self.result_summary = label("", muted=True)
result_card.add(self.result_summary)
splitter.addWidget(result_card)
splitter.setStretchFactor(0, 2)
splitter.setStretchFactor(1, 3)
self.body.addWidget(splitter, 1)
self.search.textChanged.connect(self.result_proxy.set_text)
self.switch_filter.currentIndexChanged.connect(self._apply_result_filters)
self.only_neighbors.toggled.connect(self._apply_result_filters)
self.only_up.toggled.connect(self._apply_result_filters)
self.switch_model.checked_changed.connect(self._update_buttons)
self.switch_table.selectionModel().selectionChanged.connect(self._update_buttons)
self.lldp_option.toggled.connect(lambda value: self.state.update_settings(enable_lldp=value))
self.cables_option.toggled.connect(lambda value: self.state.update_settings(create_cables=value))
self.state.switches_changed.connect(self.refresh)
self.state.profile_switched.connect(self.refresh)
self.state.profile_edited.connect(self.refresh_switches)
self.state.settings_changed.connect(self._load_settings)
self._load_settings()
self.refresh()
# ------------------------------------------------------------------
def _load_settings(self):
for widget, key in ((self.lldp_option, "enable_lldp"), (self.cables_option, "create_cables")):
widget.blockSignals(True)
widget.setChecked(bool(self.state.settings.get(key)))
widget.blockSignals(False)
def _status_text(self, row):
status = self.state.switch_status.get(row["id"])
if not status:
return "–"
snapshot = self.state.switch_snapshots.get(row["id"])
when = time.strftime("%H:%M", time.localtime(snapshot["discovered_at"])) if snapshot else ""
return f"{when} · {status[1]}" if when else status[1]
def _status_dot(self, row):
status = self.state.switch_status.get(row["id"])
if not status:
return None
return "success" if status[0] == "ok" else "danger"
def refresh(self):
self.refresh_switches()
self.refresh_results()
def refresh_switches(self):
switches = self.state.switches
self.switch_model.set_rows(switches)
self.switch_stack.setCurrentIndex(1 if switches else 0)
for widget in (self.select_all_button, self.edit_button, self.remove_button, self.lldp_option):
widget.setVisible(bool(switches))
self._update_buttons()
def refresh_results(self):
by_id = {switch["id"]: switch for switch in self.state.switches}
rows = []
for switch_id, snapshot in self.state.switch_snapshots.items():
switch = by_id.get(switch_id)
if not switch:
continue
for interface in snapshot["interfaces"]:
rows.append(dict(interface, switch=switch["name"], switch_id=switch_id))
self.result_model.set_rows(rows)
self.result_stack.setCurrentIndex(1 if rows else 0)
current = self.switch_filter.currentData()
self.switch_filter.blockSignals(True)
self.switch_filter.clear()
self.switch_filter.addItem("Alle Switche", None)
for switch_id in self.state.switch_snapshots:
if switch_id in by_id:
self.switch_filter.addItem(by_id[switch_id]["name"], switch_id)
self.switch_filter.setCurrentIndex(max(0, self.switch_filter.findData(current)))
self.switch_filter.blockSignals(False)
self._apply_result_filters()
def _apply_result_filters(self, *_args):
switch_id = self.switch_filter.currentData()
self.result_proxy.set_predicate("switch", (lambda row: row["switch_id"] == switch_id) if switch_id else None)
self.result_proxy.set_predicate("neighbor", (lambda row: bool(row.get("neighbor")))
if self.only_neighbors.isChecked() else None)
self.result_proxy.set_predicate("up", (lambda row: row.get("connected"))
if self.only_up.isChecked() else None)
rows = self.result_proxy.visible_rows()
neighbors = sum(1 for row in rows if row.get("neighbor"))
up = sum(1 for row in rows if row.get("connected"))
self.result_summary.setText(f"{len(rows)} Schnittstellen · {up} aktiv · {neighbors} mit Nachbar")
self._update_buttons()
def _checked(self):
return self.switch_model.checked_rows()
def _selected(self):
rows = self.switch_table.selectionModel().selectedRows()
return [self.switch_proxy.row_at(index) for index in rows]
def _targets(self):
"""Checked switches, or the selected rows when nothing is checked."""
return self._checked() or self._selected()
def _update_buttons(self, *_args):
busy = self.tasks.busy
targets = self._targets()
with_data = [switch for switch in targets if switch["id"] in self.state.switch_snapshots]
widgets.set_enabled(self.discover_button, bool(targets) and not busy,
"Bitte Switche anhaken." if not targets else "Bitte warten …")
self.discover_button.setText(f"{len(targets)} auslesen" if targets else "Auslesen")
widgets.set_enabled(self.sync_button, bool(with_data) and not busy,
"Bitte zuerst Switche auslesen." if not with_data else "Bitte warten …")
self.sync_button.setText(f"{len(with_data)} nach NetBox übertragen …" if with_data else "Nach NetBox übertragen …")
widgets.set_enabled(self.raw_button, bool(self.state.switch_snapshots), "Noch nichts ausgelesen.")
widgets.set_enabled(self.edit_button, len(self._selected()) == 1, "Bitte genau einen Switch markieren.")
widgets.set_enabled(self.remove_button, bool(targets), "Bitte Switche anhaken oder markieren.")
self.add_button.setEnabled(not busy)
def set_busy(self, busy):
self._update_buttons()
def select_all(self):
rows = self.switch_model.rows
all_checked = len(self.switch_model.checked) == len(rows)
self.switch_model.set_checked({row["id"] for row in rows}, not all_checked)
# ------------------------------------------------------------------
# Actions
# ------------------------------------------------------------------
def add_switches(self):
if self.state.profile is None:
return
def open_dialog(devices):
existing = {switch.get("device_id") for switch in self.state.switches}
dialog = AddSwitchesDialog(self.window, devices, existing)
if dialog.exec() and dialog.result:
self.state.switches.extend(dialog.result)
self.state.touch()
self.refresh_switches()
self.switch_model.set_checked({switch["id"] for switch in dialog.result})
self.window.toast(f"{len(dialog.result)} Switch(e) hinzugefügt – jetzt „Auslesen“ wählen")
if self.state.netbox_devices is not None:
open_dialog(self.state.netbox_devices)
else:
self.actions.load_devices(open_dialog)
def edit_switch(self):
selected = self._selected()
if len(selected) != 1:
return
current = selected[0]
dialog = SwitchDialog(self.window, current, self.state.netbox_devices)
if dialog.exec() and dialog.result:
index = self.state.switches.index(current)
self.state.switches[index] = dialog.result
if dialog.result.get("device_id") != current.get("device_id"):
self.state.switch_snapshots.pop(current["id"], None)
self.state.switch_status.pop(current["id"], None)
self.state.touch()
self.refresh()
def remove_switches(self):
targets = self._targets()
if not targets:
return
names = ", ".join(switch["name"] for switch in targets[:5]) + (" …" if len(targets) > 5 else "")
if not widgets.confirm(self.window, "Switche entfernen",
f"{len(targets)} Switch-Zugang/Zugänge aus dem Profil entfernen?\n{names}\n\n"
"Die Geräte in NetBox bleiben unverändert.", ok_text="Entfernen", destructive=True):
return
ids = {switch["id"] for switch in targets}
self.state.profile["switches"] = [switch for switch in self.state.switches if switch["id"] not in ids]
for switch_id in ids:
self.state.switch_snapshots.pop(switch_id, None)
self.state.switch_status.pop(switch_id, None)
self.state.touch()
self.refresh()
def discover(self):
targets = self._targets()
if not targets:
return
if self.lldp_option.isChecked() and not widgets.confirm(
self.window, "Switch-Konfiguration ändern?",
"„LLDP bei Bedarf aktivieren“ ist eingeschaltet. Ist LLDP auf einem Switch deaktiviert, wird es per "
"Konfigurationsbefehl aktiviert (ohne „write memory“).", ok_text="Auslesen", destructive=True):
return
self.actions.discover_switches(targets)
def sync(self):
targets = [switch["id"] for switch in self._targets() if switch["id"] in self.state.switch_snapshots]
self.actions.sync_switches(targets, self.cables_option.isChecked())
def show_raw(self):
by_id = {switch["id"]: switch for switch in self.state.switches}
items = [(by_id[key], snapshot) for key, snapshot in self.state.switch_snapshots.items() if key in by_id]
if not items:
return
selected = self._selected()
RawDataDialog(self.window, items, selected[0]["id"] if selected else None).exec()
def _context_menu(self, position):
if not self._selected():
return
muted = theme.color("text_muted")
menu = QMenu(self)
menu.addAction(icon("play", muted), "Auslesen", self.discover)
menu.addAction(icon("pencil", muted), "Bearbeiten …", self.edit_switch)
if any(switch["id"] in self.state.switch_snapshots for switch in self._selected()):
menu.addAction(icon("terminal", muted), "SSH-Rohdaten …", self.show_raw)
menu.addSeparator()
menu.addAction(icon("trash", theme.color("danger")), "Entfernen", self.remove_switches)
menu.exec(self.switch_table.viewport().mapToGlobal(position))
+202
View File
@@ -0,0 +1,202 @@
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QComboBox, QHBoxLayout, QStackedWidget
from netbox_sync.ui import widgets
from netbox_sync.ui.import_wizard import ImportWizard
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
from netbox_sync.ui.pages import Page
from netbox_sync.ui.widgets import Card, EmptyState, SearchField, Table, button, label
def _ips(vm):
return ", ".join(ip.split("/")[0] for interface in vm.get("interfaces", []) for ip in interface.get("ips", []))
def _interfaces_tooltip(vm):
lines = [f"{vm['name']} · {vm.get('guest_os') or 'unbekanntes OS'}"]
for interface in vm.get("interfaces", []):
ips = ", ".join(interface.get("ips", [])) or "keine IP"
lines.append(f" {interface['name']} {interface.get('mac', '')} {ips}")
if len(lines) == 1:
lines.append(" Keine Netzwerkschnittstellen gemeldet (VMware Tools / QEMU Agent prüfen)")
return "\n".join(lines)
class VMsPage(Page):
title = "Virtuelle Maschinen"
subtitle = "VMs aus allen aktiven Quellen laden, auswählen und nach NetBox übernehmen."
def __init__(self, window):
super().__init__(window)
self.load_button = self.header.add_action(button("VMs laden", "refresh", "primary", on_click=self.load))
self.stack = QStackedWidget()
self.empty = EmptyState("server", "Noch keine VMs geladen",
"Die Anwendung liest alle aktiven Quellen parallel aus und gleicht sie mit NetBox ab.",
"VMs jetzt laden", self.load,
secondary=("Verbindungen prüfen", lambda: window.navigate("connections")))
self.stack.addWidget(self.empty)
card = Card(padding=0, spacing=0)
filters = QHBoxLayout()
filters.setContentsMargins(16, 14, 16, 12)
filters.setSpacing(8)
self.search = SearchField("Name, IP-Adresse, Betriebssystem …")
self.source_filter = QComboBox()
self.status_filter = QComboBox()
for text, value in (("Alle Zustände", None), ("Eingeschaltet", "active"), ("Ausgeschaltet", "offline")):
self.status_filter.addItem(text, value)
self.netbox_filter = QComboBox()
for text, value in (("NetBox: alle", None), ("Nur neue", "new"), ("Nur vorhandene", "existing")):
self.netbox_filter.addItem(text, value)
filters.addWidget(self.search, 3)
filters.addWidget(self.source_filter, 1)
filters.addWidget(self.status_filter, 1)
filters.addWidget(self.netbox_filter, 1)
card.add(filters)
columns = [
Column("name", "Name", 220, tooltip=_interfaces_tooltip),
Column("netbox", "NetBox", 95, value=self._netbox_state,
color=lambda row: "accent" if self._netbox_state(row) == "Neu" else "text_muted"),
Column("source", "Quelle", 140),
Column("kind", "Typ", 55),
Column("status", "Status", 135, value=lambda row: "Eingeschaltet" if row["status"] == "active" else "Aus",
dot=lambda row: "success" if row["status"] == "active" else "text_faint"),
Column("vcpus", "vCPU", 55, align="right"),
Column("memory", "RAM", 75, align="right", value=lambda row: f"{row['memory'] / 1024:g} GB",
sort=lambda row: row["memory"]),
Column("disk", "Disk", 75, align="right",
value=lambda row: f"{row['disk'] / 1024:.0f} GB" if row.get("disk") else "–",
sort=lambda row: row.get("disk") or 0),
Column("ips", "IP-Adressen", 200, value=_ips),
Column("guest_os", "Betriebssystem", 220),
]
self.model = RowTableModel(columns, checkable=True, row_id=lambda row: row["id"])
self.proxy = FilterProxy(self.model)
self.table = Table()
self.table.setModel(self.proxy)
self.table.sortByColumn(0, Qt.AscendingOrder)
for index, column in enumerate(columns):
self.table.setColumnWidth(index, column.width)
self.table.doubleClicked.connect(self._toggle)
card.add(self.table, 1)
footer = QHBoxLayout()
footer.setContentsMargins(16, 10, 16, 12)
footer.setSpacing(8)
footer.addWidget(button("Alle sichtbaren auswählen", variant="ghost", on_click=self.select_visible))
footer.addWidget(button("Nur neue auswählen", variant="ghost", on_click=self.select_new))
footer.addWidget(button("Auswahl aufheben", variant="ghost", on_click=self.clear_selection))
footer.addStretch(1)
self.selection_label = label("", muted=True)
footer.addWidget(self.selection_label)
self.import_button = button("Importieren …", "upload", "primary", on_click=self.start_import)
footer.addWidget(self.import_button)
card.add(footer)
self.stack.addWidget(card)
self.body.addWidget(self.stack, 1)
self.search.textChanged.connect(self.proxy.set_text)
self.source_filter.currentIndexChanged.connect(self._apply_filters)
self.status_filter.currentIndexChanged.connect(self._apply_filters)
self.netbox_filter.currentIndexChanged.connect(self._apply_filters)
self.model.checked_changed.connect(self._update_selection)
self.state.vms_changed.connect(self.refresh)
self.state.profile_switched.connect(self.refresh)
self.refresh()
def _netbox_state(self, vm):
engine = self.state.engine
if engine is None:
return ""
return "Vorhanden" if vm["name"] in engine.existing_vms else "Neu"
def refresh(self):
vms = self.state.vms
self.stack.setCurrentIndex(1 if vms else 0)
current = self.source_filter.currentData()
self.source_filter.blockSignals(True)
self.source_filter.clear()
self.source_filter.addItem("Alle Quellen", None)
for name in sorted({vm["source"] for vm in vms}, key=str.casefold):
self.source_filter.addItem(name, name)
self.source_filter.setCurrentIndex(max(0, self.source_filter.findData(current)))
self.source_filter.blockSignals(False)
self.model.set_rows(vms)
self._apply_filters()
self.load_button.setText("Neu laden" if vms else "VMs laden")
if not vms:
if not self.state.netbox_configured():
self.empty.set_text(text="Zuerst unter „Verbindungen“ NetBox und mindestens eine Quelle einrichten.")
elif not self.state.sources:
self.empty.set_text(text="Es ist noch keine VMware- oder Proxmox-Quelle hinterlegt.")
else:
self.empty.set_text(text="Die Anwendung liest alle aktiven Quellen parallel aus und gleicht sie "
"mit NetBox ab.")
def _apply_filters(self, *_args):
source = self.source_filter.currentData()
status = self.status_filter.currentData()
netbox_state = self.netbox_filter.currentData()
self.proxy.set_predicate("source", (lambda row: row["source"] == source) if source else None)
self.proxy.set_predicate("status", (lambda row: row["status"] == status) if status else None)
if netbox_state:
wanted = "Neu" if netbox_state == "new" else "Vorhanden"
self.proxy.set_predicate("netbox", lambda row: self._netbox_state(row) == wanted)
else:
self.proxy.set_predicate("netbox", None)
self._update_selection()
def _toggle(self, index):
row = self.proxy.row_at(index)
self.model.set_checked({row["id"]}, row["id"] not in self.model.checked)
def select_visible(self):
self.model.set_checked({row["id"] for row in self.proxy.visible_rows()})
def select_new(self):
self.model.set_checked(set(self.model.checked), False)
self.model.set_checked({row["id"] for row in self.proxy.visible_rows() if self._netbox_state(row) == "Neu"})
def clear_selection(self):
self.model.set_checked(set(self.model.checked), False)
def _update_selection(self):
count = len(self.model.checked)
visible = self.proxy.rowCount()
total = len(self.model.rows)
shown = f"{visible} von {total} angezeigt" if visible != total else f"{total} VMs"
self.selection_label.setText(f"{shown} · {count} ausgewählt")
self.import_button.setText(f"{count} VM(s) importieren …" if count else "Importieren …")
self._update_import_button()
def _update_import_button(self):
count = len(self.model.checked)
enabled = count > 0 and not self.tasks.busy and self.state.engine is not None
widgets.set_enabled(self.import_button, enabled,
"Bitte zuerst VMs in der Tabelle anhaken." if not count else "Bitte warten …")
def set_busy(self, busy):
self.load_button.setEnabled(not busy)
self._update_import_button()
def load(self):
self.actions.load_vms()
def start_import(self):
vms = self.model.checked_rows()
if not vms or self.state.engine is None:
return
if not self.state.engine.clusters:
widgets.message(self.window, "Kein Cluster in NetBox",
"In NetBox ist noch kein Cluster angelegt. Bitte zuerst unter Virtualisierung → Cluster "
"einen Cluster anlegen und die VMs neu laden.", "warning")
return
wizard = ImportWizard(self.window, self.state, self.tasks, vms)
wizard.exec()
if wizard.result_summary:
text, kind = wizard.result_summary
self.window.toast(text, kind)
self.model.refresh()
self._apply_filters()
+11
View File
@@ -0,0 +1,11 @@
import sys
from pathlib import Path
def resource_path(name):
"""Locate bundled files both from source and inside a PyInstaller build."""
base = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parents[1]))
candidate = base / "resources" / name
if candidate.exists():
return candidate
return Path(__file__).resolve().parents[1] / "resources" / name
+195
View File
@@ -0,0 +1,195 @@
"""Application state shared by all pages."""
import copy
from PySide6.QtCore import QObject, QTimer, Signal
from netbox_sync.core.config import DEFAULT_SETTINGS, ProfileStore, empty_profile
from netbox_sync.ui.tasks import logger
log = logger("app")
class AppState(QObject):
profiles_changed = Signal() # names added/removed/renamed
profile_switched = Signal() # another profile is active now
profile_edited = Signal() # data inside the active profile changed
settings_changed = Signal()
netbox_changed = Signal() # connection status / lookup data
vms_changed = Signal()
switches_changed = Signal() # switch list or discovery results
save_failed = Signal(str)
def __init__(self, store=None):
super().__init__()
self.store = store or ProfileStore()
self.profiles = {}
self.active = ""
self.settings = dict(DEFAULT_SETTINGS)
self._save_timer = QTimer(self)
self._save_timer.setSingleShot(True)
self._save_timer.setInterval(500)
self._save_timer.timeout.connect(self.save_now)
self.reset_runtime()
# ------------------------------------------------------------------
# Runtime data (never persisted)
# ------------------------------------------------------------------
def reset_runtime(self):
self.nb = None
self.netbox_status = "unknown" # unknown | ok | error
self.netbox_message = "Noch nicht verbunden"
self.netbox_version = ""
self.engine = None
self.vms = []
self.vms_loaded_at = None
self.netbox_devices = None
self.switch_snapshots = {}
self.switch_status = {}
def set_netbox(self, nb=None, status="ok", message="", engine=None):
if nb is not None:
self.nb = nb
self.netbox_version = getattr(nb, "netbox_version", "")
if engine is not None:
self.engine = engine
self.netbox_status = status
self.netbox_message = message
if status == "error":
self.nb = None
self.engine = None
self.netbox_changed.emit()
# ------------------------------------------------------------------
# Persistence
# ------------------------------------------------------------------
def load(self):
try:
self.profiles, active, self.settings = self.store.load()
except Exception as error: # noqa: BLE001
log.error("Konfiguration konnte nicht geladen werden: %s", error)
self.profiles, active = {}, ""
for context in self.store.decrypt_failures:
log.warning("Gespeichertes Geheimnis nicht lesbar (%s) – bitte neu eingeben.", context)
if self.profiles:
self.active = active if active in self.profiles else sorted(self.profiles, key=str.casefold)[0]
self.profiles_changed.emit()
self.profile_switched.emit()
self.settings_changed.emit()
def schedule_save(self):
self._save_timer.start()
def save_now(self):
self._save_timer.stop()
try:
self.store.save(self.profiles, self.active, self.settings)
except Exception as error: # noqa: BLE001
log.error("Speichern fehlgeschlagen: %s", error)
self.save_failed.emit(str(error))
return False
return True
# ------------------------------------------------------------------
# Profiles
# ------------------------------------------------------------------
@property
def profile(self):
return self.profiles.get(self.active)
def profile_names(self):
return sorted(self.profiles, key=str.casefold)
def switch_profile(self, name):
if name == self.active or name not in self.profiles:
return
self.save_now()
self.active = name
self.reset_runtime()
self.schedule_save()
self.profile_switched.emit()
self.netbox_changed.emit()
self.vms_changed.emit()
self.switches_changed.emit()
def create_profile(self, name, copy_from=None):
profile = copy.deepcopy(self.profiles[copy_from]) if copy_from in self.profiles else empty_profile(name)
profile["name"] = name
self.profiles[name] = profile
self.profiles_changed.emit()
self.active = ""
self.switch_profile(name)
self.save_now()
def rename_profile(self, old, new):
if old not in self.profiles or new in self.profiles:
return
profile = self.profiles.pop(old)
profile["name"] = new
self.profiles[new] = profile
if self.active == old:
self.active = new
self.save_now()
self.profiles_changed.emit()
self.profile_switched.emit()
def delete_profile(self, name):
if name not in self.profiles:
return
del self.profiles[name]
names = self.profile_names()
self.active = ""
self.profiles_changed.emit()
if names:
self.switch_profile(names[0])
else:
self.reset_runtime()
self.profile_switched.emit()
self.save_now()
def edit_profile(self, **fields):
profile = self.profile
if profile is None:
return
changed = {key: value for key, value in fields.items() if profile.get(key) != value}
if not changed:
return
profile.update(changed)
if {"netbox_url", "netbox_token", "netbox_ignore_ssl"} & set(changed):
self.nb = None
self.engine = None
self.netbox_devices = None
self.netbox_status = "unknown"
self.netbox_message = "Verbindungsdaten geändert"
self.netbox_changed.emit()
self.schedule_save()
self.profile_edited.emit()
def touch(self):
"""Call after mutating ``profile['sources']`` or ``profile['switches']`` in place."""
self.schedule_save()
self.profile_edited.emit()
def update_settings(self, **values):
self.settings.update(values)
self.schedule_save()
self.settings_changed.emit()
# ------------------------------------------------------------------
# Convenience
# ------------------------------------------------------------------
@property
def sources(self):
return self.profile["sources"] if self.profile else []
@property
def switches(self):
return self.profile["switches"] if self.profile else []
def netbox_configured(self):
profile = self.profile
return bool(profile and profile.get("netbox_url") and profile.get("netbox_token"))
+190
View File
@@ -0,0 +1,190 @@
"""Background tasks and the application-wide activity log."""
import logging
import threading
import time
import traceback
from dataclasses import dataclass, field
from PySide6.QtCore import QObject, QRunnable, QThreadPool, Signal
SUCCESS = 25
logging.addLevelName(SUCCESS, "SUCCESS")
LEVELS = {"debug": logging.DEBUG, "info": logging.INFO, "success": SUCCESS,
"warning": logging.WARNING, "error": logging.ERROR}
LEVEL_NAMES = {value: key for key, value in LEVELS.items()}
AREAS = {"app": "Allgemein", "netbox": "NetBox", "vm": "VMs", "switch": "Switche", "ipam": "IPAM"}
@dataclass
class LogEntry:
timestamp: float
level: str
area: str
text: str
details: str = field(default="")
class LogBus(QObject):
"""Receives log records from any thread and re-emits them in the GUI thread."""
entry = Signal(object)
class QtLogHandler(logging.Handler):
def __init__(self, bus):
super().__init__(level=logging.INFO)
self.bus = bus
def emit(self, record):
if not record.name.startswith("netbox_sync"):
return
area = record.name.split(".")[1] if record.name.count(".") >= 1 else "app"
level = LEVEL_NAMES.get(record.levelno, "info")
details = ""
if record.exc_info:
details = "".join(traceback.format_exception(*record.exc_info))
self.bus.entry.emit(LogEntry(record.created, level, area if area in AREAS else "app",
record.getMessage(), details))
log_bus = LogBus()
def logger(area):
return logging.getLogger(f"netbox_sync.{area}")
def area_log(area):
"""Return a ``log(text, level="info")`` callback for the core modules."""
target = logger(area)
def write(text, level="info"):
target.log(LEVELS.get(level, logging.INFO), text)
return write
class TaskCancelled(Exception):
pass
class TaskContext:
def __init__(self, signals, area):
self._signals = signals
self._cancel = threading.Event()
self.area = area
self.log = area_log(area)
def progress(self, value, maximum=0, text=""):
self._signals.progress.emit(int(value), int(maximum), text)
@property
def cancelled(self):
return self._cancel.is_set()
def check_cancelled(self):
if self._cancel.is_set():
raise TaskCancelled()
def cancel(self):
self._cancel.set()
class _Signals(QObject):
progress = Signal(int, int, str)
succeeded = Signal(object)
failed = Signal(object)
finished = Signal()
class Task(QRunnable):
def __init__(self, function, area, title):
super().__init__()
self.setAutoDelete(False)
self.function = function
self.title = title
self.signals = _Signals()
self.context = TaskContext(self.signals, area)
self.started_at = None
def run(self):
self.started_at = time.monotonic()
try:
result = self.function(self.context)
except TaskCancelled as error:
self.signals.failed.emit(error)
except Exception as error: # noqa: BLE001 - reported to the UI
logger(self.context.area).debug("Task %s fehlgeschlagen", self.title, exc_info=True)
error.traceback_text = traceback.format_exc()
self.signals.failed.emit(error)
else:
self.signals.succeeded.emit(result)
finally:
self.signals.finished.emit()
def cancel(self):
self.context.cancel()
class TaskManager(QObject):
"""Runs one foreground task at a time and exposes busy/progress state."""
busy_changed = Signal(bool)
progress = Signal(int, int, str)
started = Signal(str)
def __init__(self):
super().__init__()
self.pool = QThreadPool.globalInstance()
self.pool.setMaxThreadCount(max(4, self.pool.maxThreadCount()))
self.current = None
self._tasks = set()
@property
def busy(self):
return self.current is not None
def run(self, function, *, title, area="app", on_success=None, on_error=None, on_finished=None,
on_progress=None, cancellable=True):
if self.current is not None:
logger("app").warning("Bitte warten, bis „%s“ abgeschlossen ist.", self.current.title)
return None
task = Task(function, area, title)
task.cancellable = cancellable
self.current = task
self._tasks.add(task)
def finished():
self._tasks.discard(task)
if self.current is task:
self.current = None
self.busy_changed.emit(False)
if on_finished:
on_finished()
def failed(error):
if isinstance(error, TaskCancelled):
logger(area).warning("%s abgebrochen", title)
elif on_error:
on_error(error)
else:
logger(area).error("%s: %s", title, error)
task.signals.progress.connect(self.progress)
if on_progress:
task.signals.progress.connect(on_progress)
if on_success:
task.signals.succeeded.connect(on_success)
task.signals.failed.connect(failed)
task.signals.finished.connect(finished)
self.busy_changed.emit(True)
self.started.emit(title)
self.pool.start(task)
return task
def cancel(self):
if self.current is not None:
self.current.cancel()
+314
View File
@@ -0,0 +1,314 @@
"""Light and dark design tokens plus the application style sheet."""
from string import Template
from PySide6.QtCore import QObject, Qt, Signal
from PySide6.QtGui import QColor, QFont, QPalette
from PySide6.QtWidgets import QApplication
from netbox_sync.ui.icons import svg_file
LIGHT = {
"bg": "#F3F5F9",
"surface": "#FFFFFF",
"surface_alt": "#F8FAFC",
"hover": "#EEF2F7",
"border": "#E2E8F0",
"border_strong": "#CBD5E1",
"text": "#0F172A",
"text_muted": "#64748B",
"text_faint": "#94A3B8",
"accent": "#0A6CF0",
"accent_hover": "#085DCF",
"accent_pressed": "#074EAD",
"accent_soft": "#E7F0FE",
"accent_text": "#FFFFFF",
"success": "#15803D",
"success_soft": "#DCFCE7",
"warning": "#B45309",
"warning_soft": "#FEF3C7",
"danger": "#DC2626",
"danger_soft": "#FEE2E2",
"sidebar": "#0B1F3A",
"sidebar_text": "#B6C3D6",
"sidebar_hover": "#132B4D",
"sidebar_active": "#1B3A66",
"sidebar_accent": "#22D3EE",
"selection": "#DBE8FD",
"log_bg": "#FBFCFE",
}
DARK = {
"bg": "#0E1521",
"surface": "#151E2C",
"surface_alt": "#192334",
"hover": "#1E2A3D",
"border": "#243044",
"border_strong": "#334155",
"text": "#E2E8F0",
"text_muted": "#94A3B8",
"text_faint": "#64748B",
"accent": "#3B8BFF",
"accent_hover": "#5A9DFF",
"accent_pressed": "#2F7BEA",
"accent_soft": "#16294A",
"accent_text": "#FFFFFF",
"success": "#4ADE80",
"success_soft": "#13301F",
"warning": "#FBBF24",
"warning_soft": "#33280F",
"danger": "#F87171",
"danger_soft": "#3A1717",
"sidebar": "#09111D",
"sidebar_text": "#94A3B8",
"sidebar_hover": "#121E31",
"sidebar_active": "#18294A",
"sidebar_accent": "#22D3EE",
"selection": "#1D3357",
"log_bg": "#111926",
}
QSS = Template("""
* { outline: 0; }
QWidget { color: $text; font-size: 10pt; }
QMainWindow, QDialog, #PageRoot, QStackedWidget#Pages { background: $bg; }
QDialog { background: $bg; }
QToolTip { background: $text; color: $surface; border: none; padding: 6px 8px; border-radius: 6px; }
/* ---------- Sidebar ---------- */
#Sidebar { background: $sidebar; }
#Sidebar QLabel { color: $sidebar_text; }
#Sidebar #AppTitle { color: #FFFFFF; font-size: 12pt; font-weight: 600; }
#Sidebar #AppSubtitle { color: $sidebar_text; font-size: 8.5pt; }
#Sidebar #SectionLabel { color: #6B7FA0; font-size: 8pt; font-weight: 600; }
#Sidebar QPushButton[nav="true"] {
color: $sidebar_text; background: transparent; border: none; border-radius: 8px;
padding: 9px 12px; text-align: left; font-size: 10pt;
}
#Sidebar QPushButton[nav="true"]:hover { background: $sidebar_hover; color: #FFFFFF; }
#Sidebar QPushButton[nav="true"]:checked { background: $sidebar_active; color: #FFFFFF; font-weight: 600; }
#Sidebar QPushButton[nav="true"]:disabled { color: #3E5272; }
#Sidebar QComboBox {
background: $sidebar_hover; color: #FFFFFF; border: 1px solid #22385A; border-radius: 8px; padding: 6px 10px;
}
#Sidebar QComboBox::drop-down { border: none; width: 24px; }
#Sidebar QComboBox::down-arrow { image: url($chevron_light); width: 14px; height: 14px; }
#Sidebar QToolButton { background: $sidebar_hover; border: 1px solid #22385A; border-radius: 8px; padding: 5px; }
#Sidebar QToolButton:hover { background: $sidebar_active; }
#Sidebar QToolButton::menu-indicator { image: none; }
#Sidebar #VersionLabel { color: #4F6385; font-size: 8pt; }
#Sidebar QLabel[badge="true"] { background: $danger; color: #FFFFFF; }
/* ---------- Typography ---------- */
#PageTitle { font-size: 17pt; font-weight: 600; color: $text; }
#PageSubtitle { color: $text_muted; font-size: 10pt; }
#CardTitle { font-size: 11pt; font-weight: 600; }
#CardSubtitle, QLabel[muted="true"] { color: $text_muted; }
QLabel[faint="true"] { color: $text_faint; }
#StatValue { font-size: 15pt; font-weight: 600; }
#StatLabel { color: $text_muted; font-size: 9pt; }
#EmptyTitle { font-size: 13pt; font-weight: 600; }
#WizardStep { color: $text_faint; font-weight: 600; }
#WizardStep[active="true"] { color: $accent; }
#WizardStep[done="true"] { color: $success; }
#SummaryKey { color: $text_muted; }
#SummaryValue { font-weight: 600; }
/* ---------- Cards ---------- */
#Card { background: $surface; border: 1px solid $border; border-radius: 12px; }
#Card[flat="true"] { background: transparent; border: none; }
#Banner { border-radius: 10px; border: 1px solid $border; background: $surface_alt; }
#Banner[kind="info"] { background: $accent_soft; border-color: $accent_soft; }
#Banner[kind="warning"] { background: $warning_soft; border-color: $warning_soft; }
#Banner[kind="error"] { background: $danger_soft; border-color: $danger_soft; }
#Banner[kind="success"] { background: $success_soft; border-color: $success_soft; }
#Banner QLabel { background: transparent; }
#Separator { background: $border; max-height: 1px; min-height: 1px; }
/* ---------- Badges ---------- */
QLabel[badge="true"] { border-radius: 9px; padding: 2px 9px; font-size: 8.5pt; font-weight: 600; }
QLabel[badge="true"][kind="neutral"] { background: $hover; color: $text_muted; }
QLabel[badge="true"][kind="info"] { background: $accent_soft; color: $accent; }
QLabel[badge="true"][kind="success"] { background: $success_soft; color: $success; }
QLabel[badge="true"][kind="warning"] { background: $warning_soft; color: $warning; }
QLabel[badge="true"][kind="error"] { background: $danger_soft; color: $danger; }
/* ---------- Buttons ---------- */
QPushButton {
background: $surface; border: 1px solid $border_strong; border-radius: 8px;
padding: 7px 14px; color: $text; font-weight: 500;
}
QPushButton:hover { background: $hover; }
QPushButton:pressed { background: $border; }
QPushButton:disabled { color: $text_faint; border-color: $border; background: $surface_alt; }
QPushButton[variant="primary"] { background: $accent; border-color: $accent; color: $accent_text; font-weight: 600; }
QPushButton[variant="primary"]:hover { background: $accent_hover; border-color: $accent_hover; }
QPushButton[variant="primary"]:pressed { background: $accent_pressed; }
QPushButton[variant="primary"]:disabled { background: $border; border-color: $border; color: $text_faint; }
QPushButton[variant="danger"] { color: $danger; }
QPushButton[variant="danger"]:hover { background: $danger_soft; border-color: $danger; }
QPushButton[variant="ghost"] { background: transparent; border-color: transparent; color: $text_muted; }
QPushButton[variant="ghost"]:hover { background: $hover; color: $text; }
QPushButton[variant="link"] { background: transparent; border: none; color: $accent; padding: 2px 4px; }
QPushButton::menu-indicator { image: url($chevron); subcontrol-origin: padding; subcontrol-position: right center; width: 12px; right: 8px; }
QToolButton { background: transparent; border: none; border-radius: 6px; padding: 4px; }
QToolButton:hover { background: $hover; }
/* ---------- Inputs ---------- */
QLineEdit, QComboBox, QSpinBox, QPlainTextEdit, QTextEdit {
background: $surface; border: 1px solid $border_strong; border-radius: 8px;
padding: 6px 9px; selection-background-color: $accent; selection-color: #FFFFFF;
}
QPlainTextEdit, QTextEdit { padding: 6px; }
QLineEdit:hover, QComboBox:hover, QSpinBox:hover, QPlainTextEdit:hover { border-color: $text_faint; }
QLineEdit:focus, QComboBox:focus, QSpinBox:focus, QPlainTextEdit:focus, QTextEdit:focus { border: 1px solid $accent; }
QLineEdit:disabled, QComboBox:disabled, QSpinBox:disabled { background: $surface_alt; color: $text_faint; }
QLineEdit[invalid="true"] { border-color: $danger; }
QComboBox::drop-down { border: none; width: 26px; }
QComboBox::down-arrow { image: url($chevron); width: 14px; height: 14px; }
QComboBox QAbstractItemView {
background: $surface; border: 1px solid $border_strong; border-radius: 8px; padding: 4px;
selection-background-color: $accent_soft; selection-color: $text; outline: 0;
}
QSpinBox::up-button, QSpinBox::down-button { width: 18px; border: none; background: transparent; }
QSpinBox::up-arrow { image: url($chevron_up); width: 10px; height: 10px; }
QSpinBox::down-arrow { image: url($chevron); width: 10px; height: 10px; }
QCheckBox, QRadioButton { spacing: 8px; background: transparent; }
QCheckBox::indicator, QRadioButton::indicator, QTableView::indicator {
width: 16px; height: 16px; border: 1px solid $border_strong; background: $surface;
}
QCheckBox::indicator, QTableView::indicator { border-radius: 4px; }
QRadioButton::indicator { border-radius: 9px; }
QCheckBox::indicator:hover, QRadioButton::indicator:hover, QTableView::indicator:hover { border-color: $accent; }
QCheckBox::indicator:checked, QTableView::indicator:checked { background: $accent; border-color: $accent; image: url($check); }
QCheckBox::indicator:indeterminate { background: $accent; border-color: $accent; }
QRadioButton::indicator:checked { background: $accent; border-color: $accent; image: url($radio_dot); }
QCheckBox:disabled { color: $text_faint; }
/* ---------- Tables ---------- */
QTableView, QTreeView, QListView {
background: $surface; alternate-background-color: $surface_alt; border: none;
gridline-color: transparent; selection-background-color: $selection; selection-color: $text;
}
QTableView::item, QTreeView::item { padding: 4px 6px; border: none; }
QTableView::item:hover, QTreeView::item:hover { background: $hover; }
QTableView::item:selected, QTreeView::item:selected { background: $selection; color: $text; }
QHeaderView { background: $surface; }
QHeaderView::section {
background: $surface; color: $text_muted; border: none; border-bottom: 1px solid $border;
padding: 8px 6px; font-weight: 600; font-size: 9pt;
}
QHeaderView::section:hover { color: $text; }
QHeaderView::down-arrow { image: url($chevron); width: 10px; height: 10px; }
QHeaderView::up-arrow { image: url($chevron_up); width: 10px; height: 10px; }
QTableCornerButton::section { background: $surface; border: none; }
/* ---------- Misc ---------- */
QScrollBar:vertical { background: transparent; width: 10px; margin: 2px; }
QScrollBar:horizontal { background: transparent; height: 10px; margin: 2px; }
QScrollBar::handle { background: $border_strong; border-radius: 3px; min-height: 30px; min-width: 30px; }
QScrollBar::handle:hover { background: $text_faint; }
QScrollBar::add-line, QScrollBar::sub-line { width: 0; height: 0; }
QScrollBar::add-page, QScrollBar::sub-page { background: transparent; }
QScrollArea { background: transparent; border: none; }
QScrollArea > QWidget > QWidget { background: transparent; }
QSplitter::handle { background: transparent; }
QSplitter::handle:vertical { height: 10px; }
QSplitter::handle:horizontal { width: 10px; }
QProgressBar {
background: $border; border: none; border-radius: 4px; height: 8px; text-align: center; color: transparent;
max-height: 8px;
}
QProgressBar::chunk { background: $accent; border-radius: 4px; }
QMenu { background: $surface; border: 1px solid $border_strong; border-radius: 8px; padding: 5px; }
QMenu::item { padding: 7px 26px 7px 12px; border-radius: 6px; }
QMenu::item:selected { background: $accent_soft; color: $text; }
QMenu::separator { height: 1px; background: $border; margin: 4px 6px; }
QMenu::icon { padding-left: 8px; }
QTabWidget::pane { border: 1px solid $border; border-radius: 10px; background: $surface; top: -1px; }
QTabBar::tab {
background: transparent; color: $text_muted; padding: 8px 14px; border: none;
border-bottom: 2px solid transparent; margin-right: 4px;
}
QTabBar::tab:selected { color: $accent; border-bottom: 2px solid $accent; font-weight: 600; }
QTabBar::tab:hover { color: $text; }
#StatusBar { background: $surface; border-top: 1px solid $border; }
#StatusBar QLabel { color: $text_muted; font-size: 9pt; }
#Toast { background: $text; border-radius: 10px; }
#Toast QLabel { color: $surface; background: transparent; }
#LogView { background: $log_bg; border: none; font-family: "Cascadia Mono", Consolas, monospace; font-size: 9pt; }
#StepCircle { border-radius: 14px; min-width: 28px; max-width: 28px; min-height: 28px; max-height: 28px;
background: $hover; color: $text_muted; font-weight: 600; }
#StepCircle[done="true"] { background: $success_soft; color: $success; }
""")
class ThemeManager(QObject):
"""Applies a theme and tells widgets when colours change."""
changed = Signal()
def __init__(self):
super().__init__()
self.mode = "system"
self.tokens = dict(LIGHT)
self.dark = False
def color(self, name):
return self.tokens[name]
def resolve_dark(self, mode):
if mode == "dark":
return True
if mode == "light":
return False
hints = QApplication.styleHints()
return hasattr(hints, "colorScheme") and hints.colorScheme() == Qt.ColorScheme.Dark
def apply(self, mode=None):
app = QApplication.instance()
if mode:
self.mode = mode
self.dark = self.resolve_dark(self.mode)
self.tokens = dict(DARK if self.dark else LIGHT)
tokens = self.tokens
palette = QPalette()
roles = {
QPalette.Window: tokens["bg"], QPalette.WindowText: tokens["text"],
QPalette.Base: tokens["surface"], QPalette.AlternateBase: tokens["surface_alt"],
QPalette.Text: tokens["text"], QPalette.Button: tokens["surface"],
QPalette.ButtonText: tokens["text"], QPalette.Highlight: tokens["accent"],
QPalette.HighlightedText: "#FFFFFF", QPalette.ToolTipBase: tokens["text"],
QPalette.ToolTipText: tokens["surface"], QPalette.PlaceholderText: tokens["text_faint"],
QPalette.Link: tokens["accent"], QPalette.Mid: tokens["border_strong"],
QPalette.Midlight: tokens["border"], QPalette.Light: tokens["surface"],
QPalette.Dark: tokens["border_strong"],
}
for role, value in roles.items():
palette.setColor(role, QColor(value))
for role in (QPalette.Text, QPalette.WindowText, QPalette.ButtonText):
palette.setColor(QPalette.Disabled, role, QColor(tokens["text_faint"]))
app.setPalette(palette)
style = QSS.substitute(
tokens,
chevron=svg_file("chevron-down", tokens["text_muted"], 2.2),
chevron_up=svg_file("chevron-up", tokens["text_muted"], 2.2),
chevron_light=svg_file("chevron-down", "#B6C3D6", 2.2),
check=svg_file("check", "#FFFFFF", 3.0),
radio_dot=svg_file("radio-dot", "#FFFFFF"),
)
app.setStyleSheet(style)
self.changed.emit()
def base_font():
font = QFont("Segoe UI")
font.setPointSizeF(10)
font.setHintingPreference(QFont.PreferNoHinting)
return font
theme = ThemeManager()
+572
View File
@@ -0,0 +1,572 @@
"""Reusable widgets that give every page the same look and feel."""
from PySide6.QtCore import QEasingCurve, QPropertyAnimation, QSize, Qt, QTimer, Signal
from PySide6.QtWidgets import (
QAbstractItemView,
QCheckBox,
QComboBox,
QCompleter,
QDialog,
QDialogButtonBox,
QFrame,
QGraphicsOpacityEffect,
QHBoxLayout,
QHeaderView,
QLabel,
QLineEdit,
QPlainTextEdit,
QPushButton,
QSizePolicy,
QTableView,
QVBoxLayout,
QWidget,
)
from netbox_sync.ui.icons import icon
from netbox_sync.ui.theme import theme
def repolish(widget):
widget.style().unpolish(widget)
widget.style().polish(widget)
widget.update()
class ThemedIconMixin:
"""Re-render an icon whenever the theme changes."""
def _bind_icon(self, name, color_token, setter):
def apply():
setter(icon(name, theme.color(color_token)))
apply()
theme.changed.connect(apply)
def button(text, icon_name=None, variant=None, on_click=None, tooltip=None, parent=None):
widget = QPushButton(text, parent)
widget.setCursor(Qt.PointingHandCursor)
if variant:
widget.setProperty("variant", variant)
if icon_name:
token = {"primary": "accent_text", "danger": "danger", "link": "accent"}.get(variant, "text_muted")
def apply_icon():
color = "#FFFFFF" if token == "accent_text" else theme.color(token)
if not widget.isEnabled() and variant == "primary":
color = theme.color("text_faint")
widget.setIcon(icon(icon_name, color))
apply_icon()
theme.changed.connect(apply_icon)
widget.setIconSize(QSize(16, 16))
widget._apply_icon = apply_icon
if on_click:
widget.clicked.connect(on_click)
if tooltip:
widget.setToolTip(tooltip)
return widget
def set_enabled(widget, enabled, reason=None):
"""Enable/disable a button and show why it is disabled."""
widget.setEnabled(enabled)
if hasattr(widget, "_default_tooltip") is False:
widget._default_tooltip = widget.toolTip()
widget.setToolTip(widget._default_tooltip if enabled or not reason else reason)
if hasattr(widget, "_apply_icon"):
widget._apply_icon()
def label(text="", muted=False, faint=False, wrap=False, object_name=None, selectable=False):
widget = QLabel(text)
if muted:
widget.setProperty("muted", True)
if faint:
widget.setProperty("faint", True)
if wrap:
widget.setWordWrap(True)
if object_name:
widget.setObjectName(object_name)
if selectable:
widget.setTextInteractionFlags(Qt.TextSelectableByMouse)
return widget
def hline():
line = QFrame()
line.setObjectName("Separator")
line.setFrameShape(QFrame.NoFrame)
return line
class Badge(QLabel):
def __init__(self, text="", kind="neutral"):
super().__init__(text)
self.setProperty("badge", True)
self.setAlignment(Qt.AlignCenter)
self.set(text, kind)
def set(self, text, kind="neutral"):
self.setText(text)
self.setProperty("kind", kind)
self.setVisible(bool(text))
repolish(self)
class Card(QFrame):
def __init__(self, title=None, subtitle=None, parent=None, padding=18, spacing=12):
super().__init__(parent)
self.setObjectName("Card")
self.layout_ = QVBoxLayout(self)
self.layout_.setContentsMargins(padding, padding, padding, padding)
self.layout_.setSpacing(spacing)
self.header = None
self.actions = None
if title:
self.header = QHBoxLayout()
self.header.setSpacing(8)
text_box = QVBoxLayout()
text_box.setSpacing(2)
self.title_label = label(title, object_name="CardTitle")
text_box.addWidget(self.title_label)
if subtitle:
self.subtitle_label = label(subtitle, object_name="CardSubtitle", wrap=True)
text_box.addWidget(self.subtitle_label)
self.header.addLayout(text_box, 1)
self.actions = QHBoxLayout()
self.actions.setSpacing(8)
self.header.addLayout(self.actions)
self.layout_.addLayout(self.header)
def add(self, widget, stretch=0):
if isinstance(widget, QWidget):
self.layout_.addWidget(widget, stretch)
else:
self.layout_.addLayout(widget, stretch)
return widget
def add_action(self, widget):
self.actions.addWidget(widget)
return widget
class PageHeader(QWidget):
def __init__(self, title, subtitle=""):
super().__init__()
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(10)
texts = QVBoxLayout()
texts.setSpacing(3)
self.title = label(title, object_name="PageTitle")
self.subtitle = label(subtitle, object_name="PageSubtitle", wrap=True)
texts.addWidget(self.title)
texts.addWidget(self.subtitle)
layout.addLayout(texts, 1)
self.actions = QHBoxLayout()
self.actions.setSpacing(8)
layout.addLayout(self.actions)
def add_action(self, widget):
self.actions.addWidget(widget)
return widget
class Banner(QFrame):
"""Inline message instead of yet another modal dialog."""
ICONS = {"info": ("info", "accent"), "warning": ("warning", "warning"),
"error": ("error", "danger"), "success": ("success", "success")}
def __init__(self, text="", kind="info", action_text=None, on_action=None, closable=False):
super().__init__()
self.setObjectName("Banner")
layout = QHBoxLayout(self)
layout.setContentsMargins(12, 10, 12, 10)
layout.setSpacing(10)
self.icon_label = QLabel()
self.icon_label.setFixedSize(18, 18)
layout.addWidget(self.icon_label, 0, Qt.AlignTop)
self.text_label = label(text, wrap=True)
self.text_label.setTextFormat(Qt.RichText)
self.text_label.setOpenExternalLinks(False)
layout.addWidget(self.text_label, 1)
self.action = None
if action_text:
self.action = button(action_text, variant="link", on_click=on_action)
layout.addWidget(self.action, 0, Qt.AlignVCenter)
if closable:
close = button("", "x", "ghost", on_click=self.hide)
close.setFixedSize(26, 26)
layout.addWidget(close, 0, Qt.AlignTop)
self.kind = kind
self.set(text, kind)
theme.changed.connect(lambda: self.set(self.text_label.text(), self.kind))
def set(self, text, kind=None):
if kind:
self.kind = kind
self.setProperty("kind", self.kind)
name, token = self.ICONS[self.kind]
self.icon_label.setPixmap(icon(name, theme.color(token)).pixmap(18, 18))
self.text_label.setText(text)
repolish(self)
class EmptyState(QWidget):
def __init__(self, icon_name, title, text, action_text=None, on_action=None, secondary=None):
super().__init__()
layout = QVBoxLayout(self)
layout.setContentsMargins(24, 40, 24, 40)
layout.setSpacing(10)
layout.addStretch(1)
self.icon_label = QLabel()
self.icon_label.setAlignment(Qt.AlignCenter)
icon_name_ = icon_name
def apply():
self.icon_label.setPixmap(icon(icon_name_, theme.color("text_faint"), 1.5).pixmap(56, 56))
apply()
theme.changed.connect(apply)
layout.addWidget(self.icon_label)
self.title_label = label(title, object_name="EmptyTitle")
self.title_label.setAlignment(Qt.AlignCenter)
layout.addWidget(self.title_label)
self.text_label = label(text, muted=True, wrap=True)
self.text_label.setAlignment(Qt.AlignCenter)
self.text_label.setMaximumWidth(520)
layout.addWidget(self.text_label, 0, Qt.AlignHCenter)
buttons = QHBoxLayout()
buttons.addStretch(1)
self.action = None
if secondary:
buttons.addWidget(button(secondary[0], secondary[2] if len(secondary) > 2 else None,
on_click=secondary[1]))
if action_text:
self.action = button(action_text, "arrow-right", "primary", on_click=on_action)
buttons.addWidget(self.action)
buttons.addStretch(1)
layout.addSpacing(6)
layout.addLayout(buttons)
layout.addStretch(2)
def set_text(self, title=None, text=None):
if title is not None:
self.title_label.setText(title)
if text is not None:
self.text_label.setText(text)
class StatTile(QFrame):
clicked = Signal()
def __init__(self, icon_name, caption):
super().__init__()
self.setObjectName("Card")
self.setCursor(Qt.PointingHandCursor)
layout = QHBoxLayout(self)
layout.setContentsMargins(18, 16, 18, 16)
layout.setSpacing(14)
self.icon_label = QLabel()
self.icon_label.setFixedSize(40, 40)
self.icon_label.setAlignment(Qt.AlignCenter)
self._icon_name = icon_name
layout.addWidget(self.icon_label, 0, Qt.AlignTop)
texts = QVBoxLayout()
texts.setSpacing(2)
self.caption = label(caption, object_name="StatLabel")
self.value = label("–", object_name="StatValue")
self.detail = label("", muted=True, wrap=True)
texts.addWidget(self.caption)
texts.addWidget(self.value)
texts.addWidget(self.detail)
layout.addLayout(texts, 1)
self.badge = Badge()
layout.addWidget(self.badge, 0, Qt.AlignTop)
self._apply()
theme.changed.connect(self._apply)
def _apply(self):
self.icon_label.setStyleSheet(
f"background: {theme.color('accent_soft')}; border-radius: 10px;"
)
self.icon_label.setPixmap(icon(self._icon_name, theme.color("accent")).pixmap(22, 22))
def set(self, value, detail="", badge_text="", badge_kind="neutral"):
self.value.setText(value)
self.detail.setText(detail)
self.detail.setVisible(bool(detail))
self.badge.set(badge_text, badge_kind)
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
self.clicked.emit()
super().mouseReleaseEvent(event)
class SearchField(QLineEdit):
def __init__(self, placeholder="Suchen …"):
super().__init__()
self.setPlaceholderText(placeholder)
self.setClearButtonEnabled(True)
self._action = None
def apply():
if self._action:
self.removeAction(self._action)
self._action = self.addAction(icon("search", theme.color("text_faint")), QLineEdit.LeadingPosition)
apply()
theme.changed.connect(apply)
self.setMinimumWidth(220)
class PasswordField(QLineEdit):
def __init__(self, placeholder=""):
super().__init__()
self.setEchoMode(QLineEdit.Password)
self.setPlaceholderText(placeholder)
self._toggle = self.addAction(icon("eye", theme.color("text_muted")), QLineEdit.TrailingPosition)
self._toggle.setToolTip("Anzeigen")
self._toggle.triggered.connect(self.toggle)
theme.changed.connect(self._update_icon)
def toggle(self):
visible = self.echoMode() == QLineEdit.Password
self.setEchoMode(QLineEdit.Normal if visible else QLineEdit.Password)
self._update_icon()
def _update_icon(self):
hidden = self.echoMode() == QLineEdit.Password
self._toggle.setIcon(icon("eye" if hidden else "eye-off", theme.color("text_muted")))
self._toggle.setToolTip("Anzeigen" if hidden else "Verbergen")
class SearchableComboBox(QComboBox):
"""Editable combo box with substring completion – handy for long NetBox lists."""
def __init__(self, placeholder=""):
super().__init__()
self.setEditable(True)
self.setInsertPolicy(QComboBox.NoInsert)
self.lineEdit().setPlaceholderText(placeholder)
completer = QCompleter(self.model(), self)
completer.setFilterMode(Qt.MatchContains)
completer.setCaseSensitivity(Qt.CaseInsensitive)
completer.setCompletionMode(QCompleter.PopupCompletion)
self.setCompleter(completer)
self.setMaxVisibleItems(18)
def set_items(self, items, current=None):
self.blockSignals(True)
self.clear()
for item in items:
if isinstance(item, tuple):
self.addItem(item[0], item[1])
else:
self.addItem(item, item)
self.completer().setModel(self.model())
if current is not None:
self.select_data(current)
else:
self.setCurrentIndex(-1)
self.blockSignals(False)
def select_data(self, data):
index = self.findData(data)
self.setCurrentIndex(index)
if index < 0:
self.setEditText("")
def valid_data(self):
"""Return the item data only if the visible text matches an item."""
index = self.findText(self.currentText(), Qt.MatchFixedString)
return self.itemData(index) if index >= 0 else None
def configure_table(view, stretch_column=None, selection=QAbstractItemView.ExtendedSelection):
view.setAlternatingRowColors(True)
view.setSelectionBehavior(QAbstractItemView.SelectRows)
view.setSelectionMode(selection)
view.setShowGrid(False)
view.setWordWrap(False)
view.setSortingEnabled(True)
view.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)
view.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel)
view.verticalHeader().setVisible(False)
view.verticalHeader().setDefaultSectionSize(34)
header = view.horizontalHeader()
header.setHighlightSections(False)
header.setDefaultAlignment(Qt.AlignLeft | Qt.AlignVCenter)
header.setSectionResizeMode(QHeaderView.Interactive)
header.setStretchLastSection(stretch_column is None)
if stretch_column is not None:
header.setSectionResizeMode(stretch_column, QHeaderView.Stretch)
view.setEditTriggers(QAbstractItemView.NoEditTriggers)
return view
class Table(QTableView):
def __init__(self, stretch_column=None):
super().__init__()
configure_table(self, stretch_column)
class Toast(QFrame):
"""Short non-blocking confirmation in the lower right corner."""
def __init__(self, parent):
super().__init__(parent)
self.setObjectName("Toast")
layout = QHBoxLayout(self)
layout.setContentsMargins(14, 11, 16, 11)
layout.setSpacing(10)
self.icon_label = QLabel()
self.icon_label.setFixedSize(18, 18)
layout.addWidget(self.icon_label)
self.text_label = QLabel()
self.text_label.setWordWrap(True)
self.text_label.setMaximumWidth(420)
layout.addWidget(self.text_label)
self.effect = QGraphicsOpacityEffect(self)
self.setGraphicsEffect(self.effect)
self.animation = QPropertyAnimation(self.effect, b"opacity", self)
self.animation.setDuration(220)
self.animation.setEasingCurve(QEasingCurve.OutCubic)
self.timer = QTimer(self)
self.timer.setSingleShot(True)
self.timer.timeout.connect(self.fade_out)
self.hide()
def show_message(self, text, kind="success", duration=4500):
colors = {"success": "#4ADE80", "info": "#60A5FA", "warning": "#FBBF24", "error": "#F87171"}
names = {"success": "success", "info": "info", "warning": "warning", "error": "error"}
self.icon_label.setPixmap(icon(names.get(kind, "info"), colors.get(kind, "#60A5FA")).pixmap(18, 18))
self.text_label.setText(text)
self.adjustSize()
self.reposition()
self.raise_()
self.show()
self.animation.stop()
self.animation.setStartValue(0.0)
self.animation.setEndValue(1.0)
self.animation.start()
self.timer.start(duration)
def reposition(self):
parent = self.parentWidget()
if parent:
self.move(parent.width() - self.width() - 24, parent.height() - self.height() - 52)
def fade_out(self):
self.animation.stop()
self.animation.setStartValue(1.0)
self.animation.setEndValue(0.0)
self.animation.finished.connect(self._hide_once)
self.animation.start()
def _hide_once(self):
self.animation.finished.disconnect(self._hide_once)
self.hide()
def mousePressEvent(self, _event):
self.timer.stop()
self.hide()
class TextDialog(QDialog):
"""Read-only text viewer with copy support."""
def __init__(self, parent, title, text):
super().__init__(parent)
self.setWindowTitle(title)
self.resize(900, 600)
layout = QVBoxLayout(self)
layout.setContentsMargins(16, 16, 16, 16)
editor = QPlainTextEdit(text)
editor.setObjectName("LogView")
editor.setReadOnly(True)
editor.setLineWrapMode(QPlainTextEdit.NoWrap)
layout.addWidget(editor)
buttons = QHBoxLayout()
buttons.addStretch(1)
from PySide6.QtGui import QGuiApplication
buttons.addWidget(button("Kopieren", "copy", on_click=lambda: QGuiApplication.clipboard().setText(text)))
buttons.addWidget(button("Schließen", variant="primary", on_click=self.accept))
layout.addLayout(buttons)
def message(parent, title, text, kind="info", details=None, buttons=("OK",), default=0):
"""Consistent modal message. Returns the index of the clicked button or -1."""
dialog = QDialog(parent)
dialog.setWindowTitle(title)
dialog.setMinimumWidth(460)
dialog.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum)
layout = QVBoxLayout(dialog)
layout.setContentsMargins(22, 20, 22, 18)
layout.setSpacing(14)
row = QHBoxLayout()
row.setSpacing(14)
icon_label = QLabel()
token = {"info": "accent", "warning": "warning", "error": "danger", "success": "success", "question": "accent"}[kind]
name = {"question": "info"}.get(kind, kind)
icon_label.setPixmap(icon(name, theme.color(token)).pixmap(28, 28))
row.addWidget(icon_label, 0, Qt.AlignTop)
texts = QVBoxLayout()
texts.setSpacing(6)
texts.addWidget(label(title, object_name="CardTitle"))
body = label(text, wrap=True, selectable=True)
body.setMaximumWidth(560)
texts.addWidget(body)
row.addLayout(texts, 1)
layout.addLayout(row)
if details:
detail_view = QPlainTextEdit(details)
detail_view.setObjectName("LogView")
detail_view.setReadOnly(True)
detail_view.setMinimumHeight(140)
detail_view.setMaximumHeight(260)
layout.addWidget(detail_view)
box = QHBoxLayout()
box.addStretch(1)
result = {"index": -1}
for index, text_value in enumerate(buttons):
variant = None
if index == default:
variant = "danger" if kind == "warning" and len(buttons) > 1 else "primary"
widget = button(text_value, variant=variant)
widget.clicked.connect(lambda _checked=False, i=index: (result.update(index=i), dialog.accept()))
if index == default:
widget.setDefault(True)
box.addWidget(widget)
layout.addLayout(box)
dialog.exec()
return result["index"]
def confirm(parent, title, text, ok_text="OK", cancel_text="Abbrechen", destructive=False, details=None):
kind = "warning" if destructive else "question"
index = message(parent, title, text, kind, details, buttons=(cancel_text, ok_text), default=1)
return index == 1
def error(parent, title, text, details=None):
message(parent, title, text, "error", details)
def form_dialog_buttons(dialog, ok_text="Speichern"):
box = QDialogButtonBox()
cancel = button("Abbrechen", on_click=dialog.reject)
ok = button(ok_text, variant="primary", on_click=dialog.accept)
ok.setDefault(True)
box.addButton(cancel, QDialogButtonBox.RejectRole)
box.addButton(ok, QDialogButtonBox.AcceptRole)
return box, ok
def checkbox(text, checked=False, tooltip=None):
widget = QCheckBox(text)
widget.setChecked(checked)
widget.setCursor(Qt.PointingHandCursor)
if tooltip:
widget.setToolTip(tooltip)
return widget
-170
View File
@@ -1,170 +0,0 @@
import base64
import ctypes
import json
import os
import sys
from ctypes import wintypes
from pathlib import Path
APP_NAME = "NetBox VM Import"
SECRET_KEYS = ("password", "token_secret")
def config_path():
if sys.platform == "win32":
base = Path(os.environ.get("APPDATA", Path.home()))
else:
base = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
return base / APP_NAME / "config.json"
class _DataBlob(ctypes.Structure):
_fields_ = [("cbData", wintypes.DWORD), ("pbData", ctypes.POINTER(ctypes.c_byte))]
def _blob(data):
buffer = ctypes.create_string_buffer(data)
return _DataBlob(len(data), ctypes.cast(buffer, ctypes.POINTER(ctypes.c_byte))), buffer
def protect(value):
"""Encrypt a value for the current Windows user with DPAPI."""
if not value:
return ""
if sys.platform != "win32":
raise RuntimeError("Verschlüsselte Profile werden derzeit nur unter Windows unterstützt.")
source, source_buffer = _blob(value.encode("utf-8"))
result = _DataBlob()
if not ctypes.windll.crypt32.CryptProtectData(
ctypes.byref(source), APP_NAME, None, None, None, 0, ctypes.byref(result)
):
raise ctypes.WinError()
try:
return base64.b64encode(ctypes.string_at(result.pbData, result.cbData)).decode("ascii")
finally:
ctypes.windll.kernel32.LocalFree(result.pbData)
def unprotect(value):
"""Decrypt a DPAPI value for the current Windows user."""
if not value:
return ""
source, source_buffer = _blob(base64.b64decode(value))
result = _DataBlob()
if not ctypes.windll.crypt32.CryptUnprotectData(
ctypes.byref(source), None, None, None, None, 0, ctypes.byref(result)
):
raise ctypes.WinError()
try:
return ctypes.string_at(result.pbData, result.cbData).decode("utf-8")
finally:
ctypes.windll.kernel32.LocalFree(result.pbData)
class ProfileStore:
def __init__(self, path=None):
self.path = Path(path) if path else config_path()
def load(self):
if not self.path.exists():
return {}, ""
with self.path.open("r", encoding="utf-8") as stream:
data = json.load(stream)
profiles = {}
for record in data.get("profiles", []):
name = record.get("name", "").strip()
if not name:
continue
profile = {
"name": name,
"netbox_url": record.get("netbox_url", ""),
"netbox_token": unprotect(record.get("netbox_token_encrypted", "")),
"netbox_ignore_ssl": bool(record.get("netbox_ignore_ssl", record.get("ignore_ssl_errors", False))),
"sources": [],
"switches": [],
}
for source_record in record.get("sources", []):
source = dict(source_record)
for key in SECRET_KEYS:
encrypted_key = f"{key}_encrypted"
if encrypted_key in source:
source[key] = unprotect(source.pop(encrypted_key))
profile["sources"].append(source)
for switch_record in record.get("switches", []):
switch = dict(switch_record)
for key in SECRET_KEYS:
encrypted_key = f"{key}_encrypted"
if encrypted_key in switch:
switch[key] = unprotect(switch.pop(encrypted_key))
profile["switches"].append(switch)
# Migration from v2: one VMware source embedded in each profile.
if not profile["sources"] and record.get("esxi_host"):
profile["sources"].append({
"id": "vmware-legacy",
"type": "vmware",
"name": "VMware",
"enabled": True,
"host": record.get("esxi_host", ""),
"username": record.get("esxi_user", ""),
"password": unprotect(record.get("esxi_password_encrypted", "")),
"ignore_ssl": bool(record.get("ignore_ssl_errors", False)),
})
profiles[name] = profile
# Migration from the first plaintext single-profile format.
if not profiles and any(key in data for key in ("esxi_host", "netbox_url")):
profiles["Standard"] = {
"name": "Standard",
"netbox_url": data.get("netbox_url", ""),
"netbox_token": data.get("netbox_token", ""),
"netbox_ignore_ssl": bool(data.get("ignore_ssl_errors", False)),
"sources": [{
"id": "vmware-legacy",
"type": "vmware",
"name": "VMware",
"enabled": True,
"host": data.get("esxi_host", ""),
"username": data.get("esxi_user", ""),
"password": data.get("esxi_password", ""),
"ignore_ssl": bool(data.get("ignore_ssl_errors", False)),
}],
"switches": [],
}
return profiles, data.get("active_profile", "")
def save(self, profiles, active_profile):
records = []
for name in sorted(profiles, key=str.casefold):
profile = profiles[name]
sources = []
for source_data in profile.get("sources", []):
source = {key: value for key, value in source_data.items() if key not in SECRET_KEYS}
for key in SECRET_KEYS:
if key in source_data:
source[f"{key}_encrypted"] = protect(source_data.get(key, ""))
sources.append(source)
switches = []
for switch_data in profile.get("switches", []):
switch = {key: value for key, value in switch_data.items() if key not in SECRET_KEYS}
for key in SECRET_KEYS:
if key in switch_data:
switch[f"{key}_encrypted"] = protect(switch_data.get(key, ""))
switches.append(switch)
records.append({
"name": name,
"netbox_url": profile.get("netbox_url", ""),
"netbox_token_encrypted": protect(profile.get("netbox_token", "")),
"netbox_ignore_ssl": bool(profile.get("netbox_ignore_ssl", False)),
"sources": sources,
"switches": switches,
})
payload = {"version": 4, "active_profile": active_profile, "profiles": records}
self.path.parent.mkdir(parents=True, exist_ok=True)
temp_path = self.path.with_suffix(".tmp")
with temp_path.open("w", encoding="utf-8") as stream:
json.dump(payload, stream, indent=2, ensure_ascii=False)
temp_path.replace(self.path)
+3
View File
@@ -0,0 +1,3 @@
-r requirements.txt
pyinstaller>=6.10
pytest>=8.0
+5 -5
View File
@@ -1,5 +1,5 @@
pyvmomi
pynetbox
requests
paramiko
pyinstaller
PySide6-Essentials>=6.7
pynetbox>=7.4
pyvmomi>=8.0
requests>=2.31
paramiko>=3.4
-597
View File
@@ -1,597 +0,0 @@
"""SSH discovery and NetBox synchronization for HPE and Aruba switches."""
import ipaddress
import re
import time
import paramiko
PLATFORMS = {
"aruba_cx": "Aruba CX",
"aruba_aos": "ArubaOS-Switch / ProCurve",
"hpe_comware": "HPE Comware",
}
COMMANDS = {
"aruba_cx": ("no page", "show interface brief", "show lldp neighbor-info detail"),
"aruba_aos": ("no page", "show interfaces brief", "show lldp info remote-device detail"),
"hpe_comware": ("screen-length disable", "display interface brief", "display lldp neighbor-information verbose"),
}
IP_COMMANDS = {
"aruba_cx": ("show ip interface brief", "show ipv6 interface brief"),
"aruba_aos": ("show ip", "show ipv6"),
"hpe_comware": ("display ip interface brief", "display ipv6 interface brief"),
}
LLDP_CONTROL = {
"aruba_cx": {
"status": "show lldp configuration",
"disabled": r"LLDP Enabled\s*:\s*No",
"enable": ("configure terminal", "lldp", "end"),
},
"aruba_aos": {
"status": "show lldp config",
"disabled": r"LLDP (?:Enabled|Run)\s*:\s*(?:No|False)|LLDP operation.*disabled",
"enable": ("configure terminal", "lldp run", "exit"),
},
"hpe_comware": {
"status": "display lldp status",
"disabled": r"Global status of LLDP\s*:\s*Disable",
"enable": ("system-view", "lldp global enable", "return"),
},
}
ANSI_ESCAPE = re.compile(
r"\x1b(?:\][^\x07]*(?:\x07|\x1b\\)|\[[0-?]*[ -/]*[@-~]|[@-_]|[=>])"
)
TERMINAL_CONTROL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
MAC_PATTERN = re.compile(r"(?i)\b(?:[0-9a-f]{2}[:-]){5}[0-9a-f]{2}\b|\b[0-9a-f]{4}(?:-[0-9a-f]{4}){2}\b")
CLI_PROMPT = re.compile(r"(?:^|\n)[^\r\n]*[>#][ \t]*(?:\n)?\Z")
def _clean_output(value):
value = ANSI_ESCAPE.sub("", value).replace("\r", "")
value = TERMINAL_CONTROL.sub("", value)
value = re.sub(r"--\s*MORE\s*--|Press any key to continue.*", "", value, flags=re.I)
return value
def _read_available(channel, timeout=20, initialize_session=False):
chunks = []
started = time.monotonic()
next_nudge = started + 0.5
nudges = 0
while time.monotonic() - started < timeout:
if channel.recv_ready():
chunks.append(channel.recv(65535).decode("utf-8", errors="replace"))
# Interactive AOS-CX/AOS-S/Comware commands are complete when the
# device prompt returns. This avoids truncating output at a short
# pause while also avoiding a fixed delay after every command.
current = _clean_output("".join(chunks))
if CLI_PROMPT.search(current):
break
now = time.monotonic()
if initialize_session and nudges < 3 and now >= next_nudge:
# ArubaOS-S may stop at the login/registration banner until a key
# is pressed. Some WC releases need Enter two or three times.
channel.send("\r")
nudges += 1
next_nudge = now + 1.5
time.sleep(0.05)
output = _clean_output("".join(chunks))
if not CLI_PROMPT.search(output):
tail = " | ".join(line.strip() for line in output.splitlines()[-3:] if line.strip())
detail = f" Letzte Ausgabe: {tail[-300:]}" if tail else " Keine Ausgabe vom Switch empfangen."
raise TimeoutError(
"Der Switch hat die CLI-Ausgabe nicht mit einem vollständigen Prompt abgeschlossen." + detail
)
return output
def _run_cli_command(channel, command, timeout=20):
channel.send(command + "\n")
try:
return _read_available(channel, timeout=timeout)
except TimeoutError as error:
raise TimeoutError(f"CLI-Befehl nicht vollständig abgeschlossen: {command}. {error}") from error
def run_switch_commands(config):
platform = config["platform"]
if platform not in COMMANDS:
raise ValueError(f"Nicht unterstützte Switch-Plattform: {platform}")
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(
hostname=config["host"],
port=int(config.get("port", 22)),
username=config["username"],
password=config["password"],
look_for_keys=False,
allow_agent=False,
timeout=12,
auth_timeout=12,
banner_timeout=12,
)
channel = client.invoke_shell(width=240, height=1000)
try:
_read_available(channel, timeout=45, initialize_session=True)
except TimeoutError as error:
raise TimeoutError(
f"SSH-Anmeldung nicht mit einem vollständigen CLI-Prompt abgeschlossen. {error}"
) from error
pager_command, interface_command, neighbor_command = COMMANDS[platform]
_run_cli_command(channel, pager_command)
control = LLDP_CONTROL[platform]
lldp_status = _run_cli_command(channel, control["status"])
lldp_enabled_automatically = bool(re.search(control["disabled"], lldp_status, flags=re.I))
if lldp_enabled_automatically:
enable_output = []
for command in control["enable"]:
enable_output.append(_run_cli_command(channel, command))
combined = "\n".join(enable_output)
if platform == "hpe_comware" and re.search(r"(?i)unrecognized|invalid|wrong parameter", combined):
_run_cli_command(channel, "system-view")
combined = _run_cli_command(channel, "lldp enable")
combined += "\n" + _run_cli_command(channel, "return")
if re.search(r"(?i)permission denied|authorization failed|access denied", combined):
raise PermissionError("LLDP konnte mangels Konfigurationsrechten nicht aktiviert werden.")
if re.search(r"(?i)unrecognized|invalid input|unknown command|wrong parameter", combined):
raise RuntimeError("Der LLDP-Aktivierungsbefehl wird von diesem Switch nicht unterstützt.")
time.sleep(2)
interfaces = _run_cli_command(channel, interface_command, timeout=45)
ip_outputs = []
for command in IP_COMMANDS[platform]:
ip_outputs.append(_run_cli_command(channel, command, timeout=35))
neighbors = _run_cli_command(channel, neighbor_command, timeout=60)
if platform == "aruba_cx" and re.search(r"(?i)invalid input|unknown command|unrecognized", neighbors):
neighbors = _run_cli_command(channel, "show lldp neighbor-info", timeout=60)
cdp_neighbors = ""
if platform == "aruba_cx":
cdp_summary = _run_cli_command(channel, "show cdp neighbor-info", timeout=35)
cdp_ports = []
for line in cdp_summary.splitlines():
match = re.match(r"^\s*(\d+/\d+/\d+)\s+\S+", line)
if match and match.group(1) not in cdp_ports:
cdp_ports.append(match.group(1))
details = []
for port in cdp_ports:
details.append(_run_cli_command(channel, f"show cdp neighbor-info {port}", timeout=30))
cdp_neighbors = "\n".join([cdp_summary, *details])
return {
"interfaces": interfaces,
"ipv4_interfaces": ip_outputs[0],
"ipv6_interfaces": ip_outputs[1],
"neighbors": neighbors,
"cdp_neighbors": cdp_neighbors,
"lldp_enabled_automatically": lldp_enabled_automatically,
}
finally:
client.close()
def _normalize_mac(value):
if not value:
return None
compact = re.sub(r"[^0-9a-fA-F]", "", value).upper()
if len(compact) != 12:
return None
return ":".join(compact[index:index + 2] for index in range(0, 12, 2))
def _speed_mbps(line):
matches = re.findall(
r"(?i)\b(\d+(?:\.\d+)?)\s*(T|G|M)(?:b(?:it)?|bps)?(?:T|X|SR|LR|CR)?\b",
line,
)
if not matches:
duplex = re.search(r"(?i)\b(\d+)(?:FDx|HDx)\b", line)
if duplex:
return int(duplex.group(1))
trailing = re.search(r"\b(\d{2,6})\s*$", line)
return int(trailing.group(1)) if trailing else None
value, unit = matches[-1]
factor = {"M": 1, "G": 1000, "T": 1_000_000}[unit.upper()]
return int(float(value) * factor)
def _interface_name(token):
token = token.strip(" |:")
return bool(re.match(
r"(?i)^(?:\d+(?:/\d+){0,3}|(?:GE|XGE|HGE|FGE|FortyGigE|Ten-GigabitEthernet|GigabitEthernet)\S+|"
r"Bridge-Aggregation\d+|Trk\d+|lag\d+|Vlan-interface\d+|vlan\s*\d+|loopback\s*\d*|lo\d+|mgmt)$",
token,
))
def parse_interfaces(output, platform):
interfaces = []
seen = set()
for raw_line in _clean_output(output).splitlines():
line = raw_line.strip()
if not line or set(line) <= {"-", "=", " "}:
continue
tokens = re.split(r"\s+", line.replace("|", " | ").strip())
name_index = next((index for index, token in enumerate(tokens[:3]) if _interface_name(token)), None)
if name_index is None:
continue
name = tokens[name_index].strip(" |:")
if name in seen:
continue
lower = line.lower()
if not re.search(r"\b(up|down|administratively down|disabled|enabled)\b", lower):
continue
enabled = not bool(re.search(r"administratively down|admin.*down|disabled|\bno\s+(?:up|down)\b", lower))
connected = bool(re.search(r"\bup\b", lower)) and not bool(re.search(r"\bdown\b", lower))
mac_match = MAC_PATTERN.search(line)
description = ""
if platform == "aruba_aos" and "|" in raw_line:
columns = [column.strip() for column in raw_line.split("|")]
if len(columns) > 1:
description = columns[1]
interfaces.append({
"name": name,
"enabled": enabled,
"connected": connected,
"speed_mbps": _speed_mbps(line),
"mac_address": _normalize_mac(mac_match.group(0)) if mac_match else None,
"description": description,
"neighbor": None,
"ip_addresses": [],
"virtual": False,
})
seen.add(name)
return interfaces
def _address_with_mask(address, mask=None):
try:
if "/" in address:
return str(ipaddress.ip_interface(address))
if mask:
return str(ipaddress.ip_interface(f"{address}/{mask}"))
except ValueError:
return None
return None
def parse_interface_ips(ipv4_output, ipv6_output, platform):
entries = []
if platform == "aruba_aos":
current_interface = ""
for line in _clean_output(ipv4_output).splitlines():
if "|" not in line:
continue
interface_column, values = line.split("|", 1)
candidate = interface_column.strip()
if candidate and not re.search(r"(?i)^VLAN$", candidate) and not set(candidate) <= {"-", "+", " "}:
current_interface = candidate
addresses = re.findall(r"\b\d{1,3}(?:\.\d{1,3}){3}\b", values)
if current_interface and len(addresses) >= 2:
address = _address_with_mask(addresses[0], addresses[1])
if address and not address.startswith("0.0.0.0/"):
entries.append({"interface": current_interface, "address": address})
current_interface = ""
for line in _clean_output(ipv6_output).splitlines():
vlan_match = re.match(r"^\s*Vlan Name\s*:\s*(.+)$", line, flags=re.I)
if vlan_match:
current_interface = vlan_match.group(1).strip()
address_match = re.search(r"([0-9a-fA-F:]+/\d{1,3})", line)
if address_match and current_interface:
address = _address_with_mask(address_match.group(1))
if address and not address.lower().startswith("fe80:"):
entries.append({"interface": current_interface, "address": address})
else:
for output, version in ((ipv4_output, 4), (ipv6_output, 6)):
for line in _clean_output(output).splitlines():
tokens = re.split(r"\s+", line.strip())
if len(tokens) < 2 or not _interface_name(tokens[0]):
continue
patterns = (
r"\b(\d+(?:\.\d+){3}/\d{1,2})\b"
if version == 4 else
r"\b([0-9a-fA-F]*:[0-9a-fA-F:]+/\d{1,3})\b"
)
match = re.search(patterns, line)
if not match:
continue
address = _address_with_mask(match.group(1))
if not address or address.startswith("0.0.0.0/") or address.lower().startswith("fe80:"):
continue
entries.append({"interface": tokens[0], "address": address})
unique = {}
for entry in entries:
unique[(entry["interface"].casefold(), entry["address"])] = entry
return list(unique.values())
def _interface_key(value):
value = value.casefold().replace("_", "").replace("-", "").replace(" ", "")
value = value.replace("vlaninterface", "vlan")
return value
def _field(block, patterns):
for pattern in patterns:
match = re.search(pattern, block, flags=re.I | re.M)
if match:
return match.group(1).strip()
return ""
def parse_neighbors(output):
clean = _clean_output(output)
starts = list(re.finditer(
r"(?im)^(?:\s*(?:Port|Local (?:Port|Interface|Intf)|LLDP neighbor-information of port)\s*[: ]\s*.+)$",
clean,
))
if not starts:
return _parse_neighbor_table(clean)
neighbors = []
for index, start in enumerate(starts):
end = starts[index + 1].start() if index + 1 < len(starts) else len(clean)
block = clean[start.start():end]
local_port = _field(block, (
r"^\s*Port\s*:\s*(\S+)",
r"^\s*Local (?:Port|Interface|Intf)\s*[: ]\s*(\S+)",
r"^\s*LLDP neighbor-information of port\s+(?:\d+\[)?([^\]\s:]+)\]?",
))
system_name = _field(block, (
r"^\s*Neighbor Chassis-Name\s*:\s*(.+)$",
r"^[ \t]*Neighbor System-Name[ \t]*:[ \t]*(.*)$",
r"^[ \t]*(?:System Name|SysName)[ \t]*:[ \t]*(.*)$",
r"^\s*Neighbor name\s*[: ]\s*(.+)$",
))
if not system_name:
system_name = _field(block, (
r"^[ \t]*Neighbor Chassis-ID[ \t]*:[ \t]*(.+)$",
r"^[ \t]*ChassisId[ \t]*:[ \t]*(.+)$",
))
remote_port = _field(block, (
r"^\s*Neighbor Port-ID\s*:\s*(.+)$",
r"^\s*Neighbor Port-Desc\s*:\s*(.+)$",
r"^[ \t]*(?:Port ID|PortId)[ \t]*:[ \t]*(.*)$",
r"^\s*Port ID subtype.*\n\s*Port ID\s*[: ]\s*(.+)$",
r"^\s*(?:Port Description|PortDesc)\s*[: ]\s*(.+)$",
))
management_ip = _field(block, (
r"^\s*Neighbor Management-Address\s*:\s*([0-9a-fA-F:.]+)",
r"^\s*(?:Management Address|Management address|Management IP)\s*[: ]\s*([0-9a-fA-F:.]+)",
r"^[ \t]*Address[ \t]*:[ \t]*([0-9a-fA-F:.]+)[ \t]*$",
))
if local_port and (system_name or remote_port):
neighbors.append({
"local_port": local_port,
"system_name": system_name,
"remote_port": remote_port,
"management_ip": management_ip,
})
return neighbors
def parse_cdp_neighbors(output):
"""Parse detailed AOS-CX CDP records into the common neighbor shape."""
clean = _clean_output(output)
starts = list(re.finditer(r"(?im)^\s*Local Port\s*:\s*\S+", clean))
neighbors = []
for index, start in enumerate(starts):
end = starts[index + 1].start() if index + 1 < len(starts) else len(clean)
block = clean[start.start():end]
local_port = _field(block, (r"^\s*Local Port\s*:\s*(\S+)",))
system_name = _field(block, (
r"^\s*Device ID\s*:\s*(.+)$",
r"^\s*System Name\s*:\s*(.+)$",
))
remote_port = _field(block, (
r"^\s*Neighbor Port-ID\s*:\s*(.+)$",
r"^\s*Port ID\s*:\s*(.+)$",
))
management_ip = _field(block, (
r"^\s*Address\s*:\s*([0-9a-fA-F:.]+)",
r"^\s*Management Address\s*:\s*([0-9a-fA-F:.]+)",
))
if local_port and (system_name or remote_port or management_ip):
neighbors.append({
"local_port": local_port,
"system_name": system_name,
"remote_port": remote_port,
"management_ip": management_ip,
})
return neighbors
def _parse_neighbor_table(output):
neighbors = []
for raw_line in output.splitlines():
line = raw_line.strip()
if not line or set(line) <= {"-", "=", " "}:
continue
tokens = re.split(r"\s+", line.replace("|", " | "))
if not tokens or not _interface_name(tokens[0]):
continue
if "|" in tokens:
separator = tokens.index("|")
remaining = tokens[separator + 1:]
if len(remaining) < 3:
continue
remote_port = remaining[1]
system_name = remaining[-1]
else:
if len(tokens) < 5:
continue
remote_port = tokens[2]
system_name = tokens[-1]
neighbors.append({
"local_port": tokens[0],
"system_name": system_name,
"remote_port": remote_port,
"management_ip": "",
})
return neighbors
def discover_switch(config):
outputs = run_switch_commands(config)
interfaces = parse_interfaces(outputs["interfaces"], config["platform"])
interface_ips = parse_interface_ips(
outputs.get("ipv4_interfaces", ""),
outputs.get("ipv6_interfaces", ""),
config["platform"],
)
lldp_neighbors = parse_neighbors(outputs["neighbors"])
cdp_neighbors = parse_cdp_neighbors(outputs.get("cdp_neighbors", ""))
# LLDP normally contains richer data. CDP fills ports for which CX did not
# return an LLDP record, without duplicating a physical local interface.
neighbors = list(lldp_neighbors)
occupied_ports = {_interface_key(item["local_port"]) for item in neighbors}
for neighbor in cdp_neighbors:
key = _interface_key(neighbor["local_port"])
if key not in occupied_ports:
neighbors.append(neighbor)
occupied_ports.add(key)
interface_map = {_interface_key(interface["name"]): interface for interface in interfaces}
for item in interface_ips:
key = _interface_key(item["interface"])
interface = interface_map.get(key)
if not interface:
interface = {
"name": item["interface"],
"enabled": True,
"connected": True,
"speed_mbps": None,
"mac_address": None,
"description": "Logisches Layer-3-Interface",
"neighbor": None,
"ip_addresses": [],
"virtual": True,
}
interfaces.append(interface)
interface_map[key] = interface
interface["ip_addresses"].append(item["address"])
for neighbor in neighbors:
local = interface_map.get(_interface_key(neighbor["local_port"]))
if local:
local["neighbor"] = neighbor
return {
"interfaces": interfaces,
"ip_addresses": interface_ips,
"neighbors": neighbors,
"lldp_neighbors": lldp_neighbors,
"cdp_neighbors": cdp_neighbors,
"raw": outputs,
"lldp_enabled_automatically": outputs.get("lldp_enabled_automatically", False),
}
def _netbox_interface_type(speed_mbps, virtual=False):
if virtual:
return "virtual"
if not speed_mbps:
return "other"
if speed_mbps >= 100_000:
return "100gbase-x-qsfp28"
if speed_mbps >= 40_000:
return "40gbase-x-qsfpp"
if speed_mbps >= 25_000:
return "25gbase-x-sfp28"
if speed_mbps >= 10_000:
return "10gbase-x-sfpp"
if speed_mbps >= 1000:
return "1000base-t"
return "100base-tx"
def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True):
device_id = int(config["device_id"])
interface_records = {}
created = updated = cables = ip_addresses = 0
errors = []
device = nb.dcim.devices.get(id=device_id)
tenant_id = getattr(getattr(device, "tenant", None), "id", None) if device else None
for interface in snapshot["interfaces"]:
payload = {
"device": device_id,
"name": interface["name"],
"type": _netbox_interface_type(interface.get("speed_mbps"), interface.get("virtual", False)),
"enabled": interface.get("enabled", True),
}
if interface.get("description"):
payload["description"] = interface["description"][:200]
if interface.get("mac_address"):
payload["mac_address"] = interface["mac_address"]
try:
record = nb.dcim.interfaces.get(device_id=device_id, name=interface["name"])
if record:
record.update(payload)
updated += 1
else:
record = nb.dcim.interfaces.create(payload)
created += 1
interface_records[interface["name"].casefold()] = record
except Exception as error:
errors.append(f"Interface {interface['name']}: {error}")
for interface in snapshot["interfaces"]:
record = interface_records.get(interface["name"].casefold())
if not record:
continue
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 getattr(getattr(item, "vrf", None), "id", None) is None
]
if len(candidates) > 1:
raise ValueError("mehrere globale IP-Adressen mit diesem Host gefunden")
payload = {
"address": address,
"status": "active",
"assigned_object_type": "dcim.interface",
"assigned_object_id": record.id,
}
if tenant_id:
payload["tenant"] = tenant_id
if candidates:
candidates[0].update(payload)
else:
nb.ipam.ip_addresses.create(payload)
ip_addresses += 1
except Exception as error:
errors.append(f"IP-Adresse {address} auf {interface['name']}: {error}")
if create_cables:
for neighbor in snapshot["neighbors"]:
try:
local = interface_records.get(neighbor["local_port"].casefold())
if not local or getattr(local, "cable", None):
continue
remote_device = nb.dcim.devices.get(name=neighbor["system_name"])
if not remote_device:
continue
remote = nb.dcim.interfaces.get(device_id=remote_device.id, name=neighbor["remote_port"])
if not remote or getattr(remote, "cable", None):
continue
nb.dcim.cables.create({
"a_terminations": [{"object_type": "dcim.interface", "object_id": local.id}],
"b_terminations": [{"object_type": "dcim.interface", "object_id": remote.id}],
"status": "connected",
})
cables += 1
except Exception as error:
errors.append(
f"Nachbar {neighbor.get('local_port')} → {neighbor.get('system_name')} "
f"{neighbor.get('remote_port')}: {error}"
)
return {
"created": created,
"updated": updated,
"ip_addresses": ip_addresses,
"cables": cables,
"errors": errors,
}
+6
View File
@@ -0,0 +1,6 @@
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE.parent))
sys.path.insert(0, str(HERE))
+77
View File
@@ -0,0 +1,77 @@
"""Tiny in-memory stand-in for the parts of pynetbox the sync code uses."""
import itertools
from types import SimpleNamespace
_ids = itertools.count(1000)
class Record(SimpleNamespace):
def __init__(self, endpoint=None, **values):
super().__init__(**values)
self._endpoint = endpoint
def update(self, values):
changed = any(getattr(self, key, None) != value for key, value in values.items())
for key, value in values.items():
setattr(self, key, value)
if changed and self._endpoint is not None:
self._endpoint.updates.append((self.id, dict(values)))
return changed
def _matches(record, key, value):
if key == "brief":
return True
if key.endswith("__ie"):
return str(getattr(record, key[:-4], "")).casefold() == str(value).casefold()
if key == "vrf_id":
vrf = getattr(record, "vrf", None)
vrf_id = vrf if isinstance(vrf, int) else getattr(vrf, "id", None)
return (vrf_id is None) if value == "null" else vrf_id == value
if key == "address":
return str(getattr(record, "address", "")).split("/")[0] == str(value).split("/")[0]
if key.endswith("_id") and not hasattr(record, key):
related = getattr(record, key[:-3], None)
return getattr(related, "id", related) == value
return getattr(record, key, None) == value
class Endpoint:
def __init__(self, records=()):
self.records = []
self.created = []
self.updates = []
for values in records:
self.records.append(Record(self, **values))
def all(self):
return list(self.records)
def filter(self, **kwargs):
return [record for record in self.records if all(_matches(record, k, v) for k, v in kwargs.items())]
def get(self, *args, **kwargs):
if args:
kwargs = {"id": args[0]}
found = self.filter(**kwargs)
if len(found) > 1:
raise ValueError("get() returned more than one result")
return found[0] if found else None
def create(self, payload):
record = Record(self, id=next(_ids), cable=None, **payload)
self.records.append(record)
self.created.append(payload)
return record
class FakeNetBox:
netbox_version = "4.3.0"
def __init__(self):
self.dcim = SimpleNamespace(devices=Endpoint(), interfaces=Endpoint(), cables=Endpoint(),
mac_addresses=Endpoint(), platforms=Endpoint())
self.ipam = SimpleNamespace(ip_addresses=Endpoint(), prefixes=Endpoint(), vrfs=Endpoint())
self.virtualization = SimpleNamespace(clusters=Endpoint(), virtual_machines=Endpoint(), interfaces=Endpoint())
self.tenancy = SimpleNamespace(tenants=Endpoint())
+59
View File
@@ -0,0 +1,59 @@
import json
import sys
import pytest
from netbox_sync.core.config import DEFAULT_SETTINGS, ProfileStore
pytestmark = pytest.mark.skipif(sys.platform != "win32", reason="DPAPI is Windows-only")
def test_roundtrip_encrypts_secrets(tmp_path):
store = ProfileStore(tmp_path / "config.json")
profiles = {
"Kunde A": {
"name": "Kunde A",
"netbox_url": "https://netbox.example",
"netbox_token": "token-123",
"netbox_ignore_ssl": True,
"sources": [{"id": "s1", "type": "proxmox", "name": "PVE", "url": "https://pve", "token_id": "a@pve!b",
"token_secret": "geheim", "enabled": True}],
"switches": [{"id": "w1", "name": "sw1", "device_id": 5, "platform": "auto", "host": "10.0.0.1",
"port": 22, "username": "admin", "password": "pw", "enabled": True, "_runtime": "x"}],
}
}
settings = dict(DEFAULT_SETTINGS, theme="dark")
store.save(profiles, "Kunde A", settings)
raw = (tmp_path / "config.json").read_text(encoding="utf-8")
assert "token-123" not in raw and "geheim" not in raw and '"pw"' not in raw
assert "_runtime" not in raw
loaded, active, loaded_settings = store.load()
assert active == "Kunde A"
assert loaded_settings["theme"] == "dark"
assert loaded["Kunde A"]["netbox_token"] == "token-123"
assert loaded["Kunde A"]["sources"][0]["token_secret"] == "geheim"
assert loaded["Kunde A"]["switches"][0]["password"] == "pw"
def test_unreadable_secret_does_not_block_loading(tmp_path):
path = tmp_path / "config.json"
path.write_text(json.dumps({
"version": 4,
"active_profile": "X",
"profiles": [{"name": "X", "netbox_url": "u", "netbox_token_encrypted": "AAAA", "sources": [], "switches": []}],
}), encoding="utf-8")
store = ProfileStore(path)
profiles, _active, settings = store.load()
assert profiles["X"]["netbox_token"] == ""
assert store.decrypt_failures
assert settings == DEFAULT_SETTINGS
def test_legacy_v1_migration(tmp_path):
path = tmp_path / "config.json"
path.write_text(json.dumps({"esxi_host": "vc", "esxi_user": "u", "esxi_password": "p", "netbox_url": "nb"}),
encoding="utf-8")
profiles, _active, _settings = ProfileStore(path).load()
assert profiles["Standard"]["sources"][0]["host"] == "vc"
+54
View File
@@ -0,0 +1,54 @@
from types import SimpleNamespace
from fake_netbox import FakeNetBox, Record
from netbox_sync.core.switches import build_snapshot, sync_snapshot_to_netbox
from test_switches import COMWARE_BRIEF, COMWARE_LLDP
def _setup():
nb = FakeNetBox()
tenant = SimpleNamespace(id=7, name="Muster")
nb.dcim.devices.records += [
Record(nb.dcim.devices, id=1, name="access-01", tenant=tenant),
Record(nb.dcim.devices, id=2, name="core-sw", tenant=None),
]
# Interfaces created from the NetBox device type use full Comware names.
for index, name in enumerate(("GigabitEthernet1/0/1", "GigabitEthernet1/0/2"), start=1):
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=index, name=name, device=SimpleNamespace(id=1),
type=SimpleNamespace(value="1000base-x-sfp"), enabled=True, cable=None))
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=50, name="GigabitEthernet1/0/24",
device=SimpleNamespace(id=2), enabled=True, cable=None))
snapshot = build_snapshot({"interfaces": COMWARE_BRIEF, "neighbors": COMWARE_LLDP}, "hpe_comware")
switch = {"id": "s", "name": "access-01", "device_id": 1}
return nb, switch, snapshot
def test_dry_run_writes_nothing():
nb, switch, snapshot = _setup()
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=True, dry_run=True)
assert report["errors"] == []
assert report["interfaces_created"] == 1 # Ten-GigabitEthernet1/0/49
assert report["interfaces_updated"] == 1 # GE1/0/2 is ADM -> disable
assert report["interfaces_unchanged"] == 1
assert report["cables_created"] == 1 # FQDN "core-sw.example.local" -> core-sw
assert nb.dcim.interfaces.created == [] and nb.dcim.interfaces.updates == [] and nb.dcim.cables.created == []
def test_sync_matches_short_names_and_keeps_existing_types():
nb, switch, snapshot = _setup()
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=True)
assert report["errors"] == []
names = [payload["name"] for payload in nb.dcim.interfaces.created]
assert names == ["Ten-GigabitEthernet1/0/49"], "no GE1/0/x duplicates next to template interfaces"
assert nb.dcim.interfaces.created[0]["type"] == "10gbase-x-sfpp"
# Only the admin state changed – the template type must not be overwritten.
assert nb.dcim.interfaces.updates == [(2, {"enabled": False})]
cable = nb.dcim.cables.created[0]
assert cable["a_terminations"][0]["object_id"] == 1
assert cable["b_terminations"][0]["object_id"] == 50
# A second run finds nothing left to do.
nb.dcim.interfaces.get(1).cable = True
again = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=True, dry_run=True)
assert again["changes"] == []
+203
View File
@@ -0,0 +1,203 @@
from netbox_sync.core import switches
from netbox_sync.core.switches import (
CLI_PROMPT,
COMWARE_PROMPT,
build_snapshot,
interface_key,
netbox_interface_type,
parse_interface_ips,
parse_interfaces,
parse_neighbors,
suggest_platform,
)
AOS_BRIEF = """
Status and Counters - Port Status
| Intrusion Flow Bcast
Port Type | Alert Enabled Status Mode Ctrl Limit
------------ ---------- + --------- ------- ------ ---------- ----- ------
1 100/1000T | No Yes Up 1000FDx off 0
2 100/1000T | No No Down 1000FDx off 0
49 SFP+SR | No Yes Up 10GigFD off 0
Trk1 | No Yes Up 1000FDx off 0
switch#
"""
CX_BRIEF = """
--------------------------------------------------------------------------------------------------------
Port Native Mode Type Enabled Status Reason Speed Description
VLAN (Mb/s)
--------------------------------------------------------------------------------------------------------
1/1/1 1 access 1GbT yes up 1000 Uplink
1/1/2 1 access 1GbT no down Administratively down -- --
1/1/49 -- routed SFP+DAC1 yes up 10000 --
core-sw#
"""
COMWARE_BRIEF = """
Brief information on interfaces in bridge mode:
Link: ADM - administratively down; Stby - standby
Speed: (a) - auto
Duplex: (a)/A - auto; H - half; F - full
Type: A - access; T - trunk; H - hybrid
Interface Link Speed Duplex Type PVID Description
GE1/0/1 UP 1G(a) F(a) A 1
GE1/0/2 ADM auto A A 1
XGE1/0/49 UP 10G F T 1
<comware>
"""
COMWARE_LLDP = """
LLDP neighbor-information of port 1[GigabitEthernet1/0/1]:
LLDP agent nearest-bridge:
LLDP neighbor index : 1
Update time : 0 days, 0 hours, 1 minutes, 1 seconds
Chassis type : MAC address
Chassis ID : 0011-2233-4455
Port ID type : Interface name
Port ID : GigabitEthernet1/0/24
Time to live : 121
Port description : GigabitEthernet1/0/24 Interface
System name : core-sw.example.local
Management address type : IPv4
Management address : 192.0.2.1
<comware>
"""
CX_LLDP = """
Port : 1/1/1
Neighbor Entries : 1
Neighbor Chassis-Name : access-01
Neighbor Chassis-ID : 00:11:22:33:44:55
Neighbor Port-ID : 1/1/52
Neighbor Port-Desc : 1/1/52
Neighbor Management-Address : 10.0.0.12
Port : 1/1/2
Neighbor Entries : 1
Neighbor Chassis-Name : esx01
Neighbor Port-ID : vmnic0
core-sw#
"""
AOS_LLDP = """
LLDP Remote Device Information Detail
Local Port : 24
ChassisType : mac-address
ChassisId : 00 11 22 33 44 55
PortType : local
PortId : 1/1/1
SysName : core-sw
System Descr : Aruba JL...
PortDescr : 1/1/1
switch#
"""
def test_aos_brief_uses_columns_and_no_garbage_description():
interfaces = {item["name"]: item for item in parse_interfaces(AOS_BRIEF, "aruba_aos")}
assert set(interfaces) == {"1", "2", "49", "Trk1"}
assert interfaces["1"]["enabled"] and interfaces["1"]["connected"]
assert interfaces["1"]["speed_mbps"] == 1000
assert not interfaces["2"]["enabled"] and not interfaces["2"]["connected"]
assert interfaces["49"]["speed_mbps"] == 10000
assert all(item["description"] == "" for item in interfaces.values())
assert netbox_interface_type(interfaces["49"]) == "10gbase-x-sfpp"
assert netbox_interface_type(interfaces["1"]) == "1000base-t"
assert netbox_interface_type(interfaces["Trk1"]) == "lag"
def test_cx_brief():
interfaces = {item["name"]: item for item in parse_interfaces(CX_BRIEF, "aruba_cx")}
assert set(interfaces) == {"1/1/1", "1/1/2", "1/1/49"}
assert interfaces["1/1/1"]["connected"]
assert not interfaces["1/1/2"]["enabled"]
assert netbox_interface_type(interfaces["1/1/49"]) == "10gbase-x-sfpp"
def test_comware_names_are_expanded_and_adm_is_disabled():
interfaces = {item["name"]: item for item in parse_interfaces(COMWARE_BRIEF, "hpe_comware")}
assert set(interfaces) == {"GigabitEthernet1/0/1", "GigabitEthernet1/0/2", "Ten-GigabitEthernet1/0/49"}
assert not interfaces["GigabitEthernet1/0/2"]["enabled"]
assert interfaces["GigabitEthernet1/0/1"]["speed_mbps"] == 1000
def test_interface_key_matches_vendor_spellings():
assert interface_key("GE1/0/1") == interface_key("GigabitEthernet1/0/1") == interface_key("Gi1/0/1")
assert interface_key("XGE1/0/49") == interface_key("Ten-GigabitEthernet1/0/49") == interface_key("Te1/0/49")
assert interface_key("Vlan-interface10") == interface_key("vlan10") == interface_key("Vlan 10")
assert interface_key("1/1/1") == "1/1/1"
assert interface_key("1/1/1") != interface_key("1/1/11")
def test_comware_lldp_neighbor_and_snapshot_link():
neighbors = parse_neighbors(COMWARE_LLDP)
assert neighbors == [{
"local_port": "GigabitEthernet1/0/1",
"system_name": "core-sw.example.local",
"remote_port": "GigabitEthernet1/0/24",
"port_description": "GigabitEthernet1/0/24 Interface",
"management_ip": "192.0.2.1",
"protocol": "LLDP",
}]
snapshot = build_snapshot(
{"interfaces": COMWARE_BRIEF, "neighbors": COMWARE_LLDP, "ipv4_interfaces": "", "ipv6_interfaces": ""},
"hpe_comware",
)
linked = next(item for item in snapshot["interfaces"] if item["name"] == "GigabitEthernet1/0/1")
assert linked["neighbor"]["system_name"] == "core-sw.example.local"
def test_cx_and_aos_lldp_records():
cx = parse_neighbors(CX_LLDP)
assert [(item["local_port"], item["system_name"], item["remote_port"]) for item in cx] == [
("1/1/1", "access-01", "1/1/52"),
("1/1/2", "esx01", "vmnic0"),
]
assert cx[0]["management_ip"] == "10.0.0.12"
aos = parse_neighbors(AOS_LLDP)
assert [(item["local_port"], item["system_name"], item["remote_port"]) for item in aos] == [
("24", "core-sw", "1/1/1"),
]
def test_ip_parsing_creates_virtual_interfaces():
ipv4 = """
Interface IP Address/Mask VRF Status
---------------------------------------------------------
vlan10 10.0.10.1/24 default up
1/1/49 10.255.0.1/31 default up
core-sw#
"""
entries = parse_interface_ips(ipv4, "", "aruba_cx")
assert {"interface": "vlan10", "address": "10.0.10.1/24"} in entries
snapshot = build_snapshot({"interfaces": CX_BRIEF, "neighbors": "", "ipv4_interfaces": ipv4}, "aruba_cx")
vlan = next(item for item in snapshot["interfaces"] if item["name"] == "vlan10")
assert vlan["virtual"] and vlan["ip_addresses"] == ["10.0.10.1/24"]
uplink = next(item for item in snapshot["interfaces"] if item["name"] == "1/1/49")
assert uplink["ip_addresses"] == ["10.255.0.1/31"]
def test_prompts():
assert CLI_PROMPT.search("output\nswitch# ")
assert CLI_PROMPT.search("output\n<comware>")
assert CLI_PROMPT.search("output\n[comware]")
assert not CLI_PROMPT.search("LLDP neighbor-information of port 1[GigabitEthernet1/0/1]:\n")
assert COMWARE_PROMPT.search("banner\n<HPE-5130>")
assert not COMWARE_PROMPT.search("banner\ncx-switch# ")
def test_suggest_platform():
assert suggest_platform("Aruba", "6100 48G CL4 4SFP+") == "aruba_cx"
assert suggest_platform("HPE", "Aruba 2930F-48G") == "aruba_aos"
assert suggest_platform("HPE", "FlexNetwork 5130 24G") == "hpe_comware"
assert suggest_platform("ArubaOS-CX") == "aruba_cx"
assert suggest_platform("Cisco", "C9300") == "auto"
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
+60
View File
@@ -0,0 +1,60 @@
from types import SimpleNamespace
from fake_netbox import FakeNetBox, Record
from netbox_sync.core.vm_sync import VMSyncEngine
def _engine():
nb = FakeNetBox()
nb.virtualization.clusters.records.append(Record(nb.virtualization.clusters, id=1, name="RZ1",
tenant=SimpleNamespace(id=10, name="Muster")))
nb.tenancy.tenants.records.append(Record(nb.tenancy.tenants, id=10, name="Muster"))
nb.ipam.vrfs.records.append(Record(nb.ipam.vrfs, id=5, name="Muster - Prod", rd=None,
tenant=SimpleNamespace(id=10)))
engine = VMSyncEngine(nb)
engine.load_targets()
return nb, engine
VM = {
"name": "web01", "source": "vc", "status": "active", "vcpus": 2, "memory": 4096, "disk": 40960,
"guest_os": "Debian", "kind": "VM",
"interfaces": [{"name": "NIC-0", "mac": "00:50:56:aa:bb:cc", "ips": ["10.20.30.11/24", "fe80::1"]}],
}
def test_load_targets_and_cluster_tenant():
_nb, engine = _engine()
assert engine.clusters == {"RZ1": 1}
assert engine.cluster_tenants["RZ1"]["name"] == "Muster"
assert [vrf.name for vrf in engine.tenant_vrfs(10)] == ["Muster - Prod"]
def test_detect_and_import_creates_prefix_vm_ip_and_mac():
nb, engine = _engine()
missing = engine.detect_missing_networks([VM], tenant_id=10, default_vrf_id=5)
assert [str(item["suggested_network"]) for item in missing] == ["10.20.30.0/24"]
engine.apply_network_plan([{"network": "10.20.30.0/24", "vrf_id": 5, "create_vrf": False, "vrf_name": None}], 10)
assert engine.sync_vm(VM, cluster_id=1, tenant_id=10, vrf_id=5) == "created"
assert nb.ipam.prefixes.created == [{"prefix": "10.20.30.0/24", "status": "active", "tenant": 10, "vrf": 5}]
ip = nb.ipam.ip_addresses.created[0]
assert ip["address"] == "10.20.30.11/24" and ip["vrf"] == 5 and ip["tenant"] == 10
assert nb.dcim.mac_addresses.created[0]["mac_address"] == "00:50:56:AA:BB:CC"
vm = nb.virtualization.virtual_machines.records[0]
assert vm.primary_ip4 == nb.ipam.ip_addresses.records[0].id
# Second run updates instead of duplicating.
assert engine.sync_vm(VM, cluster_id=1, tenant_id=10, vrf_id=5) == "updated"
assert len(nb.virtualization.virtual_machines.records) == 1
assert len(nb.ipam.ip_addresses.records) == 1
def test_global_vrf_import():
nb, engine = _engine()
engine.detect_missing_networks([VM], tenant_id=10, default_vrf_id=None)
engine.apply_network_plan([{"network": "10.20.30.0/24", "vrf_id": None, "create_vrf": False, "vrf_name": None}], 10)
engine.sync_vm(VM, cluster_id=1, tenant_id=10, vrf_id=None)
assert "vrf" not in nb.ipam.prefixes.created[0]
assert nb.ipam.ip_addresses.created[0]["vrf"] is None