Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1942d6ecdf | ||
|
|
b402591cdf | ||
|
|
ba50527ee5 | ||
|
|
8d2bbafc8d | ||
|
|
f400795cb5 | ||
|
|
9ce25d820a | ||
|
|
8f20bcf795 | ||
|
|
1c0a8168ed | ||
|
|
8464895b06 | ||
|
|
e499d854a9 | ||
|
|
3db5e83f0a | ||
|
|
3df4e6a9fc | ||
|
|
f729473b64 | ||
|
|
29d3724a7f | ||
|
|
535a5e9699 | ||
|
|
83787142d3 | ||
|
|
7b5dd4bc9b | ||
|
|
39a29b9230 | ||
|
|
f249c3e1c9 | ||
|
|
22ba46fca3 | ||
|
|
dc39c8f4ec | ||
|
|
28c6654f6b | ||
|
|
799a5aa007 | ||
|
|
d10190b7bc | ||
|
|
c42cedd655 |
No files matched your search
@@ -10,3 +10,4 @@ output/
|
||||
# Lokale Konfigurationen und Zugangsdaten
|
||||
config.json
|
||||
*.tmp
|
||||
.gitea-token
|
||||
+21
-15
@@ -2,10 +2,16 @@
|
||||
# Build: python -m PyInstaller --noconfirm --clean NetBoxSynchronizer.spec
|
||||
# Produces a one-folder build in dist/NetBoxSynchronizer that the Inno Setup
|
||||
# installer (installer/NetBoxSynchronizer.iss) packages.
|
||||
#
|
||||
# Portable: python -m PyInstaller --noconfirm --clean NetBoxSynchronizer.spec -- --portable
|
||||
# Produces a single self-extracting "NetBox VM Import.exe".
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
PORTABLE = "--portable" in sys.argv
|
||||
|
||||
from PyInstaller.utils.win32.versioninfo import (
|
||||
FixedFileInfo,
|
||||
StringFileInfo,
|
||||
@@ -66,12 +72,7 @@ a.datas = [
|
||||
|
||||
pyz = PYZ(a.pure)
|
||||
|
||||
exe = EXE(
|
||||
pyz,
|
||||
a.scripts,
|
||||
[],
|
||||
exclude_binaries=True,
|
||||
name="NetBoxSynchronizer",
|
||||
EXE_OPTIONS = dict(
|
||||
debug=False,
|
||||
bootloader_ignore_signals=False,
|
||||
strip=False,
|
||||
@@ -86,12 +87,17 @@ exe = EXE(
|
||||
version=version_info,
|
||||
)
|
||||
|
||||
coll = COLLECT(
|
||||
exe,
|
||||
a.binaries,
|
||||
a.datas,
|
||||
strip=False,
|
||||
upx=False,
|
||||
upx_exclude=[],
|
||||
name="NetBoxSynchronizer",
|
||||
)
|
||||
if PORTABLE:
|
||||
exe = EXE(pyz, a.scripts, a.binaries, a.datas, [], name="NetBox VM Import", upx_exclude=[],
|
||||
runtime_tmpdir=None, **EXE_OPTIONS)
|
||||
else:
|
||||
exe = EXE(pyz, a.scripts, [], exclude_binaries=True, name="NetBoxSynchronizer", **EXE_OPTIONS)
|
||||
coll = COLLECT(
|
||||
exe,
|
||||
a.binaries,
|
||||
a.datas,
|
||||
strip=False,
|
||||
upx=False,
|
||||
upx_exclude=[],
|
||||
name="NetBoxSynchronizer",
|
||||
)
|
||||
@@ -1,108 +1,210 @@
|
||||
# NetBox Synchronizer
|
||||
|
||||
Windows-Desktopanwendung, die virtuelle Maschinen aus VMware vSphere und Proxmox VE, HPE-/Aruba-Switche
|
||||
sowie Windows-Clients in NetBox dokumentiert.
|
||||
Windows desktop application that documents virtual machines from VMware
|
||||
vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Type** | Desktop application (Python, PySide6) |
|
||||
| **Platform** | Windows |
|
||||
| **Repository** | <https://git.mrblake.cc/MrBlake/NetBox-VM-Import-Desktop> |
|
||||
|
||||
## Features
|
||||
|
||||
### General
|
||||
|
||||
- Customer profiles with NetBox target, virtualisation sources and switch
|
||||
credentials; switch between them in the sidebar
|
||||
- Automatic saving; passwords, tokens and secrets are encrypted with Windows DPAPI
|
||||
- All network access runs in the background — the window stays responsive and
|
||||
operations can be cancelled
|
||||
- Light and dark theme (optionally following Windows)
|
||||
- Log with filter, search and export, plus a rotating log file under
|
||||
`%APPDATA%\NetBox VM Import\logs`
|
||||
- Keyboard shortcuts: `Ctrl+1…8` navigation, `Ctrl+9` settings, `F5` reload/read, `Ctrl+F` search
|
||||
- Updates from the Gitea releases: checked on start (can be switched off in the
|
||||
settings, or run on demand); after confirmation the installed version runs the
|
||||
new setup silently and the portable EXE replaces itself, then the application
|
||||
restarts. A version can be skipped
|
||||
|
||||
### Virtual machines
|
||||
|
||||
- Multiple VMware and Proxmox sources per profile, read in parallel; connection
|
||||
test directly in the dialog
|
||||
- QEMU/KVM VMs and optionally LXC containers; IP addresses via VMware Tools or
|
||||
the QEMU guest agent
|
||||
- Table with search, filters (source, status, "new"/"already in NetBox") and
|
||||
multi-selection
|
||||
- Automatic cluster mapping: each vCenter/ESXi or Proxmox cluster is mapped to
|
||||
the NetBox cluster with the same (or a uniquely similar) name; manual
|
||||
mappings are remembered in the profile, and missing clusters can be created in
|
||||
NetBox directly
|
||||
- Four-step import wizard: **Target** (cluster mapping, tenant preselected from
|
||||
the cluster, VRF or global) → **Networks** (check missing prefixes with size
|
||||
and VRF, create new VRFs directly) → **Review** (summary of all changes) →
|
||||
**Import** (progress, live log, cancel)
|
||||
- VMs are matched uniquely per cluster; existing prefixes are reused
|
||||
- MAC addresses are set correctly on NetBox ≥ 4.2 (separate MAC model)
|
||||
|
||||
### Switches (Aruba CX, ArubaOS-Switch/ProCurve, HPE Comware)
|
||||
|
||||
- Add several NetBox devices in one step — host taken from the primary IP,
|
||||
platform suggested from model/manufacturer
|
||||
- Platform "detect automatically" via SSH
|
||||
- Parallel SSH queries; SSH host keys are stored on first contact and verified
|
||||
afterwards
|
||||
- Interfaces, interface IP addresses and LLDP/CDP neighbours
|
||||
- **Preview before writing**: all changes are computed as a dry run and only
|
||||
sent after confirmation
|
||||
- Interface types from device type templates are left untouched; Comware short
|
||||
names (`GE1/0/1`) are mapped to full NetBox names (`GigabitEthernet1/0/1`)
|
||||
- VLAN membership per port (untagged and tagged, read from the running
|
||||
configuration) is written to the interface **label**, e.g. `10` or `1,20-22`;
|
||||
only VLAN-related lines of the configuration are kept in the raw data
|
||||
- Automatic port mapping when NetBox names differ from the switch (e.g. `5` ↔
|
||||
`1/1/5`): equal name, then equal port number, then natural order
|
||||
- **Mapping review** before the preview: non-obvious port mappings and every
|
||||
LLDP/CDP neighbour can be corrected; a neighbour can be assigned manually to
|
||||
any device of the switch's tenant group. Choices are stored in the profile
|
||||
- Networks and VLANs in the same review: per network the VRF (global, a VRF of
|
||||
the tenant group or a new one) and whether a missing prefix is created. Network
|
||||
decisions are stored per profile like the VLAN decisions; networks whose
|
||||
prefix exists or that were decided before sit in a collapsed, editable section
|
||||
- VLAN mapping: switch VLANs are matched to NetBox VLANs of the switch's tenant
|
||||
group by VID (own tenant, site and similar names decide between several);
|
||||
each VLAN can be mapped manually, skipped or created with a name and a tenant
|
||||
of the tenant group of your choice (pre-filled from the switch configuration
|
||||
and the switch's tenant). VLANs can also be **ignored** on all switches –
|
||||
they are neither created nor assigned and are left out of the labels. VLAN
|
||||
decisions are stored per profile (shared by all its switches); only VLANs
|
||||
that still need a decision are shown, stored and unambiguous ones are in a
|
||||
collapsed section that can be expanded for editing. Mapped VLANs are assigned
|
||||
to the ports (802.1Q mode, untagged/tagged)
|
||||
- Tenant required: a switch without tenant in NetBox is refused; every created
|
||||
IP address, prefix, VRF, VLAN and cable gets the switch's tenant
|
||||
- Stacks are detected (Aruba CX VSF, ArubaOS-Switch stacking/VSF, HPE Comware
|
||||
IRF): every member is assigned to its own NetBox device (suggested from the
|
||||
NetBox virtual chassis positions, stored per switch) and gets its own ports;
|
||||
LAGs and VLAN interfaces stay on the switch's device
|
||||
- Cables from LLDP/CDP, also with FQDN system names or via the management IP
|
||||
- The switch configuration is only changed when "Enable LLDP if needed" is
|
||||
explicitly switched on
|
||||
|
||||
### Sophos access points (CSV from Sophos Central)
|
||||
|
||||
- Loads the access point export of Sophos Central (comma or semicolon, UTF-8 or
|
||||
Windows encoding) and checks it: missing site, duplicate IP, serial number or
|
||||
MAC address
|
||||
- Finds existing APs in NetBox globally by serial number and MAC address and by
|
||||
name within the tenant group; NetBox APs of the tenant group that are missing
|
||||
in the export are listed as "only in NetBox"
|
||||
- Sophos sites are mapped to NetBox sites of the tenant group (suggested by
|
||||
name, stored per profile); the site is optional – APs without one go to a
|
||||
default site, since NetBox requires a site for every device. The tenant is
|
||||
mandatory and can be chosen per Sophos site (default: the site's tenant)
|
||||
- New APs are created with Sophos device type, role, site, serial number,
|
||||
firmware, interface with MAC and IP address (primary IPv4); existing ones get
|
||||
missing serial numbers and tenants, optionally the Sophos name. Tenant comes
|
||||
from the NetBox site, otherwise the selected tenant; devices of other tenants
|
||||
are never changed. Preview before writing
|
||||
|
||||
### Network scanner (read only)
|
||||
|
||||
- Scans IP ranges, networks and host names (`192.0.2.1-254`, `192.0.2.0/24`,
|
||||
up to 4096 addresses) in parallel; "own network" fills in the networks of
|
||||
this computer
|
||||
- Finds hosts by ping (Windows ICMP API, no administrator rights), ARP in the
|
||||
local subnet and TCP ports – hosts that block ping are found as well
|
||||
- Shows name (reverse DNS and NetBIOS, with workgroup/domain), MAC address,
|
||||
open services from a configurable port list and response time
|
||||
- Compares every address with NetBox automatically: NetBox object (device or VM)
|
||||
and DNS name next to each IP, with the state "matches", "name differs", "not
|
||||
in NetBox" or "in NetBox, not reachable"; nothing is written to NetBox
|
||||
- Filters for reachable hosts and deviations; double click or context menu opens
|
||||
HTTP/HTTPS, Remote Desktop, file shares or the IP address in NetBox
|
||||
|
||||
### Windows clients (agentless via WMI/CIM over WinRM)
|
||||
|
||||
- Targets from Active Directory (optional search OU, enabled accounts only,
|
||||
last logon within N days, include/exclude servers) or as a list of host
|
||||
names, IP addresses, networks (`192.0.2.0/24`) and ranges (`192.0.2.10-50`)
|
||||
- Sign-in via the Windows credential dialog (domain account with local admin
|
||||
rights, verified against the domain) or with the current Windows session; the
|
||||
password is kept in memory only
|
||||
- Reads name, manufacturer, model (for Lenovo the model name instead of the
|
||||
machine type), serial number, form factor, operating system with
|
||||
version/build, logged-on user, CPU/RAM and physical network adapters with MAC
|
||||
and IPs
|
||||
- Parallel queries; unreachable clients stay visible with their AD data, errors
|
||||
come with a concrete hint
|
||||
- Import as NetBox devices with site, role and tenant; manufacturers, device
|
||||
types and platforms are created when needed, optionally interfaces, MAC and IP
|
||||
addresses — with a preview before writing
|
||||
- Built-in **setup guide**: group policy (WinRM, service, firewall),
|
||||
permissions, common errors, check commands and a connection test for single
|
||||
clients
|
||||
|
||||
### Offline mode (without NetBox)
|
||||
|
||||
- "Offline mode (without NetBox)" checkbox in the sidebar — global, independent
|
||||
of the customer profile
|
||||
- VMs and switches are read without a NetBox connection; switches can then be
|
||||
added manually by name
|
||||
- Selected VMs, clients or read switches are exported as a JSON file
|
||||
(`*.nbsync.json`) — without passwords, tokens or user names
|
||||
- On a machine with NetBox access, "Load from file …" (VMs, switches and
|
||||
Windows clients pages) loads the file; the import wizard or dry-run preview
|
||||
then runs as usual. Switches are matched by NetBox device ID or name
|
||||
|
||||
### VRFs & networks
|
||||
|
||||
- Create several VRFs or prefixes for one tenant at once
|
||||
|
||||
## Installation
|
||||
|
||||
`NetBoxSynchronizer-Setup-<version>.exe` ausführen. Der Installer
|
||||
Run `NetBoxSynchronizer-Setup-<version>.exe`. The installer
|
||||
|
||||
- installiert standardmäßig **ohne Administratorrechte** für den aktuellen Benutzer
|
||||
(im Assistenten kann „für alle Benutzer“ gewählt werden),
|
||||
- legt einen Startmenü-Eintrag und optional eine Desktop-Verknüpfung an,
|
||||
- aktualisiert eine vorhandene Installation direkt,
|
||||
- fragt bei der Deinstallation, ob Kundenprofile und Protokolle ebenfalls gelöscht werden sollen.
|
||||
- installs for the current user **without administrator rights** by default
|
||||
("for all users" can be selected in the wizard),
|
||||
- creates a Start menu entry and optionally a desktop shortcut,
|
||||
- updates an existing installation in place,
|
||||
- asks on uninstall whether customer profiles and logs should be removed too.
|
||||
|
||||
Bestehende Kundenprofile der Vorgängerversion („NetBox VM Import“) werden automatisch übernommen.
|
||||
Customer profiles of the predecessor ("NetBox VM Import") are migrated
|
||||
automatically.
|
||||
|
||||
## Funktionen
|
||||
|
||||
**Allgemein**
|
||||
- Kundenprofile mit NetBox-Ziel, Virtualisierungsquellen und Switch-Zugängen; Wechsel über die Seitenleiste
|
||||
- Automatisches Speichern; Passwörter, Tokens und Secrets mit Windows DPAPI verschlüsselt
|
||||
- Alle Netzwerkzugriffe laufen im Hintergrund – das Fenster bleibt bedienbar, Vorgänge lassen sich abbrechen
|
||||
- Helles und dunkles Design (folgt auf Wunsch Windows)
|
||||
- Protokoll mit Filter, Suche und Export; zusätzlich rotierende Logdatei unter `%APPDATA%\NetBox VM Import\logs`
|
||||
- Tastenkürzel: `Strg+1…8` Navigation, `F5` neu laden/auslesen, `Strg+F` Suche
|
||||
|
||||
**Virtuelle Maschinen**
|
||||
- Mehrere VMware- und Proxmox-Quellen pro Profil, parallel ausgelesen; Verbindungstest direkt im Dialog
|
||||
- QEMU/KVM-VMs und optional LXC-Container; IP-Adressen über VMware Tools bzw. QEMU Guest Agent
|
||||
- Tabelle mit Suche, Filtern (Quelle, Status, „neu“/„bereits in NetBox“) und Mehrfachauswahl
|
||||
- Automatische Cluster-Zuordnung: Jeder vCenter-/ESXi- bzw. Proxmox-Cluster wird dem gleichnamigen (oder eindeutig
|
||||
ähnlichen) NetBox-Cluster zugeordnet; manuelle Zuordnungen merkt sich das Kundenprofil, fehlende Cluster können
|
||||
direkt in NetBox angelegt werden
|
||||
- Import-Assistent in vier Schritten: **Ziel** (Cluster-Zuordnung, Mandant aus dem Cluster vorausgewählt, VRF oder global)
|
||||
→ **Netzwerke** (fehlende Präfixe mit Größe und VRF prüfen, neue VRFs direkt anlegen)
|
||||
→ **Prüfen** (Zusammenfassung aller Änderungen) → **Import** (Fortschritt, Live-Protokoll, Abbrechen)
|
||||
- VMs werden pro Cluster eindeutig zugeordnet; vorhandene Präfixe werden wiederverwendet
|
||||
- MAC-Adressen werden auch mit NetBox ≥ 4.2 (eigenes MAC-Modell) korrekt gesetzt
|
||||
|
||||
**Switche** (Aruba CX, ArubaOS-Switch/ProCurve, HPE Comware)
|
||||
- Mehrere NetBox-Geräte in einem Schritt hinzufügen – Host aus der primären IP, Plattform aus Modell/Hersteller vorgeschlagen
|
||||
- Plattform „Automatisch erkennen“ per SSH
|
||||
- Parallele SSH-Abfragen; SSH-Hostschlüssel werden beim ersten Kontakt gespeichert und danach geprüft
|
||||
- Schnittstellen, Interface-IP-Adressen sowie LLDP-/CDP-Nachbarn
|
||||
- **Vorschau vor dem Schreiben**: alle Änderungen werden als Dry-Run berechnet und erst nach Bestätigung übertragen
|
||||
- Interface-Typen aus Gerätetyp-Vorlagen bleiben unangetastet; Comware-Kurznamen (`GE1/0/1`) werden den
|
||||
vollständigen NetBox-Namen (`GigabitEthernet1/0/1`) zugeordnet
|
||||
- Kabel aus LLDP/CDP auch bei FQDN-Systemnamen oder über die Management-IP
|
||||
- Die Switch-Konfiguration wird nur verändert, wenn „LLDP bei Bedarf aktivieren“ ausdrücklich eingeschaltet ist
|
||||
|
||||
**Windows-Clients** (agentlos per WMI/CIM über WinRM)
|
||||
- Ziele aus dem Active Directory (optional Such-OU, nur aktivierte Konten, letzte Anmeldung innerhalb von N Tagen,
|
||||
Server ein-/ausschließen) oder als Liste von Hostnamen, IP-Adressen, Netzen (`10.0.10.0/24`) und Bereichen
|
||||
(`10.0.20.10-50`)
|
||||
- Anmeldung über das Windows-Anmeldefenster (Domänenkonto mit lokalen Adminrechten, wird gegen die Domäne geprüft)
|
||||
oder mit der aktuellen Windows-Anmeldung; das Kennwort bleibt nur im Arbeitsspeicher
|
||||
- Liest Name, Hersteller, Modell (bei Lenovo der Modellname statt des Maschinentyps), Seriennummer, Bauform,
|
||||
Betriebssystem mit Version/Build, angemeldeten Benutzer, CPU/RAM sowie physische Netzwerkkarten mit MAC und IPs
|
||||
- Parallele Abfrage; nicht erreichbare Clients bleiben mit den AD-Daten sichtbar, Fehler mit konkretem Hinweis
|
||||
- Übernahme als NetBox-Geräte mit Standort, Rolle und Mandant; Hersteller, Gerätetypen und Plattformen werden bei
|
||||
Bedarf angelegt, optional Schnittstellen, MAC- und IP-Adressen – mit Vorschau vor dem Schreiben
|
||||
- **Einrichtungshilfe** im Programm: Gruppenrichtlinie (WinRM, Dienst, Firewall), Berechtigungen, Fehlerbilder,
|
||||
Prüfbefehle und ein Verbindungstest für einzelne Clients
|
||||
|
||||
**Offline-Modus (ohne NetBox)**
|
||||
- Checkbox „Offline-Modus (ohne NetBox)“ in der Seitenleiste – gilt global, unabhängig vom Kundenprofil
|
||||
- VMs und Switche werden ohne NetBox-Verbindung ausgelesen; Switche lassen sich dann manuell per Name anlegen
|
||||
- Ausgewählte VMs, Clients bzw. ausgelesene Switche werden als JSON-Datei (`*.nbsync.json`) exportiert – ohne Passwörter,
|
||||
Tokens oder Benutzernamen
|
||||
- Auf einem Rechner mit NetBox-Zugang lädt „Aus Datei laden …“ (Seiten VMs, Switche und Windows-Clients) die Datei; danach laufen
|
||||
Import-Assistent bzw. Dry-Run-Vorschau wie gewohnt. Switche werden über NetBox-Geräte-ID oder Namen zugeordnet
|
||||
|
||||
**VRFs & Netze**
|
||||
- Mehrere VRFs oder Präfixe für einen Mandanten gesammelt anlegen
|
||||
|
||||
## Entwicklung
|
||||
## Development
|
||||
|
||||
```powershell
|
||||
py -3 -m venv .venv
|
||||
.\.venv\Scripts\Activate.ps1
|
||||
pip install -r requirements-dev.txt
|
||||
python main.py # Anwendung starten
|
||||
python -m pytest # Tests
|
||||
python main.py # start the application
|
||||
python -m pytest # tests
|
||||
```
|
||||
|
||||
Projektstruktur:
|
||||
Project layout:
|
||||
|
||||
```
|
||||
netbox_sync/
|
||||
core/ UI-unabhängige Logik: Konfiguration, NetBox, VMware/Proxmox, VM-Import, Switche, Windows-Clients
|
||||
ui/ Qt-Oberfläche (PySide6): Hauptfenster, Seiten, Dialoge, Import-Assistent, Theme
|
||||
resources/ Icons
|
||||
installer/ Inno-Setup-Skript
|
||||
tests/ pytest (Parser, Konfiguration, Sync gegen eine In-Memory-NetBox)
|
||||
core/ UI-independent logic: configuration, NetBox, VMware/Proxmox, VM import, switches, Windows clients
|
||||
ui/ Qt interface (PySide6): main window, pages, dialogs, import wizard, theme
|
||||
resources/ icons
|
||||
installer/ Inno Setup script
|
||||
tests/ pytest (parsers, configuration, sync against an in-memory NetBox)
|
||||
```
|
||||
|
||||
## Build & Installer
|
||||
## Build & installer
|
||||
|
||||
Voraussetzung für den Installer ist [Inno Setup 6](https://jrsoftware.org/isinfo.php)
|
||||
The installer requires [Inno Setup 6](https://jrsoftware.org/isinfo.php)
|
||||
(`winget install JRSoftware.InnoSetup`).
|
||||
|
||||
```powershell
|
||||
.\build.ps1 # Tests, PyInstaller-Build und Installer
|
||||
.\build.ps1 -SkipInstaller # nur dist\NetBoxSynchronizer\
|
||||
.\build.ps1 # tests, PyInstaller build and installer
|
||||
.\build.ps1 -SkipInstaller # only dist\NetBoxSynchronizer\
|
||||
```
|
||||
|
||||
Ergebnis: `dist\installer\NetBoxSynchronizer-Setup-<version>.exe`. Die Version steht in `netbox_sync/__init__.py`.
|
||||
Output: `dist\installer\NetBoxSynchronizer-Setup-<version>.exe` and the
|
||||
portable variant `dist\portable\NetBox VM Import.exe` (runs without
|
||||
installation; `-SkipPortable` omits it). The version is set in
|
||||
`netbox_sync/__init__.py`.
|
||||
@@ -1,15 +1,17 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Baut NetBox Synchronizer: Tests, PyInstaller-Build und Inno-Setup-Installer.
|
||||
Baut NetBox Synchronizer: Tests, PyInstaller-Build, Inno-Setup-Installer und portable EXE.
|
||||
|
||||
.EXAMPLE
|
||||
.\build.ps1 # alles
|
||||
.\build.ps1 -SkipInstaller # nur dist\NetBoxSynchronizer\
|
||||
.\build.ps1 -SkipInstaller # nur dist\NetBoxSynchronizer\ (und portable EXE)
|
||||
.\build.ps1 -SkipPortable # ohne dist\portable\NetBox VM Import.exe
|
||||
.\build.ps1 -SkipTests
|
||||
#>
|
||||
param(
|
||||
[switch]$SkipTests,
|
||||
[switch]$SkipInstaller,
|
||||
[switch]$SkipPortable,
|
||||
[string]$InnoSetupCompiler
|
||||
)
|
||||
|
||||
@@ -38,6 +40,13 @@ Write-Host "Baue NetBox Synchronizer $version …" -ForegroundColor Cyan
|
||||
& $python -m PyInstaller --noconfirm --clean --log-level WARN NetBoxSynchronizer.spec
|
||||
if ($LASTEXITCODE) { throw "PyInstaller fehlgeschlagen." }
|
||||
|
||||
if (-not $SkipPortable) {
|
||||
Write-Host "Baue portable EXE …" -ForegroundColor Cyan
|
||||
& $python -m PyInstaller --noconfirm --clean --log-level WARN --distpath dist\portable --workpath build\portable NetBoxSynchronizer.spec -- --portable
|
||||
if ($LASTEXITCODE) { throw "PyInstaller (portabel) fehlgeschlagen." }
|
||||
Write-Host "Fertig: dist\portable\NetBox VM Import.exe" -ForegroundColor Green
|
||||
}
|
||||
|
||||
if ($SkipInstaller) {
|
||||
Write-Host "Fertig: dist\NetBoxSynchronizer\NetBoxSynchronizer.exe" -ForegroundColor Green
|
||||
return
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
; Inno Setup 6 script for NetBox Synchronizer.
|
||||
; Built by build.ps1, which passes the version: ISCC /DAppVersion=4.1.0 NetBoxSynchronizer.iss
|
||||
; Built by build.ps1, which passes the version: ISCC /DAppVersion=4.1.1 NetBoxSynchronizer.iss
|
||||
|
||||
#define AppName "NetBox Synchronizer"
|
||||
#ifndef AppVersion
|
||||
#define AppVersion "4.1.0"
|
||||
#define AppVersion "4.10.1"
|
||||
#endif
|
||||
#define AppPublisher "Louis-Alexander Kerst"
|
||||
#define AppExeName "NetBoxSynchronizer.exe"
|
||||
@@ -66,6 +66,8 @@ Name: "{autodesktop}\{#AppName}"; Filename: "{app}\{#AppExeName}"; AppUserModelI
|
||||
|
||||
[Run]
|
||||
Filename: "{app}\{#AppExeName}"; Description: "{cm:LaunchProgram,{#AppName}}"; Flags: nowait postinstall skipifsilent
|
||||
; Restart after an update started from within the application (silent mode).
|
||||
Filename: "{app}\{#AppExeName}"; Flags: nowait; Check: WizardSilent
|
||||
|
||||
[Code]
|
||||
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
|
||||
|
||||
APP_NAME = "NetBox Synchronizer"
|
||||
APP_VERSION = "4.1.0"
|
||||
APP_VERSION = "4.10.1"
|
||||
APP_PUBLISHER = "Louis-Alexander Kerst"
|
||||
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
|
||||
|
||||
|
||||
@@ -0,0 +1,379 @@
|
||||
"""Sophos access points from a Sophos Central CSV export into NetBox.
|
||||
|
||||
Existing devices are found globally by serial number and MAC address and by
|
||||
name within the tenant group. Sites come from the Sophos "Current Site" column
|
||||
and are mapped to NetBox sites of the tenant group (remembered per profile).
|
||||
Every created object gets a tenant: the one of the NetBox site, otherwise the
|
||||
selected default tenant.
|
||||
"""
|
||||
|
||||
import csv
|
||||
import io
|
||||
import ipaddress
|
||||
import re
|
||||
|
||||
from netbox_sync.core.client_sync import ClientSyncEngine
|
||||
from netbox_sync.core.netbox import assign_mac, normalize_mac, related_id, uses_mac_objects
|
||||
|
||||
MANUFACTURER = "Sophos"
|
||||
PLATFORM = "Sophos AP"
|
||||
INTERFACE_NAME = "eth0"
|
||||
CHUNK = 50
|
||||
|
||||
COLUMNS = {
|
||||
"name": ("ap name", "name"),
|
||||
"mac": ("mac address", "mac"),
|
||||
"serial": ("serial number", "serial", "s/n"),
|
||||
"ip": ("internal ip address", "ip address", "ip"),
|
||||
"model": ("model",),
|
||||
"site_hint": ("current site", "site"),
|
||||
"firmware": ("firmware",),
|
||||
"config_status": ("config status",),
|
||||
}
|
||||
|
||||
|
||||
class APImportError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _compact(text):
|
||||
return re.sub(r"[^0-9a-z]", "", (text or "").casefold().replace("ä", "ae").replace("ö", "oe")
|
||||
.replace("ü", "ue").replace("ß", "ss"))
|
||||
|
||||
|
||||
def parse_csv(data):
|
||||
"""Access points from a Sophos Central export (bytes or text)."""
|
||||
if isinstance(data, bytes):
|
||||
for encoding in ("utf-8-sig", "cp1252"):
|
||||
try:
|
||||
data = data.decode(encoding)
|
||||
break
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
data = data.lstrip("")
|
||||
try:
|
||||
dialect = csv.Sniffer().sniff(data[:4096], delimiters=",;\t")
|
||||
except csv.Error:
|
||||
dialect = csv.excel
|
||||
reader = csv.reader(io.StringIO(data), dialect)
|
||||
header = [cell.strip().casefold() for cell in next(reader, [])]
|
||||
index = {}
|
||||
for key, names in COLUMNS.items():
|
||||
index[key] = next((header.index(name) for name in names if name in header), None)
|
||||
if index["name"] is None or (index["serial"] is None and index["mac"] is None):
|
||||
raise APImportError("Die Datei sieht nicht wie ein Sophos-AP-Export aus (Spalten „AP Name“ und "
|
||||
"„Serial Number“ bzw. „MAC Address“ fehlen).")
|
||||
aps = []
|
||||
for row in reader:
|
||||
if not any(cell.strip() for cell in row):
|
||||
continue
|
||||
|
||||
def cell(key):
|
||||
position = index[key]
|
||||
return row[position].strip() if position is not None and position < len(row) else ""
|
||||
ip = cell("ip")
|
||||
try:
|
||||
ip = str(ipaddress.ip_address(ip)) if ip else ""
|
||||
except ValueError:
|
||||
ip = ""
|
||||
aps.append({
|
||||
"name": re.sub(r"\s+", " ", cell("name")).strip(),
|
||||
"mac": normalize_mac(cell("mac")) or "",
|
||||
"serial": cell("serial").upper(),
|
||||
"ip": ip,
|
||||
"model": cell("model"),
|
||||
"site_hint": re.sub(r"\s+", " ", cell("site_hint")).strip(),
|
||||
"firmware": cell("firmware"),
|
||||
"config_status": cell("config_status"),
|
||||
})
|
||||
if not aps:
|
||||
raise APImportError("Die Datei enthält keine Access Points.")
|
||||
_mark_duplicates(aps)
|
||||
return aps
|
||||
|
||||
|
||||
def _mark_duplicates(aps):
|
||||
for ap in aps:
|
||||
ap["issues"] = []
|
||||
if not ap["site_hint"]:
|
||||
ap["issues"].append("kein Standort in Sophos")
|
||||
for key, text in (("ip", "IP-Adresse"), ("serial", "Seriennummer"), ("mac", "MAC-Adresse")):
|
||||
groups = {}
|
||||
for ap in aps:
|
||||
if ap[key]:
|
||||
groups.setdefault(ap[key], []).append(ap)
|
||||
for value, members in groups.items():
|
||||
if len(members) > 1:
|
||||
for ap in members:
|
||||
others = ", ".join(other["name"] for other in members if other is not ap)
|
||||
ap["issues"].append(f"{text} {value} doppelt (auch {others})")
|
||||
|
||||
|
||||
def ap_key(ap):
|
||||
"""Stable key of an AP for remembered choices."""
|
||||
return ap["serial"] or ap["mac"] or ap["name"]
|
||||
|
||||
|
||||
class APSyncEngine(ClientSyncEngine):
|
||||
"""Reuses the manufacturer/device type/platform helpers of the client import."""
|
||||
|
||||
def __init__(self, nb, log=None):
|
||||
super().__init__(nb, log or (lambda *_args, **_kwargs: None))
|
||||
self.tenant_id = None
|
||||
self.tenant_ids = set()
|
||||
self.ap_sites = []
|
||||
self.group_tenants = []
|
||||
self.netbox_aps = []
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Context
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def load_context(self, tenant_id):
|
||||
"""Sites and existing Sophos devices of the tenant's tenant group."""
|
||||
self.tenant_id = tenant_id
|
||||
tenant = self.nb.tenancy.tenants.get(tenant_id)
|
||||
if tenant is None:
|
||||
raise APImportError(f"Mandant #{tenant_id} existiert nicht.")
|
||||
group_id = related_id(tenant, "group")
|
||||
scope = {"tenant_group_id": group_id} if group_id else {"tenant_id": tenant_id}
|
||||
self.tenant_ids = {tenant_id}
|
||||
if group_id:
|
||||
self.tenant_ids |= {item.id for item in self.nb.tenancy.tenants.filter(group_id=group_id)}
|
||||
tenants = {item.id: item.name for item in self.nb.tenancy.tenants.all()} if group_id else {tenant_id: tenant.name}
|
||||
self.group_tenants = sorted(({"id": key, "name": tenants[key]} for key in self.tenant_ids if key in tenants),
|
||||
key=lambda row: row["name"].casefold())
|
||||
self.ap_sites = sorted(({"id": site.id, "name": site.name, "tenant_id": related_id(site, "tenant"),
|
||||
"tenant": tenants.get(related_id(site, "tenant"), "")}
|
||||
for site in self.nb.dcim.sites.filter(**scope)), key=lambda row: row["name"].casefold())
|
||||
self.roles = sorted(((item.name, item.id) for item in self.nb.dcim.device_roles.all()),
|
||||
key=lambda pair: pair[0].casefold())
|
||||
manufacturer = (self.nb.dcim.manufacturers.get(slug="sophos")
|
||||
or next(iter(self.nb.dcim.manufacturers.filter(name__ie=MANUFACTURER)), None))
|
||||
self.netbox_aps = list(self.nb.dcim.devices.filter(manufacturer_id=manufacturer.id, **scope)) \
|
||||
if manufacturer else []
|
||||
return self.ap_sites
|
||||
|
||||
def suggest_site(self, hint):
|
||||
"""NetBox site for a Sophos site name, or ``None`` when unclear."""
|
||||
wanted = _compact(hint)
|
||||
if not wanted:
|
||||
return None
|
||||
exact = [site for site in self.ap_sites if _compact(site["name"]) == wanted]
|
||||
if len(exact) == 1:
|
||||
return exact[0]["id"]
|
||||
partial = [site for site in self.ap_sites
|
||||
if wanted in _compact(site["name"]) or (_compact(site["name"]) and _compact(site["name"]) in wanted)]
|
||||
return partial[0]["id"] if len(partial) == 1 else None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Matching
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _devices_by(self, field, values):
|
||||
found = {}
|
||||
values = sorted(set(filter(None, values)))
|
||||
for start in range(0, len(values), CHUNK):
|
||||
for device in self.nb.dcim.devices.filter(**{field: values[start:start + CHUNK]}):
|
||||
key = str(getattr(device, field, "") or "").upper()
|
||||
found.setdefault(key, []).append(device)
|
||||
return found
|
||||
|
||||
def _devices_by_mac(self, macs):
|
||||
found = {}
|
||||
macs = sorted(set(filter(None, macs)))
|
||||
for start in range(0, len(macs), CHUNK):
|
||||
chunk = macs[start:start + CHUNK]
|
||||
if uses_mac_objects(self.nb):
|
||||
records = self.nb.dcim.mac_addresses.filter(mac_address=chunk, assigned_object_type="dcim.interface")
|
||||
pairs = [(record.mac_address, related_id(getattr(record, "assigned_object", None), "device"))
|
||||
for record in records]
|
||||
else:
|
||||
pairs = [(record.mac_address, related_id(record, "device"))
|
||||
for record in self.nb.dcim.interfaces.filter(mac_address=chunk)]
|
||||
for mac, device_id in pairs:
|
||||
if device_id:
|
||||
found.setdefault(normalize_mac(mac), set()).add(device_id)
|
||||
return found
|
||||
|
||||
def match(self, aps):
|
||||
"""Attach ``device``/``method`` to every AP and return NetBox APs missing in Sophos."""
|
||||
by_serial = self._devices_by("serial", [ap["serial"] for ap in aps])
|
||||
by_mac = self._devices_by_mac([ap["mac"] for ap in aps])
|
||||
by_name = {}
|
||||
for device in self.netbox_aps:
|
||||
by_name.setdefault(_compact(device.name), []).append(device)
|
||||
cache = {device.id: device for device in self.netbox_aps}
|
||||
for devices in by_serial.values():
|
||||
cache.update({device.id: device for device in devices})
|
||||
matched = set()
|
||||
for ap in aps:
|
||||
device, method = None, ""
|
||||
candidates = by_serial.get(ap["serial"], []) if ap["serial"] else []
|
||||
if len(candidates) == 1:
|
||||
device, method = candidates[0], "Seriennummer"
|
||||
elif len(candidates) > 1:
|
||||
ap["issues"].append(f"Seriennummer in NetBox {len(candidates)}× vergeben")
|
||||
if device is None and ap["mac"] and len(by_mac.get(ap["mac"], ())) == 1:
|
||||
device_id = next(iter(by_mac[ap["mac"]]))
|
||||
device = cache.get(device_id) or self.nb.dcim.devices.get(device_id)
|
||||
method = "MAC-Adresse"
|
||||
if device is None and len(by_name.get(_compact(ap["name"]), [])) == 1:
|
||||
device, method = by_name[_compact(ap["name"])][0], "Name"
|
||||
ap["device"], ap["method"] = device, method
|
||||
if device is not None:
|
||||
matched.add(device.id)
|
||||
tenant = related_id(device, "tenant")
|
||||
if tenant not in self.tenant_ids:
|
||||
ap["issues"].append("NetBox-Gerät gehört " + (
|
||||
f"Mandant „{getattr(device.tenant, 'name', tenant)}“ außerhalb der Mandantengruppe"
|
||||
if tenant else "keinem Mandanten"))
|
||||
if ap["serial"] and getattr(device, "serial", "") and device.serial.upper() != ap["serial"]:
|
||||
ap["issues"].append(f"Seriennummer in NetBox abweichend ({device.serial})")
|
||||
return [device for device in self.netbox_aps if device.id not in matched]
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Sync
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _site_tenant(self, site_id):
|
||||
site = next((row for row in self.ap_sites if row["id"] == site_id), None)
|
||||
return (site or {}).get("tenant_id") or self.tenant_id
|
||||
|
||||
def sync(self, aps, placements, role_id, rename=True, dry_run=True, default_site=None):
|
||||
"""``placements`` maps ``ap_key`` to ``{"site": ID or None, "tenant": ID}``.
|
||||
|
||||
The site is optional; NetBox needs one for every device, so new APs
|
||||
without a site go to ``default_site``. The tenant is mandatory.
|
||||
"""
|
||||
report = self.new_report()
|
||||
self._planned = set()
|
||||
for ap in aps:
|
||||
try:
|
||||
changes = self._sync_ap(ap, placements.get(ap_key(ap)) or {}, role_id, rename, dry_run, report,
|
||||
default_site)
|
||||
except Exception as error: # noqa: BLE001 - one AP must not stop the others
|
||||
report["errors"].append(f"{ap['name']}: {error}")
|
||||
changes = [f"Fehler: {error}"]
|
||||
report["items"].append((ap["name"], changes))
|
||||
return report
|
||||
|
||||
def _sync_ap(self, ap, placement, role_id, rename, dry_run, report, default_site=None):
|
||||
device = ap.get("device")
|
||||
site_id = placement.get("site") or default_site
|
||||
changes = []
|
||||
description = f"Firmware {ap['firmware']}" if ap["firmware"] else ""
|
||||
if device is not None:
|
||||
tenant = related_id(device, "tenant")
|
||||
if tenant is not None and tenant not in self.tenant_ids:
|
||||
report["devices_unchanged"] += 1
|
||||
return ["Übersprungen – Gerät gehört einem Mandanten außerhalb der Mandantengruppe"]
|
||||
updates = {}
|
||||
if rename and ap["name"] and device.name != ap["name"]:
|
||||
updates["name"] = ap["name"]
|
||||
if ap["serial"] and not getattr(device, "serial", ""):
|
||||
updates["serial"] = ap["serial"]
|
||||
if tenant is None:
|
||||
updates["tenant"] = placement.get("tenant") or self._site_tenant(related_id(device, "site"))
|
||||
if description and (getattr(device, "description", "") or "").startswith("Firmware") \
|
||||
and device.description != description:
|
||||
updates["description"] = description
|
||||
if updates:
|
||||
report["devices_updated"] += 1
|
||||
changes.append("Aktualisieren: " + ", ".join(
|
||||
f"{key} → {value}" for key, value in updates.items() if key != "tenant")
|
||||
+ (" (Mandant ergänzt)" if "tenant" in updates else ""))
|
||||
if not dry_run:
|
||||
device.update(updates)
|
||||
else:
|
||||
report["devices_unchanged"] += 1
|
||||
changes.append(f"Vorhanden – gefunden über {ap['method']}")
|
||||
tenant_id = tenant or updates.get("tenant")
|
||||
else:
|
||||
if not site_id:
|
||||
raise APImportError("kein Standort – NetBox verlangt für Geräte einen Standort, bitte einen "
|
||||
"Standard-Standort wählen")
|
||||
if not role_id:
|
||||
raise APImportError("keine Geräterolle gewählt")
|
||||
manufacturer_id = self._manufacturer(MANUFACTURER, report, dry_run)
|
||||
type_id = self._device_type(MANUFACTURER, manufacturer_id, ap["model"] or "Access Point", report, dry_run)
|
||||
platform_id = self._platform(PLATFORM, report, dry_run)
|
||||
# An explicitly chosen tenant wins, otherwise the one of the site.
|
||||
tenant_id = placement.get("tenant") or self._site_tenant(site_id)
|
||||
payload = {"name": ap["name"], "device_type": type_id, "role": role_id, "site": site_id,
|
||||
"tenant": tenant_id, "status": "active", "platform": platform_id}
|
||||
if ap["serial"]:
|
||||
payload["serial"] = ap["serial"]
|
||||
if description:
|
||||
payload["description"] = description
|
||||
report["devices_created"] += 1
|
||||
changes.append(f"Gerät anlegen ({ap['model'] or 'Access Point'})")
|
||||
if dry_run:
|
||||
if ap["mac"] or ap["ip"]:
|
||||
report["interfaces_created"] += 1
|
||||
changes.append(f"Schnittstelle {INTERFACE_NAME} anlegen" + (f" mit MAC {ap['mac']}" if ap["mac"]
|
||||
else ""))
|
||||
if ap["ip"]:
|
||||
report["ips_created"] += 1
|
||||
changes.append(f"IP-Adresse {ap['ip']} anlegen")
|
||||
return changes
|
||||
device = self.nb.dcim.devices.create(payload)
|
||||
if dry_run and device is None:
|
||||
return changes
|
||||
changes += self._sync_network(device, ap, tenant_id, dry_run, report)
|
||||
return changes
|
||||
|
||||
def _interface(self, device, ap, dry_run, report):
|
||||
interfaces = list(self.nb.dcim.interfaces.filter(device_id=device.id))
|
||||
if ap["mac"]:
|
||||
for interface in interfaces:
|
||||
if normalize_mac(getattr(interface, "mac_address", None)) == ap["mac"]:
|
||||
return interface, []
|
||||
named = next((item for item in interfaces if item.name == INTERFACE_NAME), None)
|
||||
if named or interfaces:
|
||||
return named or interfaces[0], []
|
||||
report["interfaces_created"] += 1
|
||||
if dry_run:
|
||||
return None, [f"Schnittstelle {INTERFACE_NAME} anlegen"]
|
||||
interface = self.nb.dcim.interfaces.create({"device": device.id, "name": INTERFACE_NAME, "type": "1000base-t"})
|
||||
return interface, [f"Schnittstelle {INTERFACE_NAME} anlegen"]
|
||||
|
||||
def _sync_network(self, device, ap, tenant_id, dry_run, report):
|
||||
if not ap["mac"] and not ap["ip"]:
|
||||
return []
|
||||
interface, changes = self._interface(device, ap, dry_run, report)
|
||||
if ap["mac"] and interface is not None and not dry_run:
|
||||
if assign_mac(self.nb, interface, ap["mac"], "dcim.interface"):
|
||||
changes.append(f"MAC {ap['mac']} zugeordnet")
|
||||
if not ap["ip"]:
|
||||
return changes
|
||||
prefix = next(iter(self.nb.ipam.prefixes.filter(contains=ap["ip"], vrf_id="null")), None)
|
||||
length = str(getattr(prefix, "prefix", "")).split("/")[-1] if prefix else "32"
|
||||
address = f"{ap['ip']}/{length}"
|
||||
existing = list(self.nb.ipam.ip_addresses.filter(address=ap["ip"], vrf_id="null"))
|
||||
if existing:
|
||||
ip = existing[0]
|
||||
assigned = getattr(ip, "assigned_object_id", None)
|
||||
if interface is not None and assigned == interface.id:
|
||||
pass
|
||||
elif assigned:
|
||||
changes.append(f"IP-Adresse {ap['ip']} ist bereits einem anderen Objekt zugeordnet – übersprungen")
|
||||
return changes
|
||||
else:
|
||||
changes.append(f"IP-Adresse {ap['ip']} zuordnen")
|
||||
if not dry_run and interface is not None:
|
||||
ip.update({"assigned_object_type": "dcim.interface", "assigned_object_id": interface.id,
|
||||
"tenant": related_id(ip, "tenant") or tenant_id})
|
||||
else:
|
||||
report["ips_created"] += 1
|
||||
changes.append(f"IP-Adresse {address} anlegen")
|
||||
if dry_run or interface is None:
|
||||
return changes
|
||||
ip = self.nb.ipam.ip_addresses.create({
|
||||
"address": address, "status": "active", "tenant": tenant_id,
|
||||
"assigned_object_type": "dcim.interface", "assigned_object_id": interface.id,
|
||||
})
|
||||
if not dry_run and related_id(device, "primary_ip4") != ip.id:
|
||||
device.update({"primary_ip4": ip.id})
|
||||
changes.append(f"Primäre IP {ap['ip']}")
|
||||
return changes
|
||||
@@ -231,12 +231,12 @@ class ClientSyncEngine:
|
||||
if not dry_run:
|
||||
device.update(updates)
|
||||
if interfaces:
|
||||
changes.extend(self._sync_interfaces(device, client, dry_run, report))
|
||||
changes.extend(self._sync_interfaces(device, client, tenant_id, dry_run, report))
|
||||
if not changes:
|
||||
report["devices_unchanged"] += 1
|
||||
return changes
|
||||
|
||||
def _sync_interfaces(self, device, client, dry_run, report):
|
||||
def _sync_interfaces(self, device, client, tenant_id, dry_run, report):
|
||||
changes = []
|
||||
existing = {str(item.name).casefold(): item for item in self.nb.dcim.interfaces.filter(device_id=device.id)}
|
||||
primary = None
|
||||
@@ -257,7 +257,7 @@ class ClientSyncEngine:
|
||||
if record is not None and mac and not dry_run:
|
||||
assign_mac(self.nb, record, mac, "dcim.interface")
|
||||
for address in interface.get("ips", []):
|
||||
ip, change = self._sync_ip(address, record, interface.get("dhcp"), dry_run, report)
|
||||
ip, change = self._sync_ip(address, record, interface.get("dhcp"), tenant_id, dry_run, report)
|
||||
if change:
|
||||
changes.append(change)
|
||||
if ip is not None and primary is None and ":" not in address and interface.get("gateway"):
|
||||
@@ -266,7 +266,7 @@ class ClientSyncEngine:
|
||||
device.update({"primary_ip4": primary.id})
|
||||
return changes
|
||||
|
||||
def _sync_ip(self, address, interface, dhcp, dry_run, report):
|
||||
def _sync_ip(self, address, interface, dhcp, tenant_id, dry_run, report):
|
||||
matches = [ip for ip in self.nb.ipam.ip_addresses.filter(address=address.split("/")[0])
|
||||
if related_id(ip, "vrf") is None]
|
||||
if not matches:
|
||||
@@ -276,6 +276,7 @@ class ClientSyncEngine:
|
||||
ip = self.nb.ipam.ip_addresses.create({
|
||||
"address": address, "status": "dhcp" if dhcp else "active",
|
||||
"assigned_object_type": "dcim.interface", "assigned_object_id": interface.id,
|
||||
**({"tenant": tenant_id} if tenant_id else {}),
|
||||
})
|
||||
return ip, f"IP-Adresse {address} anlegen"
|
||||
ip = matches[0]
|
||||
|
||||
+61
-264
@@ -1,21 +1,16 @@
|
||||
"""Agentless inventory of Windows clients via WMI/CIM over WinRM.
|
||||
|
||||
Targets come from Active Directory (computer objects) or from a list of host
|
||||
names, IP addresses and ranges. Each reachable client is queried with
|
||||
``Get-CimInstance`` through Windows PowerShell, so authentication uses the
|
||||
Windows stack (Kerberos/Negotiate) – either the signed-in user or credentials
|
||||
from the Windows logon prompt. Passwords are handed to PowerShell via stdin and
|
||||
never appear on a command line or on disk.
|
||||
names, IP addresses and ranges. Each reachable client is queried in-process
|
||||
through the Windows WSMan COM API (see :mod:`netbox_sync.core.wsman`), so
|
||||
authentication uses Kerberos/Negotiate with either the signed-in user or
|
||||
credentials from the Windows logon prompt. No helper processes are started.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
@@ -134,193 +129,6 @@ def resolves(host):
|
||||
return False
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# PowerShell
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def powershell_path():
|
||||
root = os.environ.get("SystemRoot", r"C:\Windows")
|
||||
candidate = os.path.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
|
||||
return candidate if os.path.exists(candidate) else (shutil.which("powershell") or "powershell.exe")
|
||||
|
||||
|
||||
def _start_powershell(script, payload):
|
||||
if sys.platform != "win32":
|
||||
raise ClientScanError("Die Abfrage von Windows-Clients ist nur unter Windows verfügbar.")
|
||||
encoded = base64.b64encode(script.encode("utf-16-le")).decode("ascii")
|
||||
process = subprocess.Popen( # noqa: S603 - fixed executable, script passed encoded
|
||||
[powershell_path(), "-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",
|
||||
"-EncodedCommand", encoded],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
||||
)
|
||||
process.stdin.write(json.dumps(payload).encode("utf-8"))
|
||||
process.stdin.close()
|
||||
return process
|
||||
|
||||
|
||||
def _credential_payload(credential):
|
||||
if credential is None:
|
||||
return {"user": "", "password": ""}
|
||||
return {"user": credential.username, "password": credential.password}
|
||||
|
||||
|
||||
_PS_PROLOG = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false
|
||||
$job = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
||||
$cred = $null
|
||||
if ($job.user) {
|
||||
$secure = ConvertTo-SecureString $job.password -AsPlainText -Force
|
||||
$cred = New-Object System.Management.Automation.PSCredential($job.user, $secure)
|
||||
}
|
||||
function Emit($value) { [Console]::Out.WriteLine(($value | ConvertTo-Json -Compress -Depth 6)); [Console]::Out.Flush() }
|
||||
function Text($value) { if ($null -eq $value) { '' } else { ([string]$value).Trim() } }
|
||||
function Stamp($value) { if ($value -is [datetime]) { $value.ToString('s') } else { '' } }
|
||||
"""
|
||||
|
||||
_SCAN_SCRIPT = _PS_PROLOG + r"""
|
||||
if ($job.ssl) { $option = New-CimSessionOption -UseSsl } else { $option = New-CimSessionOption -Protocol Wsman }
|
||||
foreach ($target in $job.hosts) {
|
||||
$result = [ordered]@{ host = $target; ok = $false }
|
||||
$session = $null
|
||||
try {
|
||||
$params = @{ ComputerName = $target; SessionOption = $option; OperationTimeoutSec = [int]$job.timeout }
|
||||
if ($job.port) { $params.Port = [int]$job.port }
|
||||
if ($cred) { $params.Credential = $cred; $params.Authentication = 'Negotiate' }
|
||||
$session = New-CimSession @params
|
||||
$cs = Get-CimInstance -CimSession $session -ClassName Win32_ComputerSystem
|
||||
$os = Get-CimInstance -CimSession $session -ClassName Win32_OperatingSystem
|
||||
$bios = Get-CimInstance -CimSession $session -ClassName Win32_BIOS
|
||||
$product = Get-CimInstance -CimSession $session -ClassName Win32_ComputerSystemProduct
|
||||
$enclosure = @(Get-CimInstance -CimSession $session -ClassName Win32_SystemEnclosure) | Select-Object -First 1
|
||||
$cpu = @(Get-CimInstance -CimSession $session -ClassName Win32_Processor)
|
||||
$adapters = @{}
|
||||
foreach ($adapter in @(Get-CimInstance -CimSession $session -ClassName Win32_NetworkAdapter -Filter 'PhysicalAdapter = TRUE')) {
|
||||
$adapters[[int]$adapter.InterfaceIndex] = $adapter
|
||||
}
|
||||
$nics = @()
|
||||
foreach ($config in @(Get-CimInstance -CimSession $session -ClassName Win32_NetworkAdapterConfiguration -Filter 'IPEnabled = TRUE')) {
|
||||
$adapter = $adapters[[int]$config.InterfaceIndex]
|
||||
$nics += [ordered]@{
|
||||
name = Text $adapter.NetConnectionID
|
||||
description = Text $config.Description
|
||||
mac = Text $config.MACAddress
|
||||
ips = @($config.IPAddress | ForEach-Object { Text $_ })
|
||||
masks = @($config.IPSubnet | ForEach-Object { Text $_ })
|
||||
gateway = @($config.DefaultIPGateway | ForEach-Object { Text $_ })
|
||||
dhcp = [bool]$config.DHCPEnabled
|
||||
physical = [bool]($null -ne $adapter)
|
||||
speed = [int64]$adapter.Speed
|
||||
}
|
||||
}
|
||||
$displayVersion = ''
|
||||
try {
|
||||
$reg = Invoke-CimMethod -CimSession $session -Namespace root/default -ClassName StdRegProv -MethodName GetStringValue -Arguments @{ hDefKey = [uint32]2147483650; sSubKeyName = 'SOFTWARE\Microsoft\Windows NT\CurrentVersion'; sValueName = 'DisplayVersion' }
|
||||
$displayVersion = Text $reg.sValue
|
||||
} catch { }
|
||||
$result.ok = $true
|
||||
$result.name = Text $cs.Name
|
||||
$result.domain = Text $cs.Domain
|
||||
$result.part_of_domain = [bool]$cs.PartOfDomain
|
||||
$result.manufacturer = Text $cs.Manufacturer
|
||||
$result.model = Text $cs.Model
|
||||
$result.product_name = Text $product.Name
|
||||
$result.product_version = Text $product.Version
|
||||
$result.serial = Text $bios.SerialNumber
|
||||
$result.bios_version = Text $bios.SMBIOSBIOSVersion
|
||||
$result.chassis = @($enclosure.ChassisTypes | ForEach-Object { [int]$_ })
|
||||
$result.user = Text $cs.UserName
|
||||
$result.memory = [int64]$cs.TotalPhysicalMemory
|
||||
$result.cpu = Text ($cpu | Select-Object -First 1).Name
|
||||
$result.cores = [int](($cpu | Measure-Object -Property NumberOfCores -Sum).Sum)
|
||||
$result.os = Text $os.Caption
|
||||
$result.os_version = Text $os.Version
|
||||
$result.os_build = Text $os.BuildNumber
|
||||
$result.os_display_version = $displayVersion
|
||||
$result.os_architecture = Text $os.OSArchitecture
|
||||
$result.installed = Stamp $os.InstallDate
|
||||
$result.last_boot = Stamp $os.LastBootUpTime
|
||||
$result.nics = $nics
|
||||
} catch {
|
||||
$result.error = Text $_.Exception.Message
|
||||
} finally {
|
||||
if ($session) { Remove-CimSession $session -ErrorAction SilentlyContinue }
|
||||
}
|
||||
Emit $result
|
||||
}
|
||||
"""
|
||||
|
||||
_AD_SCRIPT = _PS_PROLOG + r"""
|
||||
try {
|
||||
if ($cred) {
|
||||
$plain = $cred.GetNetworkCredential()
|
||||
$root = New-Object System.DirectoryServices.DirectoryEntry($job.path, $cred.UserName, $plain.Password)
|
||||
} elseif ($job.path) {
|
||||
$root = New-Object System.DirectoryServices.DirectoryEntry($job.path)
|
||||
} else {
|
||||
$root = New-Object System.DirectoryServices.DirectoryEntry
|
||||
}
|
||||
$searcher = New-Object System.DirectoryServices.DirectorySearcher($root)
|
||||
$searcher.Filter = $job.filter
|
||||
$searcher.PageSize = 1000
|
||||
foreach ($name in 'name', 'dnshostname', 'operatingsystem', 'operatingsystemversion', 'lastlogontimestamp',
|
||||
'distinguishedname', 'description', 'useraccountcontrol') {
|
||||
[void]$searcher.PropertiesToLoad.Add($name)
|
||||
}
|
||||
foreach ($item in $searcher.FindAll()) {
|
||||
$p = $item.Properties
|
||||
Emit ([ordered]@{
|
||||
name = Text ($p['name'] | Select-Object -First 1)
|
||||
dns = Text ($p['dnshostname'] | Select-Object -First 1)
|
||||
os = Text ($p['operatingsystem'] | Select-Object -First 1)
|
||||
os_version = Text ($p['operatingsystemversion'] | Select-Object -First 1)
|
||||
last_logon = [int64]($p['lastlogontimestamp'] | Select-Object -First 1)
|
||||
dn = Text ($p['distinguishedname'] | Select-Object -First 1)
|
||||
description = Text ($p['description'] | Select-Object -First 1)
|
||||
disabled = [bool](([int]($p['useraccountcontrol'] | Select-Object -First 1)) -band 2)
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
Emit ([ordered]@{ fatal = Text $_.Exception.Message })
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def _read_lines(process, cancelled):
|
||||
"""Yield parsed JSON lines from a PowerShell process, killing it on cancel."""
|
||||
try:
|
||||
for raw in process.stdout:
|
||||
if cancelled():
|
||||
process.kill()
|
||||
return
|
||||
line = raw.decode("utf-8", errors="replace").strip()
|
||||
if line.startswith("{"):
|
||||
try:
|
||||
yield json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
try:
|
||||
process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
|
||||
|
||||
def _stderr(process):
|
||||
try:
|
||||
text = process.stderr.read().decode("utf-8", errors="replace").strip()
|
||||
except (OSError, ValueError):
|
||||
return ""
|
||||
if text.startswith("#< CLIXML"):
|
||||
parts = re.findall(r'<S S="Error">(.*?)</S>', text, re.S)
|
||||
text = "".join(parts).replace("_x000D__x000A_", "\n").replace("<", "<").replace(">", ">")
|
||||
text = text.replace(""", '"').replace("&", "&")
|
||||
return text.strip()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Active Directory
|
||||
# --------------------------------------------------------------------------
|
||||
@@ -334,17 +142,24 @@ def ad_filter(options):
|
||||
return "(&" + "".join(parts) + ")"
|
||||
|
||||
|
||||
def ad_path(options, credential):
|
||||
def domain_base(domain):
|
||||
return ",".join(f"DC={part}" for part in domain.strip(".").split(".") if part)
|
||||
|
||||
|
||||
def ad_location(options):
|
||||
"""``server/base`` for the LDAP query; defaults to the domain of the signed-in user."""
|
||||
server = (options.get("ad_server") or "").strip().strip("/")
|
||||
base = (options.get("ad_base") or "").strip()
|
||||
if not server and not base and credential is None:
|
||||
return ""
|
||||
if not server and credential is not None:
|
||||
server = os.environ.get("USERDNSDOMAIN", "")
|
||||
if not server and not base:
|
||||
raise ClientScanError("Dieser Rechner ist keiner Domäne beigetreten. Bitte unter „Domäne / DC“ die Domäne "
|
||||
"angeben, z. B. firma.local.")
|
||||
return "LDAP://" + "/".join(part for part in (server, base) if part)
|
||||
if server and not base:
|
||||
# LDAP://server binds to the default naming context of that domain or DC.
|
||||
return server
|
||||
if not base:
|
||||
domain = os.environ.get("USERDNSDOMAIN", "")
|
||||
if not domain:
|
||||
raise ClientScanError("Dieser Rechner ist keiner Domäne beigetreten. Bitte unter „Domäne / DC“ die "
|
||||
"Domäne angeben, z. B. firma.local.")
|
||||
base = domain_base(domain)
|
||||
return "/".join(part for part in (server, base) if part)
|
||||
|
||||
|
||||
def filetime_to_unix(value):
|
||||
@@ -355,15 +170,21 @@ def filetime_to_unix(value):
|
||||
|
||||
def query_ad(options, credential=None, log=lambda *_args: None, cancelled=lambda: False, now=None):
|
||||
"""Return computer objects from Active Directory as client rows (not yet scanned)."""
|
||||
payload = dict(_credential_payload(credential), path=ad_path(options, credential), filter=ad_filter(options))
|
||||
log(f"Suche Computerkonten im Active Directory{' unter ' + payload['path'] if payload['path'] else ''} …")
|
||||
process = _start_powershell(_AD_SCRIPT, payload)
|
||||
from netbox_sync.core import wsman
|
||||
|
||||
location = ad_location(options)
|
||||
log(f"Suche Computerkonten im Active Directory (LDAP://{location}) …")
|
||||
try:
|
||||
with wsman.com_thread():
|
||||
items = wsman.search_ad(location, ad_filter(options), credential)
|
||||
except wsman.WSManError as error:
|
||||
raise ClientScanError(f"Active-Directory-Abfrage fehlgeschlagen: {friendly_error(str(error))}") from error
|
||||
max_age = int(options.get("max_age_days") or 0)
|
||||
limit = ((now or time.time()) - max_age * 86400) if max_age else None
|
||||
rows, stale = [], 0
|
||||
for item in _read_lines(process, cancelled):
|
||||
if "fatal" in item:
|
||||
raise ClientScanError(f"Active-Directory-Abfrage fehlgeschlagen: {friendly_error(item['fatal'])}")
|
||||
for item in items:
|
||||
if cancelled():
|
||||
break
|
||||
if not item.get("name"):
|
||||
continue
|
||||
last_logon = filetime_to_unix(item.get("last_logon"))
|
||||
@@ -375,10 +196,6 @@ def query_ad(options, credential=None, log=lambda *_args: None, cancelled=lambda
|
||||
"os_version": item.get("os_version", ""), "last_logon": last_logon, "dn": item.get("dn", ""),
|
||||
"description": item.get("description", ""), "disabled": bool(item.get("disabled")),
|
||||
}))
|
||||
if process.returncode not in (0, None) and not rows:
|
||||
problem = _stderr(process)
|
||||
if problem:
|
||||
raise ClientScanError(f"Active-Directory-Abfrage fehlgeschlagen: {problem}")
|
||||
log(f"Active Directory: {len(rows)} Computer" + (f" ({stale} ohne Anmeldung seit {max_age} Tagen ausgelassen)"
|
||||
if stale else ""), "success")
|
||||
return rows
|
||||
@@ -420,7 +237,7 @@ def chassis_name(types):
|
||||
|
||||
|
||||
def apply_scan(row, raw, now=None):
|
||||
"""Merge the raw PowerShell result into a result row."""
|
||||
"""Merge the raw WinRM result into a result row."""
|
||||
row = dict(row)
|
||||
row["scanned_at"] = now or time.time()
|
||||
if not raw.get("ok"):
|
||||
@@ -540,65 +357,45 @@ def friendly_error(text):
|
||||
# Scan
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def _chunks(items, count):
|
||||
count = max(1, min(count, len(items)))
|
||||
return [items[index::count] for index in range(count)]
|
||||
|
||||
|
||||
def scan_clients(rows, credential=None, use_ssl=False, parallel=8, timeout=30, log=lambda *_args: None,
|
||||
on_result=lambda _row: None, cancelled=lambda: False):
|
||||
on_result=lambda _row: None, cancelled=lambda: False, query=None):
|
||||
"""Query every row's host. ``on_result`` is called for each finished row (any thread)."""
|
||||
if sys.platform != "win32" and query is None:
|
||||
raise ClientScanError("Die Abfrage von Windows-Clients ist nur unter Windows verfügbar.")
|
||||
port = WINRM_HTTPS_PORT if use_ssl else WINRM_HTTP_PORT
|
||||
by_host = {row["host"]: row for row in rows}
|
||||
results = []
|
||||
|
||||
def reachable(row):
|
||||
def scan(row):
|
||||
if cancelled():
|
||||
return None
|
||||
host = row["host"]
|
||||
if not is_ip(host) and not resolves(host):
|
||||
return row, "Rechnername kann nicht aufgelöst werden (DNS)."
|
||||
return dict(row, status="offline", message="Rechnername kann nicht aufgelöst werden (DNS).",
|
||||
scanned_at=time.time())
|
||||
if not port_open(host, port):
|
||||
return row, f"Nicht erreichbar – ausgeschaltet oder WinRM-Port {port} geschlossen."
|
||||
return row, None
|
||||
return dict(row, status="offline", scanned_at=time.time(),
|
||||
message=f"Nicht erreichbar – ausgeschaltet oder WinRM-Port {port} geschlossen.")
|
||||
if cancelled():
|
||||
return None
|
||||
if query is not None:
|
||||
raw = query(host)
|
||||
else:
|
||||
from netbox_sync.core import wsman
|
||||
|
||||
log(f"Prüfe Erreichbarkeit von {len(rows)} Client(s) auf Port {port} …")
|
||||
online = []
|
||||
with ThreadPoolExecutor(max_workers=min(64, max(1, len(rows)))) as pool:
|
||||
for future in as_completed([pool.submit(reachable, row) for row in rows]):
|
||||
if cancelled():
|
||||
break
|
||||
row, problem = future.result()
|
||||
if problem:
|
||||
finished = dict(row, status="offline", message=problem, scanned_at=time.time())
|
||||
results.append(finished)
|
||||
on_result(finished)
|
||||
else:
|
||||
online.append(row["host"])
|
||||
if cancelled() or not online:
|
||||
return results
|
||||
log(f"{len(online)} Client(s) erreichbar, frage WMI ab …")
|
||||
with wsman.com_thread():
|
||||
raw = wsman.query_client(host, credential, use_ssl, port, timeout)
|
||||
return apply_scan(row, raw)
|
||||
|
||||
def run_chunk(hosts):
|
||||
payload = dict(_credential_payload(credential), hosts=hosts, ssl=use_ssl, port=port, timeout=timeout)
|
||||
process = _start_powershell(_SCAN_SCRIPT, payload)
|
||||
done = set()
|
||||
for raw in _read_lines(process, cancelled):
|
||||
row = by_host.get(raw.get("host"))
|
||||
if row is None:
|
||||
log(f"Frage {len(rows)} Client(s) über WinRM (Port {port}) ab …")
|
||||
with ThreadPoolExecutor(max_workers=max(1, min(parallel, len(rows) or 1))) as pool:
|
||||
futures = [pool.submit(scan, row) for row in rows]
|
||||
for future in as_completed(futures):
|
||||
finished = future.result()
|
||||
if finished is None:
|
||||
continue
|
||||
done.add(raw["host"])
|
||||
finished = apply_scan(row, raw)
|
||||
results.append(finished)
|
||||
on_result(finished)
|
||||
if not cancelled():
|
||||
problem = _stderr(process) or "PowerShell wurde unerwartet beendet."
|
||||
for host in hosts:
|
||||
if host not in done:
|
||||
finished = dict(by_host[host], status="error", message=friendly_error(problem),
|
||||
scanned_at=time.time())
|
||||
results.append(finished)
|
||||
on_result(finished)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=max(1, parallel)) as pool:
|
||||
for future in as_completed([pool.submit(run_chunk, hosts) for hosts in _chunks(online, parallel)]):
|
||||
future.result()
|
||||
if cancelled():
|
||||
for pending in futures:
|
||||
pending.cancel()
|
||||
return results
|
||||
@@ -20,7 +20,11 @@ DEFAULT_SETTINGS = {
|
||||
"enable_lldp": False, # allow configuration changes on switches
|
||||
"create_cables": True,
|
||||
"offline_mode": False, # collect and export to JSON without NetBox
|
||||
"parallel_wmi": 8, # concurrent PowerShell sessions for client scans
|
||||
"parallel_wmi": 8, # concurrent WinRM sessions for client scans
|
||||
"auto_update_check": True, # look for a newer Gitea release on start
|
||||
"skipped_version": "", # release the user chose to skip
|
||||
"scanner_targets": "", # last IP ranges of the network scanner
|
||||
"scanner_ports": "", # empty = default port list
|
||||
}
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -115,6 +119,14 @@ def empty_profile(name):
|
||||
"switches": [],
|
||||
# Remembered assignment "<source id>:<hypervisor cluster>" -> NetBox cluster name.
|
||||
"cluster_map": {},
|
||||
"host_map": {},
|
||||
# Switch VLAN decisions for all switches: "<vid>" -> {"action": "map"|"new"|"skip"|"ignore", ...}.
|
||||
"vlan_map": {},
|
||||
# Switch network decisions: "<network>" -> {"vrf_id", "vrf_name" (new VRF), "create": prefix}.
|
||||
"network_map": {},
|
||||
# Sophos AP import: tenant, role, rename option and site choices
|
||||
# ("site_map": Sophos site -> NetBox site ID, "ap_sites": AP key -> NetBox site ID).
|
||||
"access_points": {},
|
||||
# Windows client scan: targets and options, never a password.
|
||||
"clients": dict(DEFAULT_CLIENT_OPTIONS),
|
||||
}
|
||||
@@ -162,6 +174,10 @@ class ProfileStore:
|
||||
"netbox_token": self._decrypt(record.get("netbox_token_encrypted", ""), f"{name}: NetBox-Token"),
|
||||
"netbox_ignore_ssl": bool(record.get("netbox_ignore_ssl", record.get("ignore_ssl_errors", False))),
|
||||
"cluster_map": dict(record.get("cluster_map", {})),
|
||||
"host_map": dict(record.get("host_map", {})),
|
||||
"vlan_map": dict(record.get("vlan_map", {})),
|
||||
"network_map": dict(record.get("network_map", {})),
|
||||
"access_points": dict(record.get("access_points", {})),
|
||||
"clients": {**DEFAULT_CLIENT_OPTIONS, **{key: value for key, value in record.get("clients", {}).items()
|
||||
if key in DEFAULT_CLIENT_OPTIONS}},
|
||||
})
|
||||
@@ -169,6 +185,15 @@ class ProfileStore:
|
||||
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 4.5/4.6: VLAN and network decisions were stored per switch.
|
||||
for switch in profile["switches"]:
|
||||
for vid, choice in (switch.pop("vlan_map", None) or {}).items():
|
||||
profile["vlan_map"].setdefault(vid, choice)
|
||||
switch.pop("create_vlans", None)
|
||||
approved = switch.pop("create_prefixes", None) or []
|
||||
for network, vrf_name in (switch.pop("network_vrfs", None) or {}).items():
|
||||
profile["network_map"].setdefault(network, {"vrf_id": None, "vrf_name": vrf_name or "",
|
||||
"create": network in approved})
|
||||
|
||||
# Migration from v2: one VMware source embedded in each profile.
|
||||
if not profile["sources"] and record.get("esxi_host"):
|
||||
@@ -225,6 +250,10 @@ class ProfileStore:
|
||||
"sources": [self._encrypt_record(source) for source in profile.get("sources", [])],
|
||||
"switches": [self._encrypt_record(switch) for switch in profile.get("switches", [])],
|
||||
"cluster_map": dict(profile.get("cluster_map", {})),
|
||||
"host_map": dict(profile.get("host_map", {})),
|
||||
"vlan_map": dict(profile.get("vlan_map", {})),
|
||||
"network_map": dict(profile.get("network_map", {})),
|
||||
"access_points": dict(profile.get("access_points", {})),
|
||||
"clients": dict(profile.get("clients", DEFAULT_CLIENT_OPTIONS)),
|
||||
})
|
||||
|
||||
|
||||
@@ -75,6 +75,7 @@ def validate(data):
|
||||
raise ExchangeError("Die Datei enthält eine VM ohne Name oder Quelle.")
|
||||
vm.setdefault("interfaces", [])
|
||||
vm.setdefault("cluster", "")
|
||||
vm.setdefault("host", "")
|
||||
vm.setdefault("status", "offline")
|
||||
for key in ("vcpus", "memory", "disk"):
|
||||
vm[key] = int(vm.get(key) or 0)
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
"""Network scanner: find hosts in IP ranges and compare them with NetBox (read only).
|
||||
|
||||
Reachability uses the Windows ICMP API (no administrator rights, no ping.exe),
|
||||
ARP for the local subnet and TCP ports, so hosts that block ICMP are found as
|
||||
well. Names come from reverse DNS and NetBIOS. Nothing is written to NetBox.
|
||||
"""
|
||||
|
||||
import ctypes
|
||||
import ipaddress
|
||||
import re
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
from netbox_sync.core.netbox import related_id
|
||||
|
||||
SERVICES = {
|
||||
21: "FTP", 22: "SSH", 23: "Telnet", 25: "SMTP", 53: "DNS", 80: "HTTP", 110: "POP3", 135: "RPC",
|
||||
139: "NetBIOS", 143: "IMAP", 161: "SNMP", 389: "LDAP", 443: "HTTPS", 445: "SMB", 515: "LPD", 631: "IPP",
|
||||
636: "LDAPS", 993: "IMAPS", 1433: "MSSQL", 3306: "MySQL", 3389: "RDP", 5432: "PostgreSQL", 5900: "VNC",
|
||||
5985: "WinRM", 5986: "WinRM-HTTPS", 8006: "Proxmox", 8080: "HTTP-Alt", 8443: "HTTPS-Alt", 9100: "Druck",
|
||||
}
|
||||
DEFAULT_PORTS = "21-23,25,53,80,135,139,443,445,3389,5900,5985,8006,8080,8443,9100"
|
||||
# Probed on hosts that do not answer ping, to find hosts behind a firewall.
|
||||
QUICK_PORTS = (445, 3389, 80, 443, 22)
|
||||
MAX_HOSTS = 4096
|
||||
|
||||
|
||||
class ScanError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def parse_ports(text):
|
||||
"""``"21-23,80, 443"`` → sorted unique port numbers."""
|
||||
ports = set()
|
||||
for part in re.split(r"[\s,;]+", (text or "").strip()):
|
||||
if not part:
|
||||
continue
|
||||
match = re.fullmatch(r"(\d+)(?:-(\d+))?", part)
|
||||
if not match:
|
||||
raise ScanError(f"Ungültige Port-Angabe: {part}")
|
||||
start, end = int(match.group(1)), int(match.group(2) or match.group(1))
|
||||
if not 1 <= start <= end <= 65535:
|
||||
raise ScanError(f"Ungültiger Port-Bereich: {part}")
|
||||
ports.update(range(start, end + 1))
|
||||
if len(ports) > 1024:
|
||||
raise ScanError("Bitte höchstens 1024 Ports angeben.")
|
||||
return sorted(ports)
|
||||
|
||||
|
||||
def expand_ips(text):
|
||||
"""IPv4 addresses from ranges, networks and names (names are resolved)."""
|
||||
from netbox_sync.core.clients import ClientScanError, expand_targets
|
||||
try:
|
||||
targets = expand_targets(text)
|
||||
except ClientScanError as error:
|
||||
raise ScanError(str(error)) from error
|
||||
result = []
|
||||
for target in targets:
|
||||
try:
|
||||
address = ipaddress.ip_address(target)
|
||||
except ValueError:
|
||||
try:
|
||||
address = ipaddress.ip_address(socket.gethostbyname(target))
|
||||
except (OSError, ValueError) as error:
|
||||
raise ScanError(f"Name nicht auflösbar: {target}") from error
|
||||
if address.version != 4:
|
||||
raise ScanError(f"Nur IPv4 wird gescannt: {target}")
|
||||
if str(address) not in result:
|
||||
result.append(str(address))
|
||||
if not result:
|
||||
raise ScanError("Bitte IP-Adressen, Bereiche (192.0.2.1-254) oder Netze (192.0.2.0/24) angeben.")
|
||||
if len(result) > MAX_HOSTS:
|
||||
raise ScanError(f"Zu viele Adressen ({len(result)}) – höchstens {MAX_HOSTS} pro Scan.")
|
||||
return result
|
||||
|
||||
|
||||
def local_networks():
|
||||
"""IPv4 /24 networks of this computer (for the "own network" button)."""
|
||||
addresses = set()
|
||||
try:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as probe:
|
||||
probe.connect(("192.0.2.1", 9)) # no packet is sent for UDP connect
|
||||
addresses.add(probe.getsockname()[0])
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
addresses.update(info[4][0] for info in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET))
|
||||
except OSError:
|
||||
pass
|
||||
networks = []
|
||||
for address in sorted(addresses):
|
||||
ip = ipaddress.ip_address(address)
|
||||
if not (ip.is_loopback or ip.is_link_local):
|
||||
network = str(ipaddress.ip_network(f"{address}/24", strict=False))
|
||||
if network not in networks:
|
||||
networks.append(network)
|
||||
return networks
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Probes
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def _inet_addr(ip):
|
||||
return struct.unpack("<I", socket.inet_aton(ip))[0]
|
||||
|
||||
|
||||
if sys.platform == "win32":
|
||||
class _IpOptions(ctypes.Structure):
|
||||
_fields_ = [("Ttl", ctypes.c_ubyte), ("Tos", ctypes.c_ubyte), ("Flags", ctypes.c_ubyte),
|
||||
("OptionsSize", ctypes.c_ubyte), ("OptionsData", ctypes.c_void_p)]
|
||||
|
||||
class _EchoReply(ctypes.Structure):
|
||||
_fields_ = [("Address", ctypes.c_ulong), ("Status", ctypes.c_ulong), ("RoundTripTime", ctypes.c_ulong),
|
||||
("DataSize", ctypes.c_ushort), ("Reserved", ctypes.c_ushort), ("Data", ctypes.c_void_p),
|
||||
("Options", _IpOptions)]
|
||||
|
||||
_iphlpapi = ctypes.windll.iphlpapi
|
||||
_iphlpapi.IcmpCreateFile.restype = ctypes.c_void_p
|
||||
_iphlpapi.IcmpCloseHandle.argtypes = [ctypes.c_void_p]
|
||||
_iphlpapi.IcmpSendEcho.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p, ctypes.c_ushort,
|
||||
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong]
|
||||
_iphlpapi.SendARP.argtypes = [ctypes.c_ulong, ctypes.c_ulong, ctypes.c_void_p, ctypes.POINTER(ctypes.c_ulong)]
|
||||
|
||||
|
||||
def ping(ip, timeout_ms=800):
|
||||
"""Round-trip time in ms, or ``None`` without answer."""
|
||||
if sys.platform != "win32":
|
||||
return None
|
||||
handle = _iphlpapi.IcmpCreateFile()
|
||||
if not handle or handle == ctypes.c_void_p(-1).value:
|
||||
return None
|
||||
try:
|
||||
payload = b"netbox-sync-scan"
|
||||
buffer = ctypes.create_string_buffer(ctypes.sizeof(_EchoReply) + len(payload) + 8)
|
||||
count = _iphlpapi.IcmpSendEcho(handle, _inet_addr(ip), payload, len(payload), None, buffer,
|
||||
ctypes.sizeof(buffer), timeout_ms)
|
||||
if count:
|
||||
reply = _EchoReply.from_buffer(buffer)
|
||||
if reply.Status == 0:
|
||||
return int(reply.RoundTripTime)
|
||||
return None
|
||||
finally:
|
||||
_iphlpapi.IcmpCloseHandle(handle)
|
||||
|
||||
|
||||
def arp_mac(ip):
|
||||
"""MAC address via ARP – only for hosts in a directly connected subnet."""
|
||||
if sys.platform != "win32":
|
||||
return None
|
||||
mac = (ctypes.c_ubyte * 8)()
|
||||
length = ctypes.c_ulong(8)
|
||||
if _iphlpapi.SendARP(_inet_addr(ip), 0, mac, ctypes.byref(length)) != 0 or length.value < 6:
|
||||
return None
|
||||
value = ":".join(f"{byte:02X}" for byte in mac[:6])
|
||||
return None if value == "00:00:00:00:00:00" else value
|
||||
|
||||
|
||||
def reverse_dns(ip):
|
||||
try:
|
||||
return socket.gethostbyaddr(ip)[0]
|
||||
except (OSError, UnicodeError):
|
||||
return ""
|
||||
|
||||
|
||||
_NBSTAT_QUERY = (b"\x13\x37\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00"
|
||||
b"\x20CKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\x00\x00\x21\x00\x01")
|
||||
|
||||
|
||||
def parse_nbstat(data):
|
||||
"""``(computer name, workgroup, MAC)`` from a NetBIOS node status answer."""
|
||||
if len(data) < 57:
|
||||
return "", "", None
|
||||
count = data[56]
|
||||
offset = 57
|
||||
name = group = ""
|
||||
for _index in range(count):
|
||||
entry = data[offset:offset + 18]
|
||||
if len(entry) < 18:
|
||||
break
|
||||
text = entry[:15].decode("latin-1").strip()
|
||||
suffix, flags = entry[15], struct.unpack(">H", entry[16:18])[0]
|
||||
if suffix == 0x00 and not flags & 0x8000 and not name:
|
||||
name = text
|
||||
elif suffix == 0x00 and flags & 0x8000 and not group:
|
||||
group = text
|
||||
offset += 18
|
||||
mac_bytes = data[offset:offset + 6]
|
||||
mac = ":".join(f"{byte:02X}" for byte in mac_bytes) if len(mac_bytes) == 6 and any(mac_bytes) else None
|
||||
return name, group, mac
|
||||
|
||||
|
||||
def netbios(ip, timeout=0.8):
|
||||
try:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
|
||||
sock.settimeout(timeout)
|
||||
sock.sendto(_NBSTAT_QUERY, (ip, 137))
|
||||
data, _address = sock.recvfrom(2048)
|
||||
except OSError:
|
||||
return "", "", None
|
||||
return parse_nbstat(data)
|
||||
|
||||
|
||||
def tcp_open(ip, port, timeout=0.6):
|
||||
try:
|
||||
with socket.create_connection((ip, port), timeout=timeout):
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def scan_host(ip, ports, timeout=0.6):
|
||||
"""Probe one address. ``alive`` is false when nothing answered."""
|
||||
started = time.monotonic()
|
||||
rtt = ping(ip, int(timeout * 1000) + 200)
|
||||
mac = arp_mac(ip)
|
||||
open_ports = []
|
||||
alive = rtt is not None or mac is not None
|
||||
if not alive:
|
||||
# Windows hosts often block ping; a few typical ports reveal them anyway.
|
||||
for port in QUICK_PORTS:
|
||||
if tcp_open(ip, port, timeout):
|
||||
open_ports.append(port)
|
||||
alive = True
|
||||
break
|
||||
if not alive:
|
||||
return {"ip": ip, "alive": False}
|
||||
with ThreadPoolExecutor(max_workers=min(16, max(1, len(ports)))) as pool:
|
||||
results = pool.map(lambda port: (port, tcp_open(ip, port, timeout)), [p for p in ports if p not in open_ports])
|
||||
open_ports += [port for port, is_open in results if is_open]
|
||||
name, workgroup, nb_mac = netbios(ip)
|
||||
return {
|
||||
"ip": ip, "alive": True, "rtt": rtt, "mac": mac or nb_mac, "dns_name": reverse_dns(ip),
|
||||
"netbios_name": name, "workgroup": workgroup,
|
||||
"ports": [{"port": port, "service": SERVICES.get(port, "")} for port in sorted(open_ports)],
|
||||
"duration": round(time.monotonic() - started, 2),
|
||||
}
|
||||
|
||||
|
||||
def scan(ips, ports, on_result, cancelled=lambda: False, workers=64, timeout=0.6):
|
||||
"""Scan ``ips`` in parallel; ``on_result`` gets every host as soon as it is done."""
|
||||
with ThreadPoolExecutor(max_workers=min(workers, len(ips))) as pool:
|
||||
futures = {pool.submit(scan_host, ip, ports, timeout): ip for ip in ips}
|
||||
for future in as_completed(futures):
|
||||
if cancelled():
|
||||
for pending in futures:
|
||||
pending.cancel()
|
||||
break
|
||||
try:
|
||||
on_result(future.result())
|
||||
except Exception as error: # noqa: BLE001 - one host must not stop the scan
|
||||
on_result({"ip": futures[future], "alive": False, "error": str(error)})
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# NetBox comparison (read only)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def _assigned_name(record):
|
||||
obj = getattr(record, "assigned_object", None)
|
||||
if obj is None:
|
||||
return "", ""
|
||||
for attribute, kind in (("device", "Gerät"), ("virtual_machine", "VM")):
|
||||
parent = getattr(obj, attribute, None)
|
||||
if parent is not None:
|
||||
return getattr(parent, "name", "") or "", kind
|
||||
return getattr(obj, "name", "") or "", ""
|
||||
|
||||
|
||||
def netbox_lookup(nb, ips):
|
||||
"""``{ip: [entry, …]}`` for all NetBox IP addresses of the scanned hosts.
|
||||
|
||||
Queries one ``parent`` filter per /24 instead of one request per host.
|
||||
"""
|
||||
wanted = set(ips)
|
||||
blocks = sorted({str(ipaddress.ip_network(f"{ip}/24", strict=False)) for ip in ips})
|
||||
found = {}
|
||||
for block in blocks:
|
||||
for record in nb.ipam.ip_addresses.filter(parent=block):
|
||||
host = str(record.address).split("/")[0]
|
||||
if host not in wanted:
|
||||
continue
|
||||
name, kind = _assigned_name(record)
|
||||
vrf = getattr(getattr(record, "vrf", None), "name", None)
|
||||
status = getattr(record, "status", None)
|
||||
found.setdefault(host, []).append({
|
||||
"id": record.id,
|
||||
"dns_name": getattr(record, "dns_name", "") or "",
|
||||
"object": name, "object_kind": kind,
|
||||
"vrf": vrf or "", "tenant_id": related_id(record, "tenant"),
|
||||
"tenant": getattr(getattr(record, "tenant", None), "name", "") or "",
|
||||
"status": getattr(status, "label", None) or getattr(status, "value", None) or str(status or ""),
|
||||
"description": getattr(record, "description", "") or "",
|
||||
"url": getattr(record, "display_url", None) or "",
|
||||
})
|
||||
return found
|
||||
|
||||
|
||||
def _short(name):
|
||||
return (name or "").split(".")[0].strip().casefold()
|
||||
|
||||
|
||||
def compare(host, entries):
|
||||
"""Comparison state of one scanned host with its NetBox entries."""
|
||||
alive = host.get("alive")
|
||||
if not entries:
|
||||
return "missing" if alive else "unknown"
|
||||
if not alive:
|
||||
return "offline"
|
||||
names = {_short(host.get("dns_name")), _short(host.get("netbios_name"))} - {""}
|
||||
if not names:
|
||||
return "match" # nothing to compare against – the address is documented
|
||||
for entry in entries:
|
||||
if names & ({_short(entry["dns_name"]), _short(entry["object"])} - {""}):
|
||||
return "match"
|
||||
return "differs"
|
||||
|
||||
|
||||
COMPARE_TEXT = {
|
||||
"match": "stimmt überein",
|
||||
"differs": "Name abweichend",
|
||||
"missing": "nicht in NetBox",
|
||||
"offline": "in NetBox, nicht erreichbar",
|
||||
"unknown": "",
|
||||
"pending": "…",
|
||||
}
|
||||
+890
-38
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,143 @@
|
||||
"""Updates from the Gitea releases of the project.
|
||||
|
||||
The latest release is read anonymously from the Gitea API. The installed
|
||||
version updates by running the new installer silently (it restarts the
|
||||
application afterwards); the portable EXE is swapped in place: Windows allows
|
||||
renaming a running EXE, so the old file is moved aside and removed on the next
|
||||
start.
|
||||
"""
|
||||
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
from netbox_sync import APP_VERSION
|
||||
|
||||
REPOSITORY_API = "https://git.mrblake.cc/api/v1/repos/MrBlake/NetBox-Import-Desktop"
|
||||
LATEST_RELEASE_URL = f"{REPOSITORY_API}/releases/latest"
|
||||
PORTABLE_ASSET = "NetBox VM Import.exe"
|
||||
INSTALLER_ASSET = re.compile(r"(?i)^NetBoxSynchronizer-Setup-[\d.]+\.exe$")
|
||||
INSTALLER_ARGUMENTS = ("/SILENT", "/SUPPRESSMSGBOXES", "/NORESTART", "/CLOSEAPPLICATIONS")
|
||||
_DETACHED = 0x00000008 | 0x00000200 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
|
||||
|
||||
|
||||
class UpdateError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def parse_version(text):
|
||||
"""``"v4.6.0"`` → ``(4, 6, 0)``."""
|
||||
numbers = [int(part) for part in re.findall(r"\d+", text or "")[:3]]
|
||||
return tuple(numbers + [0] * (3 - len(numbers)))
|
||||
|
||||
|
||||
def install_kind():
|
||||
"""``"installer"``, ``"portable"`` or ``None`` when running from source."""
|
||||
if not getattr(sys, "frozen", False):
|
||||
return None
|
||||
exe_dir = Path(sys.executable).resolve().parent
|
||||
bundle = Path(getattr(sys, "_MEIPASS", exe_dir)).resolve()
|
||||
# A one-file (portable) build unpacks itself into a temporary folder.
|
||||
return "installer" if bundle == exe_dir or exe_dir in bundle.parents else "portable"
|
||||
|
||||
|
||||
def check_for_update(current=APP_VERSION, timeout=10):
|
||||
"""Return the newer release or ``None``."""
|
||||
try:
|
||||
response = requests.get(LATEST_RELEASE_URL, timeout=timeout, headers={"Accept": "application/json"})
|
||||
response.raise_for_status()
|
||||
release = response.json()
|
||||
except (requests.RequestException, ValueError) as error:
|
||||
raise UpdateError(f"Update-Server nicht erreichbar: {error}") from error
|
||||
if release.get("draft") or release.get("prerelease"):
|
||||
return None
|
||||
tag = release.get("tag_name") or ""
|
||||
if parse_version(tag) <= parse_version(current):
|
||||
return None
|
||||
return {
|
||||
"version": tag.lstrip("vV"),
|
||||
"name": release.get("name") or tag,
|
||||
"notes": release.get("body") or "",
|
||||
"page": release.get("html_url") or "",
|
||||
"assets": {asset["name"]: {"url": asset["browser_download_url"], "size": int(asset.get("size") or 0)}
|
||||
for asset in release.get("assets", []) if asset.get("browser_download_url")},
|
||||
}
|
||||
|
||||
|
||||
def pick_asset(release, kind):
|
||||
"""``(name, asset)`` matching the running installation, or ``None``."""
|
||||
for name, asset in release["assets"].items():
|
||||
if kind == "portable" and name.casefold() == PORTABLE_ASSET.casefold():
|
||||
return name, asset
|
||||
if kind == "installer" and INSTALLER_ASSET.match(name):
|
||||
return name, asset
|
||||
return None
|
||||
|
||||
|
||||
def download(asset, target, progress=None, cancelled=None, timeout=30):
|
||||
"""Stream ``asset`` to ``target``; the size is verified before the file is kept."""
|
||||
target = Path(target)
|
||||
partial = target.with_name(target.name + ".part")
|
||||
try:
|
||||
with requests.get(asset["url"], stream=True, timeout=timeout) as response:
|
||||
response.raise_for_status()
|
||||
total = asset.get("size") or int(response.headers.get("Content-Length") or 0)
|
||||
done = 0
|
||||
with partial.open("wb") as handle:
|
||||
for chunk in response.iter_content(256 * 1024):
|
||||
if cancelled and cancelled():
|
||||
raise UpdateError("Download abgebrochen.")
|
||||
handle.write(chunk)
|
||||
done += len(chunk)
|
||||
if progress:
|
||||
progress(done, total)
|
||||
except requests.RequestException as error:
|
||||
partial.unlink(missing_ok=True)
|
||||
raise UpdateError(f"Download fehlgeschlagen: {error}") from error
|
||||
except BaseException:
|
||||
partial.unlink(missing_ok=True)
|
||||
raise
|
||||
if total and done != total:
|
||||
partial.unlink(missing_ok=True)
|
||||
raise UpdateError(f"Download unvollständig ({done} von {total} Bytes).")
|
||||
partial.replace(target)
|
||||
return target
|
||||
|
||||
|
||||
def portable_download_path():
|
||||
exe = Path(sys.executable)
|
||||
return exe.with_name(exe.stem + ".new.exe")
|
||||
|
||||
|
||||
def apply_portable(new_exe):
|
||||
"""Swap the running portable EXE for ``new_exe`` and start it."""
|
||||
exe = Path(sys.executable)
|
||||
old = exe.with_name(exe.stem + ".old.exe")
|
||||
old.unlink(missing_ok=True)
|
||||
exe.replace(old)
|
||||
try:
|
||||
Path(new_exe).replace(exe)
|
||||
except OSError:
|
||||
old.replace(exe)
|
||||
raise
|
||||
subprocess.Popen([str(exe)], close_fds=True, creationflags=_DETACHED) # noqa: S603
|
||||
|
||||
|
||||
def apply_installer(setup_exe):
|
||||
"""Run the installer silently; it closes and restarts the application."""
|
||||
subprocess.Popen([str(setup_exe), *INSTALLER_ARGUMENTS], close_fds=True, creationflags=_DETACHED) # noqa: S603
|
||||
|
||||
|
||||
def remove_leftovers():
|
||||
"""Delete the previous portable EXE left behind by an update."""
|
||||
if install_kind() != "portable":
|
||||
return
|
||||
exe = Path(sys.executable)
|
||||
for leftover in (exe.with_name(exe.stem + ".old.exe"), portable_download_path()):
|
||||
try:
|
||||
leftover.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
@@ -87,7 +87,7 @@ def load_vmware_source(source, log=_noop):
|
||||
if properties.get("name") and not properties.get("config.template"):
|
||||
vm = _normalize_vmware_vm(properties, source, vim)
|
||||
host = properties.get("runtime.host")
|
||||
vm["cluster"] = host_clusters.get(getattr(host, "_moId", None), "")
|
||||
vm["cluster"], vm["host"] = host_clusters.get(getattr(host, "_moId", None), ("", ""))
|
||||
normalized.append(vm)
|
||||
return normalized
|
||||
finally:
|
||||
@@ -97,14 +97,14 @@ def load_vmware_source(source, log=_noop):
|
||||
|
||||
|
||||
def _vmware_host_clusters(content, vim):
|
||||
"""Map ESXi host IDs to their cluster name (or the host name when standalone)."""
|
||||
"""Map ESXi host IDs to ``(cluster name, host name)``; standalone hosts use their own name as cluster."""
|
||||
result = {}
|
||||
view = content.viewManager.CreateContainerView(content.rootFolder, [vim.ComputeResource], True)
|
||||
try:
|
||||
for resource in view.view:
|
||||
name = resource.name
|
||||
for host in resource.host or []:
|
||||
result[host._moId] = name
|
||||
result[host._moId] = (name, host.name)
|
||||
finally:
|
||||
view.Destroy()
|
||||
return result
|
||||
@@ -205,6 +205,7 @@ def load_proxmox_source(source, log=_noop):
|
||||
try:
|
||||
guest = _normalize_proxmox_guest(session, source, resource)
|
||||
guest["cluster"] = cluster_name or resource.get("node", "")
|
||||
guest["host"] = resource.get("node", "")
|
||||
result.append(guest)
|
||||
except Exception as error: # noqa: BLE001 - one broken guest must not stop the source
|
||||
log(f"{source['name']} / VMID {resource.get('vmid')}: {error}", "warning")
|
||||
|
||||
@@ -28,6 +28,11 @@ def cluster_key(vm):
|
||||
return f"{vm.get('source_id', vm.get('source', ''))}:{vm.get('cluster', '')}"
|
||||
|
||||
|
||||
def host_key(vm):
|
||||
"""Identifies the hypervisor host (ESXi host / Proxmox node) of a VM across sources."""
|
||||
return f"{vm.get('source', '')}:{vm.get('host', '')}"
|
||||
|
||||
|
||||
def _compact(name):
|
||||
return re.sub(r"[^0-9a-z]", "", (name or "").casefold())
|
||||
|
||||
@@ -60,6 +65,7 @@ class VMSyncEngine:
|
||||
self.tenants = {}
|
||||
self.vrfs = []
|
||||
self.platforms = []
|
||||
self.devices = {}
|
||||
self.existing_vms = {}
|
||||
self._reset_run_state()
|
||||
|
||||
@@ -86,12 +92,19 @@ class VMSyncEngine:
|
||||
if tenant_id and tenant_name:
|
||||
self.cluster_tenants[cluster.name] = {"id": tenant_id, "name": tenant_name}
|
||||
self.tenants.setdefault(tenant_name, tenant_id)
|
||||
self.devices = {}
|
||||
for device in self.nb.dcim.devices.all():
|
||||
if device.name:
|
||||
self.devices[device.id] = {
|
||||
"name": device.name, "site": related_name(device, "site") or "",
|
||||
"cluster_id": related_id(device, "cluster"),
|
||||
}
|
||||
self.existing_vms = {}
|
||||
for vm in self.nb.virtualization.virtual_machines.filter(brief=True):
|
||||
self.existing_vms.setdefault(vm.name, []).append(vm.id)
|
||||
self.log(
|
||||
f"NetBox: {len(self.clusters)} Cluster, {len(self.tenants)} Mandanten, "
|
||||
f"{len(self.vrfs)} VRFs, {sum(map(len, self.existing_vms.values()))} VMs"
|
||||
f"{len(self.vrfs)} VRFs, {len(self.devices)} Geräte, {sum(map(len, self.existing_vms.values()))} VMs"
|
||||
)
|
||||
|
||||
def tenant_vrfs(self, tenant_id):
|
||||
@@ -301,7 +314,28 @@ class VMSyncEngine:
|
||||
raise RuntimeError(f"IP-Adresse {host_address} ist in dieser VRF mehrfach vorhanden")
|
||||
return candidates[0] if candidates else None
|
||||
|
||||
def sync_vm(self, source_vm, cluster_id, tenant_id, vrf_id):
|
||||
def device_label(self, device_id):
|
||||
device = self.devices[device_id]
|
||||
return f"{device['name']} ({device['site']})" if device["site"] else device["name"]
|
||||
|
||||
def prepare_host_device(self, device_id, cluster_id):
|
||||
"""Make sure the device may host VMs of the cluster; NetBox requires both to match.
|
||||
|
||||
A device without cluster is added to it. Returns ``False`` if it belongs to another cluster.
|
||||
"""
|
||||
device = self.devices[device_id]
|
||||
if device["cluster_id"] == cluster_id:
|
||||
return True
|
||||
if device["cluster_id"]:
|
||||
self.log(f"Gerät {device['name']} gehört in NetBox zu einem anderen Cluster – "
|
||||
"wird nicht als Host eingetragen", "warning")
|
||||
return False
|
||||
self.nb.dcim.devices.get(device_id).update({"cluster": cluster_id})
|
||||
device["cluster_id"] = cluster_id
|
||||
self.log(f"Gerät {device['name']} dem Cluster zugeordnet", "success")
|
||||
return True
|
||||
|
||||
def sync_vm(self, source_vm, cluster_id, tenant_id, vrf_id, device_id=None):
|
||||
"""Create or update one VM. Returns ``"created"`` or ``"updated"``."""
|
||||
payload = {
|
||||
"name": source_vm["name"], "cluster": cluster_id, "status": source_vm["status"],
|
||||
@@ -311,6 +345,8 @@ class VMSyncEngine:
|
||||
platform_id = self.get_platform_id(source_vm.get("guest_os"))
|
||||
if platform_id:
|
||||
payload["platform"] = platform_id
|
||||
if device_id and self.prepare_host_device(device_id, cluster_id):
|
||||
payload["device"] = device_id
|
||||
|
||||
netbox_vm = self._find_vm(source_vm["name"], cluster_id)
|
||||
if netbox_vm:
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
"""In-process access to WinRM (WSMan.Automation) and Active Directory (ADSI).
|
||||
|
||||
Both run through Windows COM inside the application process. No PowerShell
|
||||
or other helper process is started – endpoint protection such as Sophos
|
||||
"Application Lockdown" terminates applications that spawn script hosts.
|
||||
Authentication uses the Windows stack (Kerberos/Negotiate) with either the
|
||||
signed-in user or explicit credentials.
|
||||
"""
|
||||
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
WMI_CIMV2 = "http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/"
|
||||
STD_REG_PROV = "http://schemas.microsoft.com/wbem/wsman/1/wmi/root/default/StdRegProv"
|
||||
XSI_NIL = "{http://www.w3.org/2001/XMLSchema-instance}nil"
|
||||
HKEY_LOCAL_MACHINE = 2147483650
|
||||
|
||||
# WSManSessionFlags
|
||||
FLAG_UTF8 = 0x1
|
||||
FLAG_CRED_USERNAME_PASSWORD = 0x1000
|
||||
FLAG_USE_NEGOTIATE = 0x20000
|
||||
FLAG_USE_SSL = 0x8000000
|
||||
|
||||
ADS_SECURE_AUTHENTICATION = 0x1
|
||||
ADS_USE_SEALING = 0x40
|
||||
|
||||
|
||||
class WSManError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _com():
|
||||
import pythoncom
|
||||
import pywintypes
|
||||
import win32com.client
|
||||
|
||||
return pythoncom, pywintypes, win32com.client
|
||||
|
||||
|
||||
class com_thread:
|
||||
"""Initialise COM for the calling worker thread."""
|
||||
|
||||
def __enter__(self):
|
||||
pythoncom = _com()[0]
|
||||
pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
|
||||
return self
|
||||
|
||||
def __exit__(self, *_exc):
|
||||
_com()[0].CoUninitialize()
|
||||
return False
|
||||
|
||||
|
||||
def _local(tag):
|
||||
return tag.rsplit("}", 1)[-1]
|
||||
|
||||
|
||||
def parse_instance(text):
|
||||
"""Turn a WS-Man CIM instance (XML) into ``{property: value or [values]}``."""
|
||||
root = ET.fromstring(text)
|
||||
result = {}
|
||||
for child in root:
|
||||
name = _local(child.tag)
|
||||
if child.get(XSI_NIL) == "true":
|
||||
value = None
|
||||
elif len(child):
|
||||
value = (child[0].text or "").strip() # e.g. <cim:Datetime>
|
||||
else:
|
||||
value = (child.text or "").strip()
|
||||
if name in result:
|
||||
if not isinstance(result[name], list):
|
||||
result[name] = [result[name]]
|
||||
result[name].append(value)
|
||||
else:
|
||||
result[name] = value
|
||||
return result
|
||||
|
||||
|
||||
def as_list(value):
|
||||
if value is None:
|
||||
return []
|
||||
return value if isinstance(value, list) else [value]
|
||||
|
||||
|
||||
def as_bool(value):
|
||||
return str(value).strip().lower() == "true"
|
||||
|
||||
|
||||
def as_int(value):
|
||||
try:
|
||||
return int(str(value).strip())
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
def _error_text(error, session=None):
|
||||
"""Readable message (with HRESULT) from a COM error or a WSMan fault."""
|
||||
details = ""
|
||||
info = getattr(error, "excepinfo", None)
|
||||
if session is not None:
|
||||
try:
|
||||
fault = session.Error or ""
|
||||
except Exception: # noqa: BLE001 - the session may already be unusable
|
||||
fault = ""
|
||||
if fault:
|
||||
try:
|
||||
root = ET.fromstring(fault)
|
||||
code = root.get("Code", "")
|
||||
message = " ".join(text.strip() for text in root.itertext() if text.strip())
|
||||
details = f"{message} (WSMan {code})" if code else message
|
||||
except ET.ParseError:
|
||||
details = fault
|
||||
if not details:
|
||||
details = (info[2] if info and len(info) > 2 and info[2] else "") or str(error)
|
||||
hresult = getattr(error, "hresult", None)
|
||||
if isinstance(info, tuple) and len(info) > 5 and info[5]:
|
||||
hresult = info[5]
|
||||
if isinstance(hresult, int):
|
||||
details = f"{details} [0x{hresult & 0xFFFFFFFF:08X}]"
|
||||
return details
|
||||
|
||||
|
||||
class Session:
|
||||
def __init__(self, host, credential=None, use_ssl=False, port=None, timeout=30):
|
||||
_pythoncom, self._pywintypes, client = _com()
|
||||
self.wsman = client.Dispatch("WSMan.Automation")
|
||||
flags = FLAG_UTF8 | FLAG_USE_NEGOTIATE
|
||||
options = None
|
||||
if credential is not None:
|
||||
options = self.wsman.CreateConnectionOptions()
|
||||
options.UserName = credential.username
|
||||
options.Password = credential.password
|
||||
flags |= FLAG_CRED_USERNAME_PASSWORD
|
||||
if use_ssl:
|
||||
flags |= FLAG_USE_SSL
|
||||
scheme = "https" if use_ssl else "http"
|
||||
port = port or (5986 if use_ssl else 5985)
|
||||
self.session = self.wsman.CreateSession(f"{scheme}://{host}:{port}/wsman", flags, options)
|
||||
self.session.Timeout = int(timeout * 1000)
|
||||
|
||||
def _fail(self, error):
|
||||
raise WSManError(_error_text(error, self.session)) from error
|
||||
|
||||
def enumerate(self, cim_class):
|
||||
try:
|
||||
enumerator = self.session.Enumerate(WMI_CIMV2 + cim_class, "", "", 0)
|
||||
items = []
|
||||
while not enumerator.AtEndOfStream:
|
||||
items.append(parse_instance(enumerator.ReadItem()))
|
||||
return items
|
||||
except self._pywintypes.com_error as error:
|
||||
self._fail(error)
|
||||
|
||||
def first(self, cim_class):
|
||||
items = self.enumerate(cim_class)
|
||||
return items[0] if items else {}
|
||||
|
||||
def registry_string(self, key, value):
|
||||
parameters = (
|
||||
f'<p:GetStringValue_INPUT xmlns:p="{STD_REG_PROV}">'
|
||||
f"<p:hDefKey>{HKEY_LOCAL_MACHINE}</p:hDefKey>"
|
||||
f"<p:sSubKeyName>{key}</p:sSubKeyName><p:sValueName>{value}</p:sValueName>"
|
||||
"</p:GetStringValue_INPUT>"
|
||||
)
|
||||
try:
|
||||
result = parse_instance(self.session.Invoke("GetStringValue", STD_REG_PROV, parameters, 0))
|
||||
except (self._pywintypes.com_error, ET.ParseError):
|
||||
return ""
|
||||
return result.get("sValue") or ""
|
||||
|
||||
|
||||
def _datetime(value):
|
||||
"""CIM datetimes arrive as ISO strings; keep second precision."""
|
||||
return (value or "")[:19]
|
||||
|
||||
|
||||
def query_client(host, credential=None, use_ssl=False, port=None, timeout=30):
|
||||
"""Read inventory data from one client. Returns the raw result dict used by ``apply_scan``."""
|
||||
result = {"host": host, "ok": False}
|
||||
try:
|
||||
session = Session(host, credential, use_ssl, port, timeout)
|
||||
system = session.first("Win32_ComputerSystem")
|
||||
os_info = session.first("Win32_OperatingSystem")
|
||||
bios = session.first("Win32_BIOS")
|
||||
product = session.first("Win32_ComputerSystemProduct")
|
||||
enclosure = session.first("Win32_SystemEnclosure")
|
||||
processors = session.enumerate("Win32_Processor")
|
||||
adapters = {as_int(item.get("InterfaceIndex")): item for item in session.enumerate("Win32_NetworkAdapter")
|
||||
if as_bool(item.get("PhysicalAdapter"))}
|
||||
nics = []
|
||||
for config in session.enumerate("Win32_NetworkAdapterConfiguration"):
|
||||
if not as_bool(config.get("IPEnabled")):
|
||||
continue
|
||||
adapter = adapters.get(as_int(config.get("InterfaceIndex")))
|
||||
nics.append({
|
||||
"name": (adapter or {}).get("NetConnectionID") or "",
|
||||
"description": config.get("Description") or "",
|
||||
"mac": config.get("MACAddress") or "",
|
||||
"ips": as_list(config.get("IPAddress")),
|
||||
"masks": as_list(config.get("IPSubnet")),
|
||||
"gateway": as_list(config.get("DefaultIPGateway")),
|
||||
"dhcp": as_bool(config.get("DHCPEnabled")),
|
||||
"physical": adapter is not None,
|
||||
"speed": as_int((adapter or {}).get("Speed")),
|
||||
})
|
||||
display = session.registry_string(r"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "DisplayVersion")
|
||||
except WSManError as error:
|
||||
result["error"] = str(error)
|
||||
return result
|
||||
except Exception as error: # noqa: BLE001 - one broken client must not stop the scan
|
||||
result["error"] = _error_text(error)
|
||||
return result
|
||||
result.update({
|
||||
"ok": True,
|
||||
"name": system.get("Name") or "",
|
||||
"domain": system.get("Domain") or "",
|
||||
"part_of_domain": as_bool(system.get("PartOfDomain")),
|
||||
"manufacturer": system.get("Manufacturer") or "",
|
||||
"model": system.get("Model") or "",
|
||||
"product_name": product.get("Name") or "",
|
||||
"product_version": product.get("Version") or "",
|
||||
"serial": bios.get("SerialNumber") or "",
|
||||
"bios_version": bios.get("SMBIOSBIOSVersion") or "",
|
||||
"chassis": [as_int(value) for value in as_list(enclosure.get("ChassisTypes"))],
|
||||
"user": system.get("UserName") or "",
|
||||
"memory": as_int(system.get("TotalPhysicalMemory")),
|
||||
"cpu": (processors[0].get("Name") or "") if processors else "",
|
||||
"cores": sum(as_int(item.get("NumberOfCores")) for item in processors),
|
||||
"os": os_info.get("Caption") or "",
|
||||
"os_version": os_info.get("Version") or "",
|
||||
"os_build": os_info.get("BuildNumber") or "",
|
||||
"os_display_version": display,
|
||||
"os_architecture": os_info.get("OSArchitecture") or "",
|
||||
"installed": _datetime(os_info.get("InstallDate")),
|
||||
"last_boot": _datetime(os_info.get("LastBootUpTime")),
|
||||
"nics": nics,
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Active Directory (ADSI via ADODB)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
AD_ATTRIBUTES = ("name", "dNSHostName", "operatingSystem", "operatingSystemVersion", "lastLogonTimestamp",
|
||||
"distinguishedName", "description", "userAccountControl")
|
||||
|
||||
|
||||
def _field(record, name):
|
||||
value = record.Fields(name).Value
|
||||
if isinstance(value, (tuple, list)):
|
||||
value = value[0] if value else None
|
||||
return value
|
||||
|
||||
|
||||
def _large_integer(value):
|
||||
if value is None:
|
||||
return 0
|
||||
if isinstance(value, int):
|
||||
return value
|
||||
try:
|
||||
return (int(value.HighPart) << 32) + (int(value.LowPart) & 0xFFFFFFFF)
|
||||
except Exception: # noqa: BLE001 - unexpected COM type
|
||||
return 0
|
||||
|
||||
|
||||
def search_ad(location, ldap_filter, credential=None):
|
||||
"""Query computer objects. ``location`` is ``server/base`` or ``base`` (without ``LDAP://``)."""
|
||||
_pythoncom, pywintypes, client = _com()
|
||||
try:
|
||||
connection = client.Dispatch("ADODB.Connection")
|
||||
connection.Provider = "ADsDSOObject"
|
||||
if credential is not None:
|
||||
connection.Properties("User ID").Value = credential.username
|
||||
connection.Properties("Password").Value = credential.password
|
||||
connection.Properties("Encrypt Password").Value = True
|
||||
connection.Properties("ADSI Flag").Value = ADS_SECURE_AUTHENTICATION | ADS_USE_SEALING
|
||||
connection.Open("Active Directory Provider")
|
||||
command = client.Dispatch("ADODB.Command")
|
||||
command.ActiveConnection = connection
|
||||
command.Properties("Page Size").Value = 1000
|
||||
command.CommandText = f"<LDAP://{location}>;{ldap_filter};{','.join(AD_ATTRIBUTES)};subtree"
|
||||
records = command.Execute()[0]
|
||||
rows = []
|
||||
while not records.EOF:
|
||||
rows.append({
|
||||
"name": _field(records, "name") or "",
|
||||
"dns": _field(records, "dNSHostName") or "",
|
||||
"os": _field(records, "operatingSystem") or "",
|
||||
"os_version": _field(records, "operatingSystemVersion") or "",
|
||||
"last_logon": _large_integer(_field(records, "lastLogonTimestamp")),
|
||||
"dn": _field(records, "distinguishedName") or "",
|
||||
"description": _field(records, "description") or "",
|
||||
"disabled": bool(as_int(_field(records, "userAccountControl")) & 2),
|
||||
})
|
||||
records.MoveNext()
|
||||
connection.Close()
|
||||
return rows
|
||||
except pywintypes.com_error as error:
|
||||
raise WSManError(_error_text(error)) from error
|
||||
@@ -17,6 +17,7 @@ from netbox_sync.core.switches import (
|
||||
PLATFORMS,
|
||||
describe_snapshot,
|
||||
discover_switch,
|
||||
plan_switch_sync,
|
||||
suggest_platform,
|
||||
sync_snapshot_to_netbox,
|
||||
)
|
||||
@@ -24,7 +25,7 @@ from netbox_sync.core.virtualization import load_source
|
||||
from netbox_sync.core.vm_sync import VMSyncEngine
|
||||
from netbox_sync.ui import widgets
|
||||
from netbox_sync.ui.client_dialogs import ClientPreviewDialog, ClientTargetDialog
|
||||
from netbox_sync.ui.dialogs import SyncPreviewDialog
|
||||
from netbox_sync.ui.dialogs import SwitchMappingDialog, SyncPreviewDialog
|
||||
from netbox_sync.ui.tasks import area_log, logger
|
||||
|
||||
|
||||
@@ -404,7 +405,11 @@ class Actions:
|
||||
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])
|
||||
# VLAN and network decisions are shared by all switches of the profile.
|
||||
vlan_map = self.state.profile.setdefault("vlan_map", {})
|
||||
network_map = self.state.profile.setdefault("network_map", {})
|
||||
items = [(dict(by_id[switch_id], vlan_map=dict(vlan_map), network_map=dict(network_map)),
|
||||
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")
|
||||
@@ -412,8 +417,56 @@ class Actions:
|
||||
connect = self._connector()
|
||||
log = area_log("switch")
|
||||
|
||||
def preview(ctx):
|
||||
def plan(ctx):
|
||||
nb = connect(ctx)
|
||||
plans = []
|
||||
for index, (switch, snapshot) in enumerate(items):
|
||||
ctx.progress(index, len(items), switch["name"])
|
||||
ctx.log(f"{switch['name']}: ordne Schnittstellen und Nachbarn zu …")
|
||||
plans.append((switch, plan_switch_sync(nb, switch, snapshot)))
|
||||
return nb, plans
|
||||
|
||||
def review(result):
|
||||
nb, plans = result
|
||||
self.state.set_netbox(nb, "ok", f"Verbunden · NetBox {nb.netbox_version}")
|
||||
reviewable = [(switch, item) for switch, item in plans if not item["error"]]
|
||||
needs_review = any(
|
||||
any(entry["method"] not in ("name", "new") or (entry["method"] == "new" and entry["physical"])
|
||||
for entry in item["interfaces"]) or (create_cables and item["neighbors"])
|
||||
or any(not member["device_id"] for member in item.get("stack", []))
|
||||
or any(not network["stored"] and not network["existing"] for network in item["networks"])
|
||||
or any(not vlan["stored"] and vlan["method"] in ("new", "ambiguous") for vlan in item["vlans"])
|
||||
for _switch, item in reviewable)
|
||||
|
||||
def ask():
|
||||
# Started after the planning task has finished, so the next
|
||||
# task is not rejected as "still busy".
|
||||
if needs_review:
|
||||
dialog = SwitchMappingDialog(self.window, reviewable, create_cables)
|
||||
if not dialog.exec():
|
||||
return
|
||||
stored = {switch["id"]: switch for switch in self.state.switches}
|
||||
vlan_map.clear()
|
||||
vlan_map.update(dialog.vlan_map)
|
||||
network_map.clear()
|
||||
network_map.update(dialog.network_map)
|
||||
for switch, _snapshot in items:
|
||||
choices = dialog.result.get(switch["id"])
|
||||
if choices:
|
||||
switch.update(choices)
|
||||
if switch["id"] in stored:
|
||||
stored[switch["id"]].update(choices)
|
||||
switch.update(vlan_map=dict(vlan_map), network_map=dict(network_map))
|
||||
for legacy in ("network_vrfs", "create_prefixes", "create_vlans"):
|
||||
switch.pop(legacy, None)
|
||||
stored.get(switch["id"], {}).pop(legacy, None)
|
||||
self.state.touch()
|
||||
self.state.switches_changed.emit() # ignored VLANs vanish from the VLAN column
|
||||
self.tasks.run(lambda ctx: preview(ctx, nb), title="Änderungen berechnen", area="switch",
|
||||
on_success=show_preview, on_error=self._netbox_failed)
|
||||
QTimer.singleShot(0, ask)
|
||||
|
||||
def preview(ctx, nb):
|
||||
reports = []
|
||||
for index, (switch, snapshot) in enumerate(items):
|
||||
ctx.progress(index, len(items), switch["name"])
|
||||
@@ -423,7 +476,6 @@ class Actions:
|
||||
|
||||
def show_preview(result):
|
||||
nb, reports = result
|
||||
self.state.set_netbox(nb, "ok", f"Verbunden · NetBox {nb.netbox_version}")
|
||||
|
||||
def ask():
|
||||
# Opened after the preview task has fully finished, so the
|
||||
@@ -433,7 +485,7 @@ class Actions:
|
||||
self._apply_switch_sync(nb, items, create_cables, log)
|
||||
QTimer.singleShot(0, ask)
|
||||
|
||||
self.tasks.run(preview, title="Änderungen berechnen", area="switch", on_success=show_preview,
|
||||
self.tasks.run(plan, title="Zuordnung ermitteln", area="switch", on_success=review,
|
||||
on_error=self._netbox_failed)
|
||||
|
||||
def _apply_switch_sync(self, nb, items, create_cables, log):
|
||||
|
||||
@@ -84,6 +84,7 @@ def main():
|
||||
hints.colorSchemeChanged.connect(lambda _scheme: theme.mode == "system" and theme.apply())
|
||||
install_excepthook(lambda: window)
|
||||
window.show()
|
||||
window.updates.check_on_start()
|
||||
return app.exec()
|
||||
|
||||
|
||||
|
||||
@@ -36,9 +36,9 @@ class ClientTargetDialog(_Dialog):
|
||||
else:
|
||||
self.role.setEditText(remembered)
|
||||
form.addRow("Geräterolle *", self.role)
|
||||
self.tenant = SearchableComboBox("Kein Mandant")
|
||||
self.tenant.set_items([("Kein Mandant", None)] + list(engine.tenants), options.get("netbox_tenant"))
|
||||
form.addRow("Mandant", self.tenant)
|
||||
self.tenant = SearchableComboBox("Mandant wählen …")
|
||||
self.tenant.set_items(list(engine.tenants), options.get("netbox_tenant"))
|
||||
form.addRow("Mandant *", self.tenant)
|
||||
self.root.addLayout(form)
|
||||
self.interfaces = checkbox("Netzwerkkarten, MAC- und IP-Adressen übernehmen",
|
||||
options.get("sync_interfaces", True),
|
||||
@@ -60,16 +60,21 @@ class ClientTargetDialog(_Dialog):
|
||||
role_text = self.role.currentText().strip()
|
||||
role = self.role.valid_data()
|
||||
_mark_invalid(self.site, site is None)
|
||||
tenant = self.tenant.valid_data()
|
||||
_mark_invalid(self.role, not role_text)
|
||||
_mark_invalid(self.tenant, tenant is None)
|
||||
if site is None:
|
||||
self.show_error("Bitte einen vorhandenen Standort auswählen.")
|
||||
return
|
||||
if not role_text:
|
||||
self.show_error("Bitte eine Geräterolle auswählen oder einen Namen für eine neue Rolle eingeben.")
|
||||
return
|
||||
if tenant is None:
|
||||
self.show_error("Bitte einen Mandanten auswählen – alle Objekte in NetBox brauchen einen Mandanten.")
|
||||
return
|
||||
self.result = {
|
||||
"site_id": site, "role_id": role, "role_name": role_text,
|
||||
"tenant_id": self.tenant.valid_data(),
|
||||
"tenant_id": tenant,
|
||||
"interfaces": self.interfaces.isChecked(), "update_existing": self.update_existing.isChecked(),
|
||||
}
|
||||
super().accept()
|
||||
|
||||
+436
-3
@@ -3,7 +3,7 @@
|
||||
import uuid
|
||||
|
||||
from PySide6.QtCore import QThreadPool, Qt
|
||||
from PySide6.QtGui import QGuiApplication
|
||||
from PySide6.QtGui import QColor, QGuiApplication
|
||||
from PySide6.QtWidgets import (
|
||||
QButtonGroup,
|
||||
QComboBox,
|
||||
@@ -16,6 +16,8 @@ from PySide6.QtWidgets import (
|
||||
QPlainTextEdit,
|
||||
QPushButton,
|
||||
QSpinBox,
|
||||
QTableWidget,
|
||||
QTableWidgetItem,
|
||||
QTabWidget,
|
||||
QTreeWidget,
|
||||
QTreeWidgetItem,
|
||||
@@ -24,7 +26,7 @@ from PySide6.QtWidgets import (
|
||||
)
|
||||
|
||||
from netbox_sync.core.config import known_hosts_path
|
||||
from netbox_sync.core.switches import PLATFORMS, forget_host_key
|
||||
from netbox_sync.core.switches import MATCH_METHODS, PLATFORMS, VLAN_METHODS, forget_host_key
|
||||
from netbox_sync.core.virtualization import test_source
|
||||
from netbox_sync.ui.icons import icon
|
||||
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
|
||||
@@ -525,6 +527,10 @@ class SyncPreviewDialog(_Dialog):
|
||||
(f"{totals.get('interfaces_updated', 0)} Interfaces geändert", "info"),
|
||||
(f"{totals.get('ips_created', 0) + totals.get('ips_updated', 0)} IP-Adressen", "info"),
|
||||
]
|
||||
for key, text in (("vrfs_created", "VRF(s) neu"), ("prefixes_created", "Prefix(e) neu"),
|
||||
("vlans_created", "VLAN(s) neu")):
|
||||
if totals.get(key):
|
||||
items.append((f"{totals[key]} {text}", "info"))
|
||||
if create_cables:
|
||||
items.append((f"{totals.get('cables_created', 0)} Kabel", "info"))
|
||||
errors = sum(len(report["errors"]) for _switch, report in reports)
|
||||
@@ -554,6 +560,10 @@ class SyncPreviewDialog(_Dialog):
|
||||
child = QTreeWidgetItem([error])
|
||||
child.setIcon(0, icon("warning", theme.color("danger")))
|
||||
top.addChild(child)
|
||||
for note in report.get("notes", []):
|
||||
child = QTreeWidgetItem([note])
|
||||
child.setIcon(0, icon("info", theme.color("warning")))
|
||||
top.addChild(child)
|
||||
for change in changes[:2000]:
|
||||
top.addChild(QTreeWidgetItem([change]))
|
||||
tree.addTopLevelItem(top)
|
||||
@@ -566,10 +576,433 @@ class SyncPreviewDialog(_Dialog):
|
||||
self.root.addWidget(buttons)
|
||||
|
||||
|
||||
class SwitchMappingDialog(_Dialog):
|
||||
"""Review interface mapping and neighbor devices before computing changes.
|
||||
|
||||
``plans`` is a list of ``(switch, plan)`` from ``plan_switch_sync``. After
|
||||
acceptance ``result`` maps switch IDs to ``interface_map`` and
|
||||
``neighbor_devices`` to be stored in the profile.
|
||||
"""
|
||||
|
||||
NEW = "\x00new"
|
||||
|
||||
def __init__(self, parent, plans, create_cables):
|
||||
super().__init__(parent, "Zuordnung prüfen",
|
||||
"Schnittstellen, Nachbarn, Netze und VLANs prüfen und bei Bedarf korrigieren. Neue Objekte "
|
||||
"erhalten immer den Mandanten des Switches – die Auswahl wird im Profil gespeichert.",
|
||||
width=820)
|
||||
self.resize(1120, 680)
|
||||
self.plans = plans
|
||||
self.result = None
|
||||
# Profile-wide VLAN decisions; every switch config carries the same map.
|
||||
self.previous_vlan_map = dict((plans[0][0].get("vlan_map") if plans else None) or {})
|
||||
self.vlan_map = dict(self.previous_vlan_map)
|
||||
self.previous_network_map = dict((plans[0][0].get("network_map") if plans else None) or {})
|
||||
self.network_map = dict(self.previous_network_map)
|
||||
self._new_vrf_names = []
|
||||
tabs = QTabWidget()
|
||||
|
||||
# Stack ---------------------------------------------------------------
|
||||
self.stack_rows = []
|
||||
stacks = [(switch, plan) for switch, plan in plans if plan.get("stack")]
|
||||
if stacks:
|
||||
stack_page = QWidget()
|
||||
stack_layout = QVBoxLayout(stack_page)
|
||||
stack_layout.setContentsMargins(0, 12, 0, 0)
|
||||
stack_layout.addWidget(label(
|
||||
"Der Switch ist ein Stack. Jedes Mitglied wird einem eigenen NetBox-Gerät zugeordnet, die Ports "
|
||||
"kommen an das Gerät ihres Mitglieds (2/1/5 an das Gerät von Mitglied 2). LAGs und VLAN-Interfaces "
|
||||
"bleiben am Gerät des Switch-Eintrags. Vorschlag: Positionen im Virtual Chassis von NetBox.",
|
||||
muted=True, wrap=True))
|
||||
self.stack_table = QTableWidget(0, 5)
|
||||
self.stack_table.setHorizontalHeaderLabels(["Switch", "Mitglied", "Modell", "Ports", "NetBox-Gerät"])
|
||||
for switch, plan in stacks:
|
||||
items = [("– Ports überspringen –", 0)] + [(device["name"], device["id"]) for device in plan["devices"]]
|
||||
for entry in plan["stack"]:
|
||||
row = self.stack_table.rowCount()
|
||||
self.stack_table.insertRow(row)
|
||||
texts = (switch["name"], str(entry["member"]), entry["model"], str(entry["ports"]))
|
||||
for column, text in enumerate(texts):
|
||||
self.stack_table.setItem(row, column, QTableWidgetItem(text))
|
||||
combo = SearchableComboBox("Gerät suchen …")
|
||||
combo.set_items(items, entry["device_id"] or 0)
|
||||
self.stack_table.setCellWidget(row, 4, combo)
|
||||
self.stack_rows.append((switch, entry, combo))
|
||||
self._prepare_table(self.stack_table, (160, 80, 120, 70, 320))
|
||||
stack_layout.addWidget(self.stack_table, 1)
|
||||
open_members = sum(1 for _switch, entry, _combo in self.stack_rows if not entry["device_id"])
|
||||
tabs.addTab(stack_page, f"Stack ({open_members} ohne Gerät)" if open_members else "Stack")
|
||||
|
||||
# Interfaces --------------------------------------------------------
|
||||
interface_page = QWidget()
|
||||
interface_layout = QVBoxLayout(interface_page)
|
||||
interface_layout.setContentsMargins(0, 12, 0, 0)
|
||||
self.only_unclear = checkbox("Nur Schnittstellen ohne Namensgleichheit anzeigen", True)
|
||||
interface_layout.addWidget(self.only_unclear)
|
||||
self.interface_table = QTableWidget(0, 5)
|
||||
self.interface_table.setHorizontalHeaderLabels(["Switch", "Schnittstelle (Switch)", "VLANs",
|
||||
"NetBox-Schnittstelle", "Zuordnung"])
|
||||
self.interface_rows = []
|
||||
for switch, plan in plans:
|
||||
vlans = {item["name"]: item["vlan_label"] for item in plan["interfaces"]}
|
||||
for item in plan["interfaces"]:
|
||||
if not item["physical"] and item["method"] in ("name", "new"):
|
||||
continue
|
||||
# In a stack every member has its own NetBox device and interfaces.
|
||||
names = plan.get("owner_interfaces", {}).get(str(item.get("owner_id")), plan["netbox_interfaces"])
|
||||
choices = [("+ neu anlegen", self.NEW)] + [(name, name) for name in names]
|
||||
row = self.interface_table.rowCount()
|
||||
self.interface_table.insertRow(row)
|
||||
combo = QComboBox()
|
||||
for text, data in choices:
|
||||
combo.addItem(text, data)
|
||||
combo.setCurrentIndex(max(0, combo.findData(item["netbox_name"] or self.NEW)))
|
||||
for column, text in enumerate((switch["name"], item["name"], vlans.get(item["name"], ""))):
|
||||
self.interface_table.setItem(row, column, QTableWidgetItem(text))
|
||||
self.interface_table.setCellWidget(row, 3, combo)
|
||||
method = QTableWidgetItem(MATCH_METHODS.get(item["method"], item["method"]))
|
||||
if item["method"] in ("number", "order"):
|
||||
method.setForeground(QColor(theme.color("warning")))
|
||||
self.interface_table.setItem(row, 4, method)
|
||||
self.interface_rows.append((row, switch, item, combo))
|
||||
self._prepare_table(self.interface_table, (140, 170, 110, 220, 150))
|
||||
interface_layout.addWidget(self.interface_table, 1)
|
||||
unclear = sum(1 for _row, _switch, item, _combo in self.interface_rows if item["method"] != "name")
|
||||
tabs.addTab(interface_page, f"Schnittstellen ({unclear} zu prüfen)")
|
||||
self.only_unclear.toggled.connect(self._filter_interfaces)
|
||||
self._filter_interfaces(True)
|
||||
|
||||
# Neighbors -----------------------------------------------------------
|
||||
self.neighbor_rows = []
|
||||
if create_cables:
|
||||
neighbor_page = QWidget()
|
||||
neighbor_layout = QVBoxLayout(neighbor_page)
|
||||
neighbor_layout.setContentsMargins(0, 12, 0, 0)
|
||||
scopes = sorted({plan["device_scope"] for _switch, plan in plans})
|
||||
neighbor_layout.addWidget(label(
|
||||
"Für jeden Nachbarn kann ein bestehendes NetBox-Gerät gewählt werden (Auswahl aus: "
|
||||
f"{', '.join(scopes)}). Die Gegenstelle wird über den Portnamen gesucht; „kein Kabel“ "
|
||||
"überspringt den Nachbarn.", muted=True, wrap=True))
|
||||
self.neighbor_table = QTableWidget(0, 5)
|
||||
self.neighbor_table.setHorizontalHeaderLabels(["Switch", "Lokaler Port", "Nachbar (LLDP/CDP)",
|
||||
"Nachbar-Port", "NetBox-Gerät"])
|
||||
for switch, plan in plans:
|
||||
for neighbor in plan["neighbors"]:
|
||||
row = self.neighbor_table.rowCount()
|
||||
self.neighbor_table.insertRow(row)
|
||||
combo = SearchableComboBox("Gerät suchen …")
|
||||
combo.set_items([("– kein Kabel –", 0)] + [(device["name"], device["id"]) for device in plan["devices"]],
|
||||
neighbor.get("device_id") or 0)
|
||||
texts = (switch["name"], neighbor["local_port"], neighbor.get("system_name") or
|
||||
neighbor.get("management_ip") or "", neighbor.get("remote_port") or "")
|
||||
for column, text in enumerate(texts):
|
||||
self.neighbor_table.setItem(row, column, QTableWidgetItem(text))
|
||||
self.neighbor_table.setCellWidget(row, 4, combo)
|
||||
self.neighbor_rows.append((switch, neighbor, combo))
|
||||
self._prepare_table(self.neighbor_table, (140, 110, 220, 150, 260))
|
||||
neighbor_layout.addWidget(self.neighbor_table, 1)
|
||||
found = sum(1 for _switch, neighbor, _combo in self.neighbor_rows if neighbor.get("device_id"))
|
||||
tabs.addTab(neighbor_page, f"Nachbarn ({found} von {len(self.neighbor_rows)} zugeordnet)")
|
||||
|
||||
# Networks --------------------------------------------------------------
|
||||
# Network decisions apply to all switches of the profile: one row per network.
|
||||
self.network_rows = []
|
||||
networks = {}
|
||||
for switch, plan in plans:
|
||||
for item in plan["networks"]:
|
||||
entry = networks.setdefault(item["network"], {"item": item, "switches": [], "tenants": [], "vrfs": {}})
|
||||
entry["switches"].append(switch["name"])
|
||||
if plan["tenant"] not in entry["tenants"]:
|
||||
entry["tenants"].append(plan["tenant"])
|
||||
entry["vrfs"].update({vrf["id"]: vrf["label"] for vrf in plan["vrfs"]})
|
||||
if networks:
|
||||
network_page = QWidget()
|
||||
network_layout = QVBoxLayout(network_page)
|
||||
network_layout.setContentsMargins(0, 12, 0, 0)
|
||||
network_layout.addWidget(label(
|
||||
"Netze der Switch-IP-Adressen. Die VRF gilt für Prefix und IP-Adressen; zur Auswahl stehen die "
|
||||
"globale Tabelle und die VRFs der Mandantengruppe. Fehlende Prefixe werden nur angelegt, wenn sie "
|
||||
"angehakt sind – mit dem Mandanten des Switches. Die Auswahl gilt für alle Switche des Profils.",
|
||||
muted=True, wrap=True))
|
||||
settled = {network: entry["item"]["stored"] or bool(entry["item"]["existing"])
|
||||
for network, entry in networks.items()}
|
||||
self.open_network_table = self._network_table()
|
||||
self.settled_network_table = self._network_table()
|
||||
for network, entry in networks.items():
|
||||
table = self.settled_network_table if settled[network] else self.open_network_table
|
||||
self._add_network_row(table, entry)
|
||||
for table in (self.open_network_table, self.settled_network_table):
|
||||
self._prepare_table(table, (160, 150, 150, 300, 200))
|
||||
open_count = sum(1 for value in settled.values() if not value)
|
||||
self.settled_network_toggle = self._collapsible(network_layout, self.open_network_table,
|
||||
self.settled_network_table, open_count,
|
||||
len(networks) - open_count, "Netze")
|
||||
missing = sum(1 for entry in networks.values() if not entry["item"]["existing"])
|
||||
tabs.addTab(network_page, f"Netze ({open_count} zu prüfen, {missing} Prefix(e) fehlen)")
|
||||
|
||||
# VLANs -----------------------------------------------------------------
|
||||
# VLAN decisions apply to all switches of the profile: one row per VID.
|
||||
self.vlan_rows = []
|
||||
merged = {}
|
||||
for switch, plan in plans:
|
||||
for item in plan["vlans"]:
|
||||
entry = merged.setdefault(item["vid"], {"item": item, "switches": [], "candidates": {}, "tenants": {}})
|
||||
entry["switches"].append(switch["name"])
|
||||
entry["candidates"].update({candidate["id"]: candidate["label"] for candidate in item["candidates"]})
|
||||
entry["tenants"].update({tenant["id"]: tenant["name"] for tenant in plan["tenants"]})
|
||||
if merged:
|
||||
vlan_page = QWidget()
|
||||
vlan_layout = QVBoxLayout(vlan_page)
|
||||
vlan_layout.setContentsMargins(0, 12, 0, 0)
|
||||
vlan_layout.addWidget(label(
|
||||
"Gesucht wird in der Mandantengruppe über die VLAN-ID; bei mehreren Treffern entscheiden Mandant, "
|
||||
"Standort und Name. Neue VLANs erhalten den eingetragenen Namen und Mandanten. Ignorierte VLANs "
|
||||
"werden weder angelegt noch zugeordnet und fehlen im Label. Die Auswahl gilt für alle Switche "
|
||||
"des Profils und wird gespeichert.", muted=True, wrap=True))
|
||||
settled = {vid: entry["item"]["stored"] or entry["item"]["method"] in ("vid", "name")
|
||||
for vid, entry in merged.items()}
|
||||
self.open_vlan_table = self._vlan_table()
|
||||
self.settled_vlan_table = self._vlan_table()
|
||||
for vid in sorted(merged):
|
||||
self._add_vlan_row(self.settled_vlan_table if settled[vid] else self.open_vlan_table, merged[vid])
|
||||
for table in (self.open_vlan_table, self.settled_vlan_table):
|
||||
self._prepare_table(table, (130, 60, 150, 280, 190, 170, 110))
|
||||
open_count = sum(1 for value in settled.values() if not value)
|
||||
self.settled_toggle = self._collapsible(vlan_layout, self.open_vlan_table, self.settled_vlan_table,
|
||||
open_count, len(merged) - open_count, "VLANs")
|
||||
missing = sum(1 for entry in merged.values() if entry["item"]["method"] == "new")
|
||||
tabs.addTab(vlan_page, f"VLANs ({open_count} zu prüfen, {missing} fehlen)")
|
||||
|
||||
self.root.addWidget(tabs, 1)
|
||||
self.root.addWidget(self.error_banner)
|
||||
buttons, _ok = form_dialog_buttons(self, "Weiter zur Vorschau")
|
||||
self.root.addWidget(buttons)
|
||||
|
||||
@staticmethod
|
||||
def _prepare_table(table, widths):
|
||||
# Rows must fit the styled combo boxes, otherwise their text is clipped.
|
||||
height = max((table.cellWidget(row, column).sizeHint().height()
|
||||
for row in range(min(table.rowCount(), 1)) for column in range(table.columnCount())
|
||||
if table.cellWidget(row, column)), default=0)
|
||||
table.verticalHeader().setDefaultSectionSize(max(height + 10, table.verticalHeader().defaultSectionSize()))
|
||||
table.verticalHeader().hide()
|
||||
table.setEditTriggers(QTableWidget.NoEditTriggers)
|
||||
table.setSelectionMode(QTableWidget.NoSelection)
|
||||
table.horizontalHeader().setStretchLastSection(True)
|
||||
for column, width in enumerate(widths):
|
||||
table.setColumnWidth(column, width)
|
||||
|
||||
IGNORE = "\x00ignore"
|
||||
|
||||
@staticmethod
|
||||
def _vlan_table():
|
||||
table = QTableWidget(0, 7)
|
||||
table.setHorizontalHeaderLabels(["Switch(e)", "VLAN", "Name (Switch)", "NetBox-VLAN",
|
||||
"Name des neuen VLANs", "Mandant (neu)", "Zuordnung"])
|
||||
return table
|
||||
|
||||
def _add_vlan_row(self, table, entry):
|
||||
item = entry["item"]
|
||||
row = table.rowCount()
|
||||
table.insertRow(row)
|
||||
switches = ", ".join(entry["switches"])
|
||||
for column, text in enumerate((switches, str(item["vid"]), item["name"])):
|
||||
table.setItem(row, column, QTableWidgetItem(text))
|
||||
combo = QComboBox()
|
||||
for candidate_id, text in sorted(entry["candidates"].items(), key=lambda pair: pair[1].casefold()):
|
||||
combo.addItem(text, candidate_id)
|
||||
combo.addItem("+ neu anlegen", self.NEW)
|
||||
combo.addItem("– nicht zuordnen –", 0)
|
||||
combo.addItem("⊘ ignorieren (auf allen Switchen)", self.IGNORE)
|
||||
current = {"skip": 0, "ignore": self.IGNORE}.get(item["method"], item["netbox_id"] or self.NEW)
|
||||
combo.setCurrentIndex(max(0, combo.findData(current)))
|
||||
name = QLineEdit(item["new_name"])
|
||||
name.setMaxLength(64)
|
||||
name.setPlaceholderText(item["name"])
|
||||
tenant = QComboBox()
|
||||
for tenant_id, text in sorted(entry["tenants"].items(), key=lambda pair: pair[1].casefold()):
|
||||
tenant.addItem(text, tenant_id)
|
||||
tenant.setCurrentIndex(max(0, tenant.findData(item["new_tenant"])))
|
||||
method = QTableWidgetItem(VLAN_METHODS.get(item["method"], item["method"])
|
||||
+ (" · gespeichert" if item["stored"] else ""))
|
||||
if not item["stored"] and item["method"] in ("ambiguous", "new"):
|
||||
method.setForeground(QColor(theme.color("warning")))
|
||||
table.setCellWidget(row, 3, combo)
|
||||
table.setCellWidget(row, 4, name)
|
||||
table.setCellWidget(row, 5, tenant)
|
||||
table.setItem(row, 6, method)
|
||||
|
||||
def toggle(_index=None):
|
||||
for widget in (name, tenant):
|
||||
widget.setEnabled(combo.currentData() == self.NEW)
|
||||
combo.currentIndexChanged.connect(toggle)
|
||||
toggle()
|
||||
self.vlan_rows.append((item, combo, name, tenant))
|
||||
|
||||
@staticmethod
|
||||
def _collapsible(layout, open_table, settled_table, open_count, settled_count, noun):
|
||||
"""Open items on top, decided ones in a collapsed section that can be expanded."""
|
||||
layout.addWidget(label(f"<b>Zu prüfen ({open_count})</b>" if open_count else
|
||||
f"Alle {noun} sind zugeordnet oder gespeichert.", wrap=True))
|
||||
layout.addWidget(open_table, 1)
|
||||
open_table.setVisible(bool(open_count))
|
||||
toggle = button("", variant="link")
|
||||
toggle.setCheckable(True)
|
||||
|
||||
def update(expanded):
|
||||
arrow = "▾" if expanded else "▸"
|
||||
toggle.setText(f"{arrow} Gespeicherte und eindeutig zugeordnete {noun} ({settled_count})"
|
||||
+ ("" if expanded else " – zum Bearbeiten ausklappen"))
|
||||
settled_table.setVisible(expanded and settled_count > 0)
|
||||
toggle.toggled.connect(update)
|
||||
update(False)
|
||||
toggle.setVisible(settled_count > 0)
|
||||
layout.addWidget(toggle, 0, Qt.AlignLeft)
|
||||
layout.addWidget(settled_table, 1)
|
||||
return toggle
|
||||
|
||||
@staticmethod
|
||||
def _network_table():
|
||||
table = QTableWidget(0, 5)
|
||||
table.setHorizontalHeaderLabels(["Switch(e)", "Mandant", "Netz", "VRF", "Prefix in NetBox"])
|
||||
return table
|
||||
|
||||
def _add_network_row(self, table, entry):
|
||||
item = entry["item"]
|
||||
row = table.rowCount()
|
||||
table.insertRow(row)
|
||||
texts = (", ".join(entry["switches"]), ", ".join(entry["tenants"]), item["network"])
|
||||
for column, text in enumerate(texts):
|
||||
table.setItem(row, column, QTableWidgetItem(text))
|
||||
combo = QComboBox()
|
||||
combo.addItem("Global (keine VRF)", 0)
|
||||
for vrf_id, text in sorted(entry["vrfs"].items(), key=lambda pair: pair[1].casefold()):
|
||||
combo.addItem(text, vrf_id)
|
||||
new_names = list(self._new_vrf_names)
|
||||
if item["vrf_name"] and item["vrf_name"] not in new_names:
|
||||
new_names.append(item["vrf_name"])
|
||||
for name in new_names:
|
||||
combo.addItem(f"{name} (neu)", f"new:{name}")
|
||||
combo.addItem("+ Neue VRF …", self.NEW)
|
||||
current = f"new:{item['vrf_name']}" if item["vrf_name"] else item["vrf_id"]
|
||||
combo.setCurrentIndex(max(0, combo.findData(current)))
|
||||
combo.setProperty("previous", combo.currentIndex())
|
||||
table.setCellWidget(row, 3, combo)
|
||||
status = QTableWidgetItem()
|
||||
table.setItem(row, 4, status)
|
||||
row_entry = (item, combo, status)
|
||||
self.network_rows.append(row_entry)
|
||||
combo.activated.connect(lambda _index, row_entry=row_entry: self._vrf_chosen(row_entry))
|
||||
self._update_network_row(row_entry, item["create"])
|
||||
|
||||
def _vrf_chosen(self, entry):
|
||||
_item, combo, _status = entry
|
||||
if combo.currentData() == self.NEW:
|
||||
name = ask_text(self, "Neue VRF", "Name der neuen VRF. Sie wird beim Übertragen mit dem Mandanten "
|
||||
"des Switches angelegt.")
|
||||
if not name:
|
||||
combo.setCurrentIndex(combo.property("previous"))
|
||||
return
|
||||
self._new_vrf_names.append(name)
|
||||
# Offer the new VRF in every network row.
|
||||
for _other_item, other, _other_status in self.network_rows:
|
||||
if other.findData(f"new:{name}") < 0:
|
||||
other.insertItem(other.count() - 1, f"{name} (neu)", f"new:{name}")
|
||||
combo.setCurrentIndex(combo.findData(f"new:{name}"))
|
||||
combo.setProperty("previous", combo.currentIndex())
|
||||
self._update_network_row(entry)
|
||||
|
||||
def _update_network_row(self, entry, create=None):
|
||||
item, combo, status = entry
|
||||
if combo.currentData() in item["existing"]:
|
||||
status.setText("vorhanden")
|
||||
status.setFlags(Qt.ItemIsEnabled)
|
||||
status.setData(Qt.CheckStateRole, None)
|
||||
status.setForeground(QColor(theme.color("text_muted")))
|
||||
return
|
||||
status.setText("fehlt – anlegen")
|
||||
status.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
|
||||
if create is not None or status.data(Qt.CheckStateRole) is None:
|
||||
status.setCheckState(Qt.Checked if create is not False else Qt.Unchecked)
|
||||
status.setForeground(QColor(theme.color("warning")))
|
||||
|
||||
def _filter_interfaces(self, only_unclear):
|
||||
for row, _switch, item, _combo in self.interface_rows:
|
||||
self.interface_table.setRowHidden(row, only_unclear and item["method"] == "name")
|
||||
|
||||
def accept(self):
|
||||
result = {switch["id"]: {"interface_map": dict(switch.get("interface_map") or {}),
|
||||
"neighbor_devices": dict(switch.get("neighbor_devices") or {})}
|
||||
for switch, _plan in self.plans}
|
||||
# Members moved to another device: their port choices refer to the old
|
||||
# device and are dropped, so the ports are matched again automatically.
|
||||
moved = set()
|
||||
for switch, entry, combo in self.stack_rows:
|
||||
chosen = int(combo.valid_data() or 0)
|
||||
result[switch["id"]].setdefault("stack_devices", {})[str(entry["member"])] = chosen
|
||||
if chosen != (entry["device_id"] or 0) and entry["device_id"]:
|
||||
moved.add((switch["id"], entry["device_id"]))
|
||||
used = {}
|
||||
for _row, switch, item, combo in self.interface_rows:
|
||||
if (switch["id"], item.get("owner_id")) in moved:
|
||||
result[switch["id"]]["interface_map"].pop(item["name"], None)
|
||||
continue
|
||||
chosen = combo.currentData()
|
||||
target = "" if chosen == self.NEW else chosen
|
||||
mapping = result[switch["id"]]["interface_map"]
|
||||
if target and (switch["id"], target) in used:
|
||||
self.show_error(f"{switch['name']}: „{target}“ ist mehreren Schnittstellen zugeordnet "
|
||||
f"({used[(switch['id'], target)]}, {item['name']}).")
|
||||
return
|
||||
if target:
|
||||
used[(switch["id"], target)] = item["name"]
|
||||
# Plain name matches stay automatic; everything else is remembered.
|
||||
if item["method"] == "name" and target == item["netbox_name"]:
|
||||
mapping.pop(item["name"], None)
|
||||
else:
|
||||
mapping[item["name"]] = target
|
||||
for switch, neighbor, combo in self.neighbor_rows:
|
||||
chosen = combo.valid_data()
|
||||
chosen = int(chosen or 0)
|
||||
stored = result[switch["id"]]["neighbor_devices"]
|
||||
if neighbor["method"] == "auto" and chosen == (neighbor.get("device_id") or 0):
|
||||
stored.pop(neighbor["local_port"], None)
|
||||
else:
|
||||
stored[neighbor["local_port"]] = chosen
|
||||
network_map = dict(self.previous_network_map)
|
||||
for item, combo, status in self.network_rows:
|
||||
chosen = combo.currentData()
|
||||
new_name = chosen[4:] if isinstance(chosen, str) and chosen.startswith("new:") else ""
|
||||
network_map[item["network"]] = {
|
||||
"vrf_id": chosen if isinstance(chosen, int) and chosen else None,
|
||||
"vrf_name": new_name,
|
||||
"create": status.data(Qt.CheckStateRole) is not None and status.checkState() == Qt.Checked,
|
||||
}
|
||||
self.network_map = network_map
|
||||
vlan_map = dict(self.previous_vlan_map)
|
||||
for item, combo, name, tenant in self.vlan_rows:
|
||||
chosen = combo.currentData()
|
||||
if chosen == self.NEW:
|
||||
if not name.text().strip():
|
||||
self.show_error(f"Bitte einen Namen für das neue VLAN {item['vid']} eingeben.")
|
||||
return
|
||||
choice = {"action": "new", "name": name.text().strip(), "tenant": tenant.currentData()}
|
||||
elif chosen == self.IGNORE:
|
||||
choice = {"action": "ignore"}
|
||||
elif chosen:
|
||||
choice = {"action": "map", "id": chosen}
|
||||
else:
|
||||
choice = {"action": "skip"}
|
||||
vlan_map[str(item["vid"])] = choice
|
||||
self.vlan_map = vlan_map
|
||||
self.result = result
|
||||
super().accept()
|
||||
|
||||
|
||||
class RawDataDialog(_Dialog):
|
||||
SECTIONS = {
|
||||
"interfaces": "Schnittstellen", "ipv4_interfaces": "IPv4", "ipv6_interfaces": "IPv6",
|
||||
"neighbors": "LLDP", "cdp_neighbors": "CDP", "lldp_status": "LLDP-Status",
|
||||
"neighbors": "LLDP", "cdp_neighbors": "CDP", "vlan_config": "VLAN-Konfiguration", "lldp_status": "LLDP-Status",
|
||||
}
|
||||
|
||||
def __init__(self, parent, items, selected_id=None):
|
||||
|
||||
@@ -26,6 +26,8 @@ _PATHS = {
|
||||
"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"/>',
|
||||
"wifi": '<path d="M12 20h.01"/><path d="M2 8.82a15 15 0 0 1 20 0"/><path d="M5 12.86a10 10 0 0 1 14 0"/>'
|
||||
'<path d="M8.5 16.43a5 5 0 0 1 7 0"/>',
|
||||
"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"/>',
|
||||
|
||||
@@ -22,7 +22,7 @@ from PySide6.QtWidgets import (
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from netbox_sync.core.vm_sync import cluster_key, prefix_choices, vrf_label
|
||||
from netbox_sync.core.vm_sync import cluster_key, host_key, prefix_choices, vrf_label
|
||||
from netbox_sync.ui.icons import icon
|
||||
from netbox_sync.ui.tasks import log_bus
|
||||
from netbox_sync.ui.theme import theme
|
||||
@@ -31,6 +31,7 @@ from netbox_sync.ui.widgets import Banner, SearchableComboBox, button, checkbox,
|
||||
NEW_VRF = "__new__"
|
||||
NEW_CLUSTER = "__new_cluster__"
|
||||
GLOBAL_VRF = "__global__"
|
||||
NO_DEVICE = "__no_device__"
|
||||
STEPS = ("Ziel", "Netzwerke", "Prüfen", "Import")
|
||||
|
||||
|
||||
@@ -127,6 +128,53 @@ class ImportWizard(QDialog):
|
||||
group["vms"].append(vm)
|
||||
return sorted(groups.values(), key=lambda item: (item["source"].casefold(), item["cluster"].casefold()))
|
||||
|
||||
def _host_groups(self):
|
||||
groups = {}
|
||||
for vm in self.vms:
|
||||
if vm.get("host"):
|
||||
key = host_key(vm)
|
||||
groups.setdefault(key, {"key": key, "host": vm["host"], "source": vm.get("source", ""), "vms": []})
|
||||
groups[key]["vms"].append(vm)
|
||||
return sorted(groups.values(), key=lambda item: (item["source"].casefold(), item["host"].casefold()))
|
||||
|
||||
def _build_host_table(self):
|
||||
"""Hypervisor host → NetBox device. Names rarely match, so the user always chooses."""
|
||||
self.host_groups = self._host_groups()
|
||||
remembered = (self.state.profile or {}).get("host_map", {})
|
||||
devices = sorted(((self.engine.device_label(device_id), device_id) for device_id in self.engine.devices),
|
||||
key=lambda item: item[0].casefold())
|
||||
table = QTableWidget(len(self.host_groups), 3)
|
||||
table.setHorizontalHeaderLabels(["Hypervisor-Host", "VMs", "NetBox-Gerät"])
|
||||
table.verticalHeader().setVisible(False)
|
||||
table.verticalHeader().setDefaultSectionSize(46)
|
||||
table.setShowGrid(False)
|
||||
table.setAlternatingRowColors(True)
|
||||
table.setSelectionMode(QTableWidget.NoSelection)
|
||||
table.setFocusPolicy(Qt.NoFocus)
|
||||
table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
|
||||
table.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)
|
||||
table.setColumnWidth(1, 60)
|
||||
table.setFixedHeight(46 * min(len(self.host_groups), 4) + 40)
|
||||
for row, group in enumerate(self.host_groups):
|
||||
item = QTableWidgetItem(f"{group['host']} · {group['source']}")
|
||||
item.setToolTip("\n".join(sorted(vm["name"] for vm in group["vms"])))
|
||||
table.setItem(row, 0, item)
|
||||
count = QTableWidgetItem(str(len(group["vms"])))
|
||||
count.setTextAlignment(Qt.AlignCenter)
|
||||
table.setItem(row, 1, count)
|
||||
combo = SearchableComboBox("NetBox-Gerät suchen …")
|
||||
current = remembered.get(group["key"])
|
||||
if current not in self.engine.devices and current != NO_DEVICE:
|
||||
current = None
|
||||
combo.set_items([("– nicht zuordnen –", NO_DEVICE), *devices], current)
|
||||
holder = QWidget()
|
||||
holder_layout = QHBoxLayout(holder)
|
||||
holder_layout.setContentsMargins(0, 4, 8, 4)
|
||||
holder_layout.addWidget(combo)
|
||||
table.setCellWidget(row, 2, holder)
|
||||
group["combo"] = combo
|
||||
return table
|
||||
|
||||
def _build_target_page(self):
|
||||
page = QWidget()
|
||||
layout = QVBoxLayout(page)
|
||||
@@ -187,6 +235,11 @@ class ImportWizard(QDialog):
|
||||
group["status"] = status
|
||||
combo.activated.connect(lambda _index, g=group: (g.update(how="manual"), self._clusters_changed()))
|
||||
layout.addWidget(self.cluster_table)
|
||||
host_table = self._build_host_table()
|
||||
if self.host_groups:
|
||||
layout.addWidget(label("Auf welches NetBox-Gerät soll jeder Hypervisor-Host gemappt werden?",
|
||||
muted=True, wrap=True))
|
||||
layout.addWidget(host_table)
|
||||
|
||||
form = QFormLayout()
|
||||
form.setHorizontalSpacing(18)
|
||||
@@ -290,6 +343,10 @@ class ImportWizard(QDialog):
|
||||
if self._selected_cluster(group) is None]
|
||||
if missing:
|
||||
return None, "Bitte für folgende Hypervisor-Cluster einen NetBox-Cluster wählen: " + ", ".join(missing)
|
||||
unmapped = [group["host"] for group in self.host_groups if group["combo"].valid_data() is None]
|
||||
if unmapped:
|
||||
return None, ("Bitte für folgende Hypervisor-Hosts ein NetBox-Gerät wählen "
|
||||
"(oder „nicht zuordnen“): " + ", ".join(unmapped))
|
||||
tenant = self.tenant.valid_data()
|
||||
vrf = self.vrf.currentData()
|
||||
if not tenant:
|
||||
@@ -307,8 +364,10 @@ class ImportWizard(QDialog):
|
||||
"label": group["cluster"] or "(ohne Cluster)",
|
||||
"count": len(group["vms"]),
|
||||
}
|
||||
hosts = {group["key"]: group["combo"].valid_data() for group in self.host_groups}
|
||||
return {
|
||||
"clusters": clusters,
|
||||
"hosts": hosts,
|
||||
"tenant": tenant,
|
||||
"tenant_id": self.engine.tenants[tenant],
|
||||
"vrf_mode": "new" if vrf == NEW_VRF else ("global" if vrf == GLOBAL_VRF else "existing"),
|
||||
@@ -508,6 +567,10 @@ class ImportWizard(QDialog):
|
||||
]
|
||||
rows = [
|
||||
("Cluster", "\n".join(cluster_lines)),
|
||||
*([("Hosts", "\n".join(
|
||||
f"{group['host']} → " + ("nicht zuordnen" if target["hosts"][group["key"]] == NO_DEVICE
|
||||
else self.engine.device_label(target["hosts"][group["key"]]))
|
||||
for group in self.host_groups))] if self.host_groups else []),
|
||||
("Mandant", target["tenant"]),
|
||||
("Standard-VRF", vrf_text),
|
||||
("Virtuelle Maschinen", f"{len(self.vms)} gesamt · {new} werden angelegt · {existing} aktualisiert"),
|
||||
@@ -581,6 +644,7 @@ class ImportWizard(QDialog):
|
||||
if self.state.profile is not None:
|
||||
remembered = self.state.profile.setdefault("cluster_map", {})
|
||||
remembered.update({key: item["name"] for key, item in target["clusters"].items()})
|
||||
self.state.profile.setdefault("host_map", {}).update(target["hosts"])
|
||||
self.state.touch()
|
||||
log_bus.entry.connect(self._append_log)
|
||||
self.run_progress.setRange(0, len(vms))
|
||||
@@ -607,7 +671,9 @@ class ImportWizard(QDialog):
|
||||
break
|
||||
ctx.progress(index, len(vms), vm["name"])
|
||||
try:
|
||||
outcome = engine.sync_vm(vm, cluster_ids[cluster_key(vm)], target["tenant_id"], vrf_id)
|
||||
device_id = target["hosts"].get(host_key(vm))
|
||||
outcome = engine.sync_vm(vm, cluster_ids[cluster_key(vm)], target["tenant_id"], vrf_id,
|
||||
None if device_id == NO_DEVICE else device_id)
|
||||
results[outcome] += 1
|
||||
except Exception as error: # noqa: BLE001
|
||||
results["failed"].append(f"{vm['name']}: {error}")
|
||||
|
||||
@@ -23,11 +23,13 @@ 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.access_points import AccessPointsPage
|
||||
from netbox_sync.ui.pages.clients import ClientsPage
|
||||
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.scanner import ScannerPage
|
||||
from netbox_sync.ui.pages.settings import SettingsPage
|
||||
from netbox_sync.ui.pages.switches import SwitchesPage
|
||||
from netbox_sync.ui.pages.vms import VMsPage
|
||||
@@ -35,6 +37,7 @@ 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.updates import UpdateManager
|
||||
from netbox_sync.ui.widgets import Badge, Toast, button, label
|
||||
|
||||
NAVIGATION = (
|
||||
@@ -43,7 +46,9 @@ NAVIGATION = (
|
||||
("vms", "Virtuelle Maschinen", "server"),
|
||||
("switches", "Switche", "network"),
|
||||
("clients", "Windows-Clients", "monitor"),
|
||||
("aps", "Access Points", "wifi"),
|
||||
("ipam", "VRFs && Netze", "globe"),
|
||||
("scanner", "Netzwerk-Scanner", "search"),
|
||||
("log", "Protokoll", "list"),
|
||||
)
|
||||
|
||||
@@ -81,6 +86,7 @@ class MainWindow(QMainWindow):
|
||||
self.state = AppState()
|
||||
self.tasks = TaskManager()
|
||||
self.actions = Actions(self)
|
||||
self.updates = UpdateManager(self)
|
||||
self.pages = {}
|
||||
self.nav_buttons = {}
|
||||
self.unseen_errors = 0
|
||||
@@ -102,7 +108,9 @@ class MainWindow(QMainWindow):
|
||||
self.toast_widget = Toast(central)
|
||||
|
||||
for key, page_class in (("overview", OverviewPage), ("connections", ConnectionsPage), ("vms", VMsPage),
|
||||
("switches", SwitchesPage), ("clients", ClientsPage), ("ipam", IpamPage), ("log", LogPage),
|
||||
("switches", SwitchesPage), ("clients", ClientsPage), ("aps", AccessPointsPage),
|
||||
("ipam", IpamPage), ("scanner", ScannerPage),
|
||||
("log", LogPage),
|
||||
("settings", SettingsPage)):
|
||||
page = page_class(self)
|
||||
self.pages[key] = page
|
||||
@@ -120,7 +128,7 @@ class MainWindow(QMainWindow):
|
||||
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", "", ""))):
|
||||
for index, (key, _title, _icon) in enumerate((*NAVIGATION[:8], ("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)
|
||||
@@ -271,6 +279,8 @@ class MainWindow(QMainWindow):
|
||||
page.discover()
|
||||
elif page is self.pages["clients"] and not self.tasks.busy:
|
||||
page.scan()
|
||||
elif page is self.pages["scanner"] and not self.tasks.busy:
|
||||
page.scan()
|
||||
|
||||
def _focus_search(self):
|
||||
search = getattr(self.current_page(), "search", None)
|
||||
@@ -361,7 +371,7 @@ class MainWindow(QMainWindow):
|
||||
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", "clients", "ipam"):
|
||||
for key in ("connections", "vms", "switches", "clients", "aps", "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()
|
||||
|
||||
@@ -0,0 +1,483 @@
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import Qt, QTimer
|
||||
from PySide6.QtWidgets import (
|
||||
QFileDialog,
|
||||
QFormLayout,
|
||||
QHBoxLayout,
|
||||
QStackedWidget,
|
||||
QTableWidget,
|
||||
QTableWidgetItem,
|
||||
)
|
||||
|
||||
from netbox_sync.core.ap_sync import APImportError, APSyncEngine, ap_key, parse_csv
|
||||
from netbox_sync.core.netbox import related_id
|
||||
from netbox_sync.ui import widgets
|
||||
from netbox_sync.ui.client_dialogs import ClientPreviewDialog
|
||||
from netbox_sync.ui.dialogs import _Dialog
|
||||
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
|
||||
from netbox_sync.ui.pages import Page
|
||||
from netbox_sync.ui.tasks import logger
|
||||
from netbox_sync.ui.widgets import (
|
||||
Card,
|
||||
EmptyState,
|
||||
SearchableComboBox,
|
||||
SearchField,
|
||||
Table,
|
||||
button,
|
||||
checkbox,
|
||||
form_dialog_buttons,
|
||||
label,
|
||||
)
|
||||
|
||||
STATE_TEXT = {"new": "neu", "known": "in NetBox", "check": "prüfen", "netbox_only": "nur in NetBox"}
|
||||
STATE_DOT = {"new": "accent", "known": "success", "check": "warning", "netbox_only": "text_faint"}
|
||||
ROLE_HINTS = ("access point", "accesspoint", "access-point", "wlan", "wifi", "ap")
|
||||
|
||||
|
||||
def placement_value(value):
|
||||
"""Stored choice as ``{"site": ID or None, "tenant": ID or None}`` (4.9.0 stored only a site ID)."""
|
||||
if isinstance(value, dict):
|
||||
return {"site": value.get("site") or None, "tenant": value.get("tenant") or None}
|
||||
return {"site": value or None, "tenant": None}
|
||||
|
||||
|
||||
class SiteMappingDialog(_Dialog):
|
||||
"""Assign an optional NetBox site and the mandatory tenant to Sophos sites
|
||||
and to APs without a Sophos site."""
|
||||
|
||||
def __init__(self, parent, rows, sites, tenants, default_tenant):
|
||||
super().__init__(parent, "Standorte & Mandanten zuordnen",
|
||||
"Der Standort ist optional – APs ohne Zuordnung kommen an den Standard-Standort, weil NetBox "
|
||||
"für jedes Gerät einen Standort verlangt. Der Mandant ist Pflicht; vorgeschlagen wird der des "
|
||||
"Standorts, sonst der gewählte Mandant.", width=860)
|
||||
self.resize(980, 620)
|
||||
self.sites = {site["id"]: site for site in sites}
|
||||
site_items = [("– kein Standort (Standard-Standort) –", 0)] + [
|
||||
(site["name"] + (f" ({site['tenant']})" if site["tenant"] else ""), site["id"]) for site in sites]
|
||||
tenant_items = [(tenant["name"], tenant["id"]) for tenant in tenants]
|
||||
self.default_tenant = default_tenant
|
||||
self.table = QTableWidget(0, 4)
|
||||
self.table.setHorizontalHeaderLabels(["Sophos-Standort / Access Point", "APs", "NetBox-Standort (optional)",
|
||||
"Mandant *"])
|
||||
self.rows = []
|
||||
for text, count, key, current in rows:
|
||||
row = self.table.rowCount()
|
||||
self.table.insertRow(row)
|
||||
self.table.setItem(row, 0, QTableWidgetItem(text))
|
||||
self.table.setItem(row, 1, QTableWidgetItem(str(count)))
|
||||
site = SearchableComboBox("Standort suchen …")
|
||||
site.set_items(site_items, current["site"] or 0)
|
||||
tenant = SearchableComboBox("Mandant wählen …")
|
||||
tenant.set_items(tenant_items, current["tenant"] or self._site_tenant(current["site"]))
|
||||
site.activated.connect(lambda _index, site=site, tenant=tenant: tenant.select_data(
|
||||
self._site_tenant(site.valid_data())))
|
||||
self.table.setCellWidget(row, 2, site)
|
||||
self.table.setCellWidget(row, 3, tenant)
|
||||
self.rows.append((key, site, tenant))
|
||||
self.table.verticalHeader().hide()
|
||||
self.table.verticalHeader().setDefaultSectionSize(42)
|
||||
self.table.setEditTriggers(QTableWidget.NoEditTriggers)
|
||||
self.table.setSelectionMode(QTableWidget.NoSelection)
|
||||
self.table.horizontalHeader().setStretchLastSection(True)
|
||||
for column, width in enumerate((300, 50, 330, 240)):
|
||||
self.table.setColumnWidth(column, width)
|
||||
self.root.addWidget(self.table, 1)
|
||||
self.root.addWidget(self.error_banner)
|
||||
buttons, _ok = form_dialog_buttons(self, "Übernehmen")
|
||||
self.root.addWidget(buttons)
|
||||
self.result = {}
|
||||
|
||||
def _site_tenant(self, site_id):
|
||||
return (self.sites.get(site_id) or {}).get("tenant_id") or self.default_tenant
|
||||
|
||||
def accept(self):
|
||||
result = {}
|
||||
for key, site, tenant in self.rows:
|
||||
if tenant.valid_data() is None:
|
||||
self.show_error(f"Bitte für „{key[1]}“ einen Mandanten wählen.")
|
||||
return
|
||||
result[key] = {"site": site.valid_data() or None, "tenant": tenant.valid_data()}
|
||||
self.result = result
|
||||
super().accept()
|
||||
|
||||
|
||||
class AccessPointsPage(Page):
|
||||
title = "Access Points"
|
||||
subtitle = ("Sophos-APs aus einem Export von Sophos Central laden, mit NetBox abgleichen (global über "
|
||||
"Seriennummer und MAC, im Mandanten über den Namen) und fehlende anlegen.")
|
||||
|
||||
def __init__(self, window):
|
||||
super().__init__(window)
|
||||
self.aps = []
|
||||
self.only_netbox = []
|
||||
self.engine = None
|
||||
self.tenants = []
|
||||
self.file_name = ""
|
||||
|
||||
source = Card("Sophos-Export", "In Sophos Central: Wireless › Access Points › Exportieren (CSV).")
|
||||
self.load_button = source.add_action(button("CSV laden …", "folder", on_click=self.load_file))
|
||||
self.sync_button = source.add_action(button("Nach NetBox übertragen …", "upload", "primary",
|
||||
on_click=self.sync))
|
||||
form = QFormLayout()
|
||||
form.setHorizontalSpacing(18)
|
||||
tenant_row = QHBoxLayout()
|
||||
self.tenant = SearchableComboBox("Mandant wählen …")
|
||||
self.tenant.setMinimumWidth(320)
|
||||
tenant_row.addWidget(self.tenant)
|
||||
self.tenant_hint = label("Standorte und vorhandene APs werden in seiner Mandantengruppe gesucht.", muted=True)
|
||||
tenant_row.addWidget(self.tenant_hint, 1)
|
||||
form.addRow("Mandant *", tenant_row)
|
||||
self.role = SearchableComboBox("Geräterolle wählen …")
|
||||
self.role.setMinimumWidth(320)
|
||||
form.addRow("Geräterolle", self.role)
|
||||
site_row = QHBoxLayout()
|
||||
self.default_site = SearchableComboBox("Standort wählen …")
|
||||
self.default_site.setMinimumWidth(320)
|
||||
site_row.addWidget(self.default_site)
|
||||
site_row.addWidget(label("Für neue APs ohne zugeordneten Standort – NetBox verlangt für jedes Gerät einen.",
|
||||
muted=True), 1)
|
||||
form.addRow("Standard-Standort", site_row)
|
||||
self.rename = checkbox("Namen vorhandener Geräte aus Sophos übernehmen", True)
|
||||
form.addRow("", self.rename)
|
||||
source.add(form)
|
||||
self.body.addWidget(source)
|
||||
|
||||
result = Card("Abgleich")
|
||||
self.sites_button = result.add_action(button("Standorte && Mandanten …", "globe", on_click=self.map_sites))
|
||||
self.refresh_button = result.add_action(button("Neu abgleichen", "refresh", on_click=self.compare))
|
||||
filters = QHBoxLayout()
|
||||
self.search = SearchField("Name, S/N, MAC, IP, Standort …")
|
||||
self.only_open = checkbox("Nur neue und zu prüfende")
|
||||
filters.addWidget(self.search, 2)
|
||||
filters.addWidget(self.only_open)
|
||||
filters.addStretch(1)
|
||||
result.add(filters)
|
||||
columns = [
|
||||
Column("state", "Status", 110, value=lambda row: STATE_TEXT.get(row["state"], ""),
|
||||
dot=lambda row: "warning" if row.get("issues") and row["state"] == "new"
|
||||
else STATE_DOT.get(row["state"]), tooltip=lambda row: "\n".join(row.get("issues", []))),
|
||||
Column("name", "Name", 230),
|
||||
Column("model", "Modell", 80),
|
||||
Column("serial", "Seriennummer", 140),
|
||||
Column("mac", "MAC-Adresse", 135),
|
||||
Column("ip", "IP-Adresse", 110),
|
||||
Column("site_hint", "Sophos-Standort", 170),
|
||||
Column("netbox_site", "NetBox-Standort", 190,
|
||||
color=lambda row: "warning" if row["state"] == "new" and not row.get("site_id")
|
||||
else ("text_muted" if str(row.get("netbox_site", "")).startswith("Standard:") else None)),
|
||||
Column("tenant", "Mandant", 150),
|
||||
Column("netbox_device", "NetBox-Gerät", 170),
|
||||
Column("method", "Gefunden über", 110, color=lambda row: "text_muted"),
|
||||
Column("issues", "Hinweise", 260, value=lambda row: "; ".join(row.get("issues", [])),
|
||||
color=lambda row: "warning"),
|
||||
]
|
||||
self.model = RowTableModel(columns, row_id=lambda row: row["key"])
|
||||
self.proxy = FilterProxy(self.model)
|
||||
self.table = Table()
|
||||
self.table.setModel(self.proxy)
|
||||
for index, column in enumerate(columns):
|
||||
self.table.setColumnWidth(index, column.width)
|
||||
self.stack = QStackedWidget()
|
||||
self.stack.addWidget(EmptyState("upload", "Noch kein Export geladen",
|
||||
"Die CSV-Datei aus Sophos Central laden. Danach wird automatisch mit NetBox "
|
||||
"abgeglichen – geschrieben wird erst nach der Vorschau.",
|
||||
"CSV laden …", self.load_file))
|
||||
self.stack.addWidget(self.table)
|
||||
result.add(self.stack, 1)
|
||||
self.summary = label("", muted=True)
|
||||
result.add(self.summary)
|
||||
self.body.addWidget(result, 1)
|
||||
|
||||
self.search.textChanged.connect(self.proxy.set_text)
|
||||
self.only_open.toggled.connect(lambda value: self.proxy.set_predicate(
|
||||
"open", (lambda row: row["state"] in ("new", "check")) if value else None))
|
||||
self.tenant.activated.connect(lambda _index: self._tenant_chosen())
|
||||
self.role.activated.connect(lambda _index: self._store(role_id=self.role.valid_data()))
|
||||
self.default_site.activated.connect(lambda _index: (self._store(default_site=self.default_site.valid_data()),
|
||||
self._refresh()))
|
||||
self.rename.toggled.connect(lambda value: self._store(rename=value))
|
||||
self.state.profile_switched.connect(self._profile_switched)
|
||||
self._profile_switched()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Profile settings
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _settings(self):
|
||||
return self.state.profile.setdefault("access_points", {}) if self.state.profile else {}
|
||||
|
||||
def _store(self, **values):
|
||||
if self.state.profile is None:
|
||||
return
|
||||
self._settings().update(values)
|
||||
self.state.touch()
|
||||
|
||||
def _profile_switched(self):
|
||||
self.aps, self.only_netbox, self.engine, self.tenants = [], [], None, []
|
||||
self.tenant.set_items([])
|
||||
self.role.set_items([])
|
||||
self.default_site.set_items([])
|
||||
self.rename.blockSignals(True)
|
||||
self.rename.setChecked(self._settings().get("rename", True))
|
||||
self.rename.blockSignals(False)
|
||||
self._refresh()
|
||||
|
||||
def on_show(self):
|
||||
if not self.tenants and self._netbox_ready() and not self.tasks.busy:
|
||||
self._load_lists()
|
||||
|
||||
def set_busy(self, busy):
|
||||
for widget in (self.load_button, self.sites_button, self.refresh_button):
|
||||
widget.setEnabled(not busy)
|
||||
self._update_buttons()
|
||||
|
||||
def _netbox_ready(self):
|
||||
return bool(self.state.profile) and not self.state.offline and self.state.netbox_configured()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Loading
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def load_file(self):
|
||||
path, _filter = QFileDialog.getOpenFileName(self.window, "Sophos-Export laden", "",
|
||||
"CSV-Dateien (*.csv);;Alle Dateien (*)")
|
||||
if not path:
|
||||
return
|
||||
try:
|
||||
self.aps = parse_csv(Path(path).read_bytes())
|
||||
except (OSError, APImportError) as error:
|
||||
widgets.message(self.window, "Datei nicht lesbar", str(error), "warning")
|
||||
return
|
||||
self.file_name = Path(path).name
|
||||
self.only_netbox, self.engine = [], None
|
||||
logger("app").info("Sophos-Export %s: %s Access Points", self.file_name, len(self.aps))
|
||||
self._refresh()
|
||||
if self._netbox_ready():
|
||||
self._load_lists(then_compare=True)
|
||||
|
||||
def _load_lists(self, then_compare=False):
|
||||
connect = self.actions._connector()
|
||||
|
||||
def work(ctx):
|
||||
nb = connect(ctx)
|
||||
ctx.log("Lade Mandanten und Geräterollen …")
|
||||
tenants = sorted(((item.name, item.id) for item in nb.tenancy.tenants.all()), key=lambda x: x[0].casefold())
|
||||
roles = sorted(((item.name, item.id) for item in nb.dcim.device_roles.all()), key=lambda x: x[0].casefold())
|
||||
return tenants, roles
|
||||
|
||||
def done(result):
|
||||
self.tenants, roles = result
|
||||
settings = self._settings()
|
||||
# The tenant is always chosen deliberately – never preselected.
|
||||
self.tenant.set_items(self.tenants)
|
||||
role_id = settings.get("role_id") or next(
|
||||
(role_id for name, role_id in roles if name.casefold() in ROLE_HINTS
|
||||
or "access point" in name.casefold()), None)
|
||||
self.role.set_items(roles, role_id)
|
||||
if then_compare and self.tenant.valid_data():
|
||||
QTimer.singleShot(0, self.compare)
|
||||
|
||||
self.tasks.run(work, title="Mandanten laden", area="app", on_success=done,
|
||||
on_error=self.actions._netbox_failed)
|
||||
|
||||
def _tenant_chosen(self):
|
||||
self._store(tenant_id=self.tenant.valid_data())
|
||||
if self.aps and self.tenant.valid_data():
|
||||
self.compare()
|
||||
|
||||
def compare(self):
|
||||
tenant_id = self.tenant.valid_data()
|
||||
if not self.aps or not tenant_id or self.tasks.busy:
|
||||
if not tenant_id and self.aps:
|
||||
self.window.toast("Bitte zuerst den Mandanten wählen.", "info")
|
||||
return
|
||||
connect = self.actions._connector()
|
||||
aps = [dict(ap, issues=[issue for issue in ap["issues"] if not issue.startswith(("NetBox-Gerät gehört",
|
||||
"Seriennummer in NetBox"))])
|
||||
for ap in self.aps]
|
||||
|
||||
def work(ctx):
|
||||
engine = APSyncEngine(connect(ctx), ctx.log)
|
||||
ctx.log("Lade Standorte und vorhandene Access Points der Mandantengruppe …")
|
||||
engine.load_context(tenant_id)
|
||||
ctx.log(f"Suche {len(aps)} Access Points in NetBox (Seriennummer, MAC, Name) …")
|
||||
only_netbox = engine.match(aps)
|
||||
return engine, aps, only_netbox
|
||||
|
||||
def done(result):
|
||||
self.engine, self.aps, self.only_netbox = result
|
||||
self.default_site.set_items([(site["name"] + (f" ({site['tenant']})" if site["tenant"] else ""),
|
||||
site["id"]) for site in self.engine.ap_sites],
|
||||
self._settings().get("default_site"))
|
||||
found = sum(1 for ap in self.aps if ap.get("device"))
|
||||
logger("app").log(25, "Abgleich: %s von %s APs in NetBox, %s nur in NetBox", found, len(self.aps),
|
||||
len(self.only_netbox))
|
||||
self._refresh()
|
||||
|
||||
self.tasks.run(work, title="Access Points abgleichen", area="app", on_success=done,
|
||||
on_error=self.actions._netbox_failed)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Table
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _placement(self, ap):
|
||||
"""Site (optional) and tenant for a new AP: stored choice, else the suggestion."""
|
||||
settings = self._settings()
|
||||
stored = (settings.get("ap_sites") or {}).get(ap_key(ap)) or (settings.get("site_map") or {}).get(
|
||||
ap["site_hint"])
|
||||
if stored:
|
||||
return dict(placement_value(stored), stored=True)
|
||||
site = self.engine.suggest_site(ap["site_hint"]) if self.engine else None
|
||||
return {"site": site, "tenant": None, "stored": False}
|
||||
|
||||
def _tenant_for(self, placement):
|
||||
if placement.get("tenant"):
|
||||
return placement["tenant"]
|
||||
return self.engine._site_tenant(placement.get("site")) if self.engine else None
|
||||
|
||||
def _site_name(self, site_id):
|
||||
sites = self.engine.ap_sites if self.engine else []
|
||||
return next((site["name"] for site in sites if site["id"] == site_id), "")
|
||||
|
||||
def _tenant_name(self, tenant_id):
|
||||
tenants = self.engine.group_tenants if self.engine else []
|
||||
return next((tenant["name"] for tenant in tenants if tenant["id"] == tenant_id), "")
|
||||
|
||||
def _refresh(self):
|
||||
rows = []
|
||||
default_site = self.default_site.valid_data()
|
||||
for ap in self.aps:
|
||||
device = ap.get("device")
|
||||
site_id = tenant_name = None
|
||||
if device:
|
||||
site = getattr(device, "site", None)
|
||||
site_name = getattr(site, "name", "") or self._site_name(getattr(site, "id", site))
|
||||
tenant_name = getattr(getattr(device, "tenant", None), "name", "") or self._tenant_name(
|
||||
related_id(device, "tenant"))
|
||||
elif self.engine:
|
||||
placement = self._placement(ap)
|
||||
site_id = placement["site"] or default_site
|
||||
site_name = (self._site_name(placement["site"]) if placement["site"] else
|
||||
f"Standard: {self._site_name(default_site)}" if default_site else "– Standard-Standort fehlt –")
|
||||
tenant_name = self._tenant_name(self._tenant_for(placement))
|
||||
else:
|
||||
site_name = ""
|
||||
state = "new" if not device else ("check" if ap["issues"] else "known")
|
||||
rows.append(dict(ap, key=ap_key(ap), state=state if self.engine else "", site_id=site_id,
|
||||
netbox_site=site_name, tenant=tenant_name or "",
|
||||
netbox_device=device.name if device else "", method=ap.get("method", "")))
|
||||
for device in self.only_netbox:
|
||||
rows.append({"key": f"netbox-{device.id}", "state": "netbox_only", "name": device.name,
|
||||
"model": getattr(getattr(device, "device_type", None), "model", "") or "",
|
||||
"serial": getattr(device, "serial", "") or "", "mac": "",
|
||||
"ip": str(getattr(getattr(device, "primary_ip4", None), "address", "") or "").split("/")[0],
|
||||
"site_hint": "", "netbox_site": getattr(getattr(device, "site", None), "name", "")
|
||||
or self._site_name(related_id(device, "site")),
|
||||
"tenant": self._tenant_name(related_id(device, "tenant")),
|
||||
"netbox_device": device.name, "method": "",
|
||||
"issues": ["In NetBox, aber nicht im Sophos-Export"]})
|
||||
self.model.set_rows(rows)
|
||||
self.stack.setCurrentIndex(1 if rows else 0)
|
||||
counts = {key: sum(1 for row in rows if row["state"] == key) for key in STATE_TEXT}
|
||||
parts = [f"{len(self.aps)} Access Points" + (f" aus {self.file_name}" if self.file_name else "")]
|
||||
if self.engine:
|
||||
parts += [f"{counts['known']} in NetBox", f"{counts['new']} neu", f"{counts['check']} zu prüfen",
|
||||
f"{counts['netbox_only']} nur in NetBox"]
|
||||
missing_sites = sum(1 for row in rows if row["state"] == "new" and not row.get("site_id"))
|
||||
if missing_sites:
|
||||
parts.append(f"{missing_sites} ohne Standort – Standard-Standort wählen")
|
||||
elif self.aps:
|
||||
parts.append("Mandant wählen, um mit NetBox abzugleichen" if self._netbox_ready()
|
||||
else "kein NetBox-Abgleich (kein Zugang im Profil oder Offline-Modus)")
|
||||
self.summary.setText(" · ".join(parts) if self.aps or self.only_netbox else "")
|
||||
self._update_buttons()
|
||||
|
||||
def _update_buttons(self):
|
||||
busy = self.tasks.busy
|
||||
widgets.set_enabled(self.sync_button, bool(self.engine) and not busy,
|
||||
"Bitte Export laden und Mandanten wählen." if not self.engine else "Bitte warten …")
|
||||
widgets.set_enabled(self.sites_button, bool(self.engine) and not busy, "Erst mit NetBox abgleichen.")
|
||||
widgets.set_enabled(self.refresh_button, bool(self.aps) and not busy, "Erst einen Export laden.")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Sites and transfer
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _new_aps(self):
|
||||
return [ap for ap in self.aps if not ap.get("device")]
|
||||
|
||||
def map_sites(self):
|
||||
if not self.engine:
|
||||
return False
|
||||
new = self._new_aps()
|
||||
groups = {}
|
||||
for ap in new:
|
||||
if ap["site_hint"]:
|
||||
groups.setdefault(ap["site_hint"], []).append(ap)
|
||||
rows = [(hint, len(members), ("site", hint), self._placement(members[0]))
|
||||
for hint, members in sorted(groups.items(), key=lambda pair: pair[0].casefold())]
|
||||
rows += [(f"{ap['name']} (ohne Sophos-Standort)", 1, ("ap", ap_key(ap)), self._placement(ap))
|
||||
for ap in new if not ap["site_hint"]]
|
||||
if not rows:
|
||||
self.window.toast("Alle Access Points sind bereits in NetBox.", "info")
|
||||
return False
|
||||
dialog = SiteMappingDialog(self.window, rows, self.engine.ap_sites, self.engine.group_tenants,
|
||||
self.tenant.valid_data())
|
||||
if not dialog.exec():
|
||||
return False
|
||||
settings = self._settings()
|
||||
site_map, ap_sites = dict(settings.get("site_map") or {}), dict(settings.get("ap_sites") or {})
|
||||
for (kind, key), value in dialog.result.items():
|
||||
(site_map if kind == "site" else ap_sites)[key] = value
|
||||
self._store(site_map=site_map, ap_sites=ap_sites)
|
||||
self._refresh()
|
||||
return True
|
||||
|
||||
def sync(self):
|
||||
if not self.engine or self.tasks.busy:
|
||||
return
|
||||
new = self._new_aps()
|
||||
role_id = self.role.valid_data()
|
||||
if new and not role_id:
|
||||
widgets.message(self.window, "Geräterolle fehlt", "Für neue Access Points bitte eine Geräterolle wählen.",
|
||||
"info")
|
||||
return
|
||||
if any(not self._placement(ap)["stored"] for ap in new) and not self.map_sites():
|
||||
return
|
||||
default_site = self.default_site.valid_data()
|
||||
placements = {}
|
||||
for ap in new:
|
||||
placement = self._placement(ap)
|
||||
placements[ap_key(ap)] = {"site": placement["site"], "tenant": self._tenant_for(placement)}
|
||||
homeless = [ap["name"] for ap in new if not placements[ap_key(ap)]["site"]]
|
||||
if homeless and not default_site:
|
||||
widgets.message(self.window, "Standard-Standort fehlt",
|
||||
f"{len(homeless)} neue Access Points haben keinen Standort. NetBox verlangt für jedes "
|
||||
"Gerät einen Standort – bitte oben einen Standard-Standort wählen.", "info",
|
||||
"\n".join(homeless))
|
||||
return
|
||||
engine, aps, rename = self.engine, list(self.aps), self.rename.isChecked()
|
||||
|
||||
def run(dry_run):
|
||||
return lambda ctx: engine.sync(aps, placements, role_id, rename, dry_run=dry_run, default_site=default_site)
|
||||
|
||||
def show(report):
|
||||
def ask():
|
||||
if ClientPreviewDialog(self.window, report).exec():
|
||||
self.tasks.run(run(False), title="Access Points übertragen", area="app", on_success=applied,
|
||||
on_error=self.actions._netbox_failed)
|
||||
QTimer.singleShot(0, ask)
|
||||
|
||||
def applied(report):
|
||||
for error in report["errors"]:
|
||||
logger("app").error("%s", error)
|
||||
text = (f"{report['devices_created']} Access Points angelegt, {report['devices_updated']} aktualisiert"
|
||||
+ (f", {len(report['errors'])} Fehler" if report["errors"] else ""))
|
||||
logger("app").log(25, "%s", text)
|
||||
self.window.toast(text, "warning" if report["errors"] else "success")
|
||||
QTimer.singleShot(0, self.compare)
|
||||
|
||||
self.tasks.run(run(True), title="Änderungen berechnen", area="app", on_success=show,
|
||||
on_error=self.actions._netbox_failed)
|
||||
@@ -0,0 +1,338 @@
|
||||
import os
|
||||
import subprocess
|
||||
import webbrowser
|
||||
|
||||
from PySide6.QtCore import QObject, Qt, QTimer, Signal
|
||||
from PySide6.QtGui import QGuiApplication
|
||||
from PySide6.QtWidgets import QFormLayout, QHBoxLayout, QLineEdit, QMenu, QStackedWidget
|
||||
|
||||
from netbox_sync.core import netscan
|
||||
from netbox_sync.ui import widgets
|
||||
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.tasks import logger
|
||||
from netbox_sync.ui.theme import theme
|
||||
from netbox_sync.ui.widgets import Card, EmptyState, SearchField, Table, button, checkbox, label
|
||||
|
||||
COMPARE_DOT = {"match": "success", "differs": "warning", "missing": "danger", "offline": "text_faint"}
|
||||
|
||||
|
||||
class _Results(QObject):
|
||||
"""Carries hosts from the scan threads to the UI thread."""
|
||||
|
||||
host = Signal(object)
|
||||
|
||||
|
||||
def _name(row):
|
||||
return row.get("dns_name") or row.get("netbios_name") or ""
|
||||
|
||||
|
||||
def _netbox(row, key):
|
||||
return ", ".join(dict.fromkeys(entry[key] for entry in row.get("netbox", []) if entry[key]))
|
||||
|
||||
|
||||
def _services(row):
|
||||
return ", ".join(f"{item['service'] or 'TCP'} ({item['port']})" for item in row.get("ports", []))
|
||||
|
||||
|
||||
class ScannerPage(Page):
|
||||
title = "Netzwerk-Scanner"
|
||||
subtitle = ("IP-Bereiche nach erreichbaren Geräten, Namen, MAC-Adressen und offenen Diensten durchsuchen. "
|
||||
"Jede Adresse wird automatisch mit NetBox abgeglichen – es wird nichts geschrieben.")
|
||||
|
||||
def __init__(self, window):
|
||||
super().__init__(window)
|
||||
self.rows = {}
|
||||
self.netbox = {}
|
||||
self.netbox_note = ""
|
||||
self.scan_task = None
|
||||
self.results = _Results()
|
||||
self.results.host.connect(self._host_found)
|
||||
self.refresh_timer = QTimer(self)
|
||||
self.refresh_timer.setSingleShot(True)
|
||||
self.refresh_timer.setInterval(250)
|
||||
self.refresh_timer.timeout.connect(self._refresh)
|
||||
|
||||
target_card = Card("Scan")
|
||||
form = QFormLayout()
|
||||
form.setHorizontalSpacing(18)
|
||||
targets = QHBoxLayout()
|
||||
self.targets = QLineEdit()
|
||||
self.targets.setPlaceholderText("z. B. 192.168.1.1-254, 10.0.0.0/24, server01")
|
||||
targets.addWidget(self.targets, 1)
|
||||
self.own_network = button("Eigenes Netz", "network", tooltip="Netze dieses Rechners übernehmen")
|
||||
self.own_network.clicked.connect(self._own_network_menu)
|
||||
targets.addWidget(self.own_network)
|
||||
form.addRow("IP-Bereiche", targets)
|
||||
self.ports = QLineEdit()
|
||||
self.ports.setPlaceholderText(netscan.DEFAULT_PORTS)
|
||||
form.addRow("Ports", self.ports)
|
||||
target_card.add(form)
|
||||
self.scan_button = target_card.add_action(button("Scannen", "play", "primary", on_click=self.scan))
|
||||
self.body.addWidget(target_card)
|
||||
|
||||
result_card = Card("Ergebnisse", "Name aus DNS bzw. NetBIOS; NetBox-Spalten aus den IP-Adressen in NetBox.")
|
||||
filters = QHBoxLayout()
|
||||
self.search = SearchField("IP, Name, MAC, Dienst, NetBox-Objekt …")
|
||||
self.only_alive = checkbox("Nur erreichbare", True)
|
||||
self.only_issues = checkbox("Nur Abweichungen",
|
||||
tooltip="Nicht in NetBox, abweichender Name oder in NetBox, aber nicht erreichbar")
|
||||
filters.addWidget(self.search, 2)
|
||||
filters.addWidget(self.only_alive)
|
||||
filters.addWidget(self.only_issues)
|
||||
filters.addStretch(1)
|
||||
result_card.add(filters)
|
||||
columns = [
|
||||
Column("ip", "IP-Adresse", 130, dot=lambda row: "success" if row.get("alive") else "text_faint"),
|
||||
Column("name", "Name", 210, value=_name,
|
||||
tooltip=lambda row: "\n".join(filter(None, (
|
||||
f"DNS: {row['dns_name']}" if row.get("dns_name") else "",
|
||||
f"NetBIOS: {row['netbios_name']}" if row.get("netbios_name") else "",
|
||||
f"Arbeitsgruppe/Domäne: {row['workgroup']}" if row.get("workgroup") else "")))),
|
||||
Column("mac", "MAC-Adresse", 140),
|
||||
Column("services", "Dienste", 230, value=_services, tooltip=_services),
|
||||
Column("rtt", "Antwort", 70, value=lambda row: "" if row.get("rtt") is None else f"{row['rtt']} ms",
|
||||
sort=lambda row: row.get("rtt") if row.get("rtt") is not None else 99999,
|
||||
color=lambda row: "text_muted"),
|
||||
Column("nb_object", "NetBox-Objekt", 190, value=lambda row: _netbox(row, "object"),
|
||||
tooltip=lambda row: "\n".join(
|
||||
f"{entry['object_kind'] or 'IP'} {entry['object']} · {entry['vrf'] or 'global'} · "
|
||||
f"{entry['tenant'] or 'ohne Mandant'} · {entry['status']}"
|
||||
+ (f"\n{entry['description']}" if entry["description"] else "")
|
||||
for entry in row.get("netbox", []))),
|
||||
Column("nb_dns", "NetBox-DNS-Name", 190, value=lambda row: _netbox(row, "dns_name")),
|
||||
Column("compare", "Abgleich", 170, value=lambda row: netscan.COMPARE_TEXT.get(row.get("compare"), ""),
|
||||
dot=lambda row: COMPARE_DOT.get(row.get("compare"))),
|
||||
]
|
||||
self.model = RowTableModel(columns, row_id=lambda row: row["ip"])
|
||||
self.proxy = FilterProxy(self.model)
|
||||
self.table = Table()
|
||||
self.table.setModel(self.proxy)
|
||||
for index, column in enumerate(columns):
|
||||
self.table.setColumnWidth(index, column.width)
|
||||
self.table.sortByColumn(0, Qt.AscendingOrder)
|
||||
self.table.doubleClicked.connect(lambda _index: self._open_default())
|
||||
self.table.setContextMenuPolicy(Qt.CustomContextMenu)
|
||||
self.table.customContextMenuRequested.connect(self._context_menu)
|
||||
self.stack = QStackedWidget()
|
||||
self.stack.addWidget(EmptyState("search", "Noch nicht gescannt",
|
||||
"IP-Bereiche eintragen und „Scannen“ wählen. Ist ein NetBox-Zugang "
|
||||
"eingerichtet, erscheinen Objekt und DNS-Name aus NetBox automatisch."))
|
||||
self.stack.addWidget(self.table)
|
||||
result_card.add(self.stack, 1)
|
||||
self.summary = label("", muted=True)
|
||||
result_card.add(self.summary)
|
||||
self.body.addWidget(result_card, 1)
|
||||
|
||||
self.search.textChanged.connect(self.proxy.set_text)
|
||||
self.only_alive.toggled.connect(self._apply_filters)
|
||||
self.only_issues.toggled.connect(self._apply_filters)
|
||||
self.targets.editingFinished.connect(
|
||||
lambda: self.state.update_settings(scanner_targets=self.targets.text().strip()))
|
||||
self.ports.editingFinished.connect(lambda: self.state.update_settings(scanner_ports=self.ports.text().strip()))
|
||||
self.targets.returnPressed.connect(self.scan)
|
||||
self.targets.setText(self.state.settings.get("scanner_targets", ""))
|
||||
self.ports.setText(self.state.settings.get("scanner_ports", ""))
|
||||
self._apply_filters()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def on_show(self):
|
||||
if not self.targets.text().strip():
|
||||
networks = netscan.local_networks()
|
||||
if networks:
|
||||
self.targets.setText(networks[0])
|
||||
|
||||
def set_busy(self, busy):
|
||||
scanning = busy and self.scan_task is not None and self.tasks.current is self.scan_task
|
||||
self.scan_button.setText("Stopp" if scanning else "Scannen")
|
||||
widgets.set_enabled(self.scan_button, scanning or not busy, "Bitte warten …")
|
||||
|
||||
def _own_network_menu(self):
|
||||
networks = netscan.local_networks()
|
||||
if not networks:
|
||||
self.window.toast("Kein eigenes IPv4-Netz gefunden.", "info")
|
||||
return
|
||||
menu = QMenu(self)
|
||||
for network in networks:
|
||||
menu.addAction(network, lambda n=network: self.targets.setText(n))
|
||||
if len(networks) > 1:
|
||||
menu.addSeparator()
|
||||
menu.addAction("Alle", lambda: self.targets.setText(", ".join(networks)))
|
||||
menu.exec(self.own_network.mapToGlobal(self.own_network.rect().bottomLeft()))
|
||||
|
||||
def _apply_filters(self, *_args):
|
||||
self.proxy.set_predicate("alive", (lambda row: row.get("alive") or row.get("compare") == "offline")
|
||||
if self.only_alive.isChecked() else None)
|
||||
self.proxy.set_predicate("issues", (lambda row: row.get("compare") in ("differs", "missing", "offline"))
|
||||
if self.only_issues.isChecked() else None)
|
||||
self._update_summary()
|
||||
|
||||
def _update_summary(self):
|
||||
rows = list(self.rows.values())
|
||||
alive = sum(1 for row in rows if row.get("alive"))
|
||||
counts = {key: sum(1 for row in rows if row.get("compare") == key) for key in COMPARE_DOT}
|
||||
parts = [f"{alive} erreichbar"]
|
||||
if self.netbox_note:
|
||||
parts.append(self.netbox_note)
|
||||
else:
|
||||
parts += [f"{counts['match']} stimmen mit NetBox überein", f"{counts['differs']} abweichend",
|
||||
f"{counts['missing']} nicht in NetBox", f"{counts['offline']} in NetBox, nicht erreichbar"]
|
||||
self.summary.setText(" · ".join(parts))
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Scan
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def scan(self):
|
||||
if self.scan_task is not None and self.tasks.current is self.scan_task:
|
||||
self.tasks.cancel()
|
||||
return
|
||||
if self.tasks.busy:
|
||||
return
|
||||
try:
|
||||
ips = netscan.expand_ips(self.targets.text())
|
||||
ports = netscan.parse_ports(self.ports.text().strip() or netscan.DEFAULT_PORTS)
|
||||
except netscan.ScanError as error:
|
||||
widgets.message(self.window, "Eingabe prüfen", str(error), "warning")
|
||||
return
|
||||
self.state.update_settings(scanner_targets=self.targets.text().strip(), scanner_ports=self.ports.text().strip())
|
||||
compare = bool(self.state.profile) and not self.state.offline and self.state.netbox_configured()
|
||||
connect = self.actions._connector() if compare else None
|
||||
self.rows, self.netbox = {}, {}
|
||||
self.netbox_note = "" if compare else "kein NetBox-Abgleich (kein Zugang im Profil oder Offline-Modus)"
|
||||
self.model.set_rows([])
|
||||
self.stack.setCurrentIndex(1)
|
||||
results = self.results
|
||||
|
||||
def work(ctx):
|
||||
netbox_map, note = {}, ""
|
||||
if connect:
|
||||
try:
|
||||
ctx.progress(0, len(ips), "NetBox-Abgleich …")
|
||||
netbox_map = netscan.netbox_lookup(connect(ctx), ips)
|
||||
ctx.log(f"NetBox: {sum(len(items) for items in netbox_map.values())} IP-Adressen in den "
|
||||
"gescannten Bereichen")
|
||||
except Exception as error: # noqa: BLE001 - the scan works without NetBox
|
||||
note = f"NetBox-Abgleich nicht möglich: {error}"
|
||||
ctx.log(note, "warning")
|
||||
results.host.emit({"__netbox__": netbox_map, "__note__": note})
|
||||
ctx.log(f"Scanne {len(ips)} Adressen, {len(ports)} Ports …")
|
||||
done = [0]
|
||||
|
||||
def found(host):
|
||||
done[0] += 1
|
||||
ctx.progress(done[0], len(ips), host["ip"])
|
||||
results.host.emit(host)
|
||||
netscan.scan(ips, ports, found, lambda: ctx.cancelled)
|
||||
ctx.check_cancelled()
|
||||
return len(ips)
|
||||
|
||||
def finished(count):
|
||||
self._finish()
|
||||
alive = sum(1 for row in self.rows.values() if row.get("alive"))
|
||||
logger("app").log(25, "Scan abgeschlossen: %s von %s Adressen erreichbar", alive, count)
|
||||
self.window.toast(f"{alive} von {count} Adressen erreichbar")
|
||||
|
||||
self.scan_task = self.tasks.run(work, title=f"{len(ips)} Adressen scannen", area="app",
|
||||
on_success=finished, on_error=lambda error: widgets.error(
|
||||
self.window, "Scan fehlgeschlagen", str(error)),
|
||||
on_finished=self._scan_ended)
|
||||
self.set_busy(True)
|
||||
|
||||
def _scan_ended(self):
|
||||
self.scan_task = None
|
||||
self._finish()
|
||||
self.set_busy(self.tasks.busy)
|
||||
|
||||
def _host_found(self, host):
|
||||
if "__netbox__" in host:
|
||||
self.netbox = host["__netbox__"]
|
||||
if host["__note__"]:
|
||||
self.netbox_note = host["__note__"]
|
||||
return
|
||||
row = dict(host, netbox=self.netbox.get(host["ip"], []))
|
||||
row["compare"] = netscan.compare(row, row["netbox"]) if not self.netbox_note else ""
|
||||
if row["alive"] or row["netbox"]:
|
||||
self.rows[row["ip"]] = row
|
||||
if not self.refresh_timer.isActive():
|
||||
self.refresh_timer.start()
|
||||
|
||||
def _finish(self):
|
||||
# Documented addresses that never answered are listed as "not reachable".
|
||||
for ip, entries in self.netbox.items():
|
||||
if ip not in self.rows:
|
||||
self.rows[ip] = {"ip": ip, "alive": False, "netbox": entries, "compare": "offline"}
|
||||
self._refresh()
|
||||
|
||||
def _refresh(self):
|
||||
self.model.set_rows(list(self.rows.values()))
|
||||
self._update_summary()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Actions on hosts
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _selected(self):
|
||||
rows = self.table.selectionModel().selectedRows()
|
||||
return [self.proxy.row_at(index) for index in rows]
|
||||
|
||||
def _netbox_url(self, entry):
|
||||
base = (self.state.profile or {}).get("netbox_url", "").rstrip("/")
|
||||
return f"{base}/ipam/ip-addresses/{entry['id']}/" if base else entry.get("url")
|
||||
|
||||
def _open_default(self):
|
||||
selected = self._selected()
|
||||
if not selected:
|
||||
return
|
||||
row = selected[0]
|
||||
ports = {item["port"] for item in row.get("ports", [])}
|
||||
if ports & {443, 8443, 8006}:
|
||||
port = min(ports & {443, 8443, 8006})
|
||||
webbrowser.open(f"https://{row['ip']}" + ("" if port == 443 else f":{port}"))
|
||||
elif ports & {80, 8080}:
|
||||
port = min(ports & {80, 8080})
|
||||
webbrowser.open(f"http://{row['ip']}" + ("" if port == 80 else f":{port}"))
|
||||
elif 3389 in ports:
|
||||
self._rdp(row)
|
||||
elif 445 in ports:
|
||||
os.startfile(f"\\\\{row['ip']}") # noqa: S606 - Windows Explorer
|
||||
elif row.get("netbox"):
|
||||
webbrowser.open(self._netbox_url(row["netbox"][0]))
|
||||
|
||||
@staticmethod
|
||||
def _rdp(row):
|
||||
subprocess.Popen(["mstsc", f"/v:{row['ip']}"]) # noqa: S603, S607 - user action
|
||||
|
||||
def _context_menu(self, position):
|
||||
selected = self._selected()
|
||||
if not selected:
|
||||
return
|
||||
row = selected[0]
|
||||
ports = {item["port"] for item in row.get("ports", [])}
|
||||
muted = theme.color("text_muted")
|
||||
menu = QMenu(self)
|
||||
for port, scheme in ((443, "https"), (8443, "https"), (8006, "https"), (80, "http"), (8080, "http")):
|
||||
if port in ports:
|
||||
suffix = "" if port in (80, 443) else f":{port}"
|
||||
url = f"{scheme}://{row['ip']}{suffix}"
|
||||
menu.addAction(icon("globe", muted), f"Im Browser öffnen ({url})", lambda u=url: webbrowser.open(u))
|
||||
if 3389 in ports:
|
||||
menu.addAction(icon("monitor", muted), "Remotedesktop verbinden", lambda: self._rdp(row))
|
||||
if 445 in ports or 139 in ports:
|
||||
menu.addAction(icon("folder", muted), "Freigaben öffnen",
|
||||
lambda: os.startfile(f"\\\\{row['ip']}")) # noqa: S606
|
||||
for entry in row.get("netbox", []):
|
||||
menu.addAction(icon("upload", muted), f"In NetBox öffnen ({entry['object'] or entry['dns_name'] or 'IP'})",
|
||||
lambda e=entry: webbrowser.open(self._netbox_url(e)))
|
||||
if not menu.isEmpty():
|
||||
menu.addSeparator()
|
||||
clipboard = QGuiApplication.clipboard()
|
||||
menu.addAction(icon("copy", muted), "IP-Adresse kopieren",
|
||||
lambda: clipboard.setText("\n".join(item["ip"] for item in selected)))
|
||||
if _name(row):
|
||||
menu.addAction(icon("copy", muted), "Name kopieren", lambda: clipboard.setText(_name(row)))
|
||||
if row.get("mac"):
|
||||
menu.addAction(icon("copy", muted), "MAC-Adresse kopieren", lambda: clipboard.setText(row["mac"]))
|
||||
menu.exec(self.table.viewport().mapToGlobal(position))
|
||||
@@ -60,7 +60,7 @@ class SettingsPage(Page):
|
||||
self.parallel_wmi.setRange(1, 32)
|
||||
self.parallel_wmi.setSuffix(" gleichzeitig")
|
||||
self.parallel_wmi.setFixedWidth(160)
|
||||
form.addRow("PowerShell-Sitzungen", self.parallel_wmi)
|
||||
form.addRow("WinRM-Sitzungen", self.parallel_wmi)
|
||||
clients.add(form)
|
||||
clients.add(label("Kennwörter aus dem Windows-Anmeldefenster werden nie gespeichert, sondern nur bis zum "
|
||||
"Beenden des Programms im Arbeitsspeicher gehalten.", muted=True, wrap=True))
|
||||
@@ -81,6 +81,18 @@ class SettingsPage(Page):
|
||||
"nicht auf einem anderen Rechner entschlüsselt werden.", muted=True, wrap=True))
|
||||
self.body.addWidget(data)
|
||||
|
||||
updates = Card("Updates", "Neue Versionen kommen aus den Releases von Netbox-Import-Desktop (Gitea).")
|
||||
line = QHBoxLayout()
|
||||
self.auto_update = checkbox("Beim Start nach Updates suchen")
|
||||
line.addWidget(self.auto_update)
|
||||
line.addStretch(1)
|
||||
line.addWidget(button("Jetzt nach Updates suchen", "refresh", on_click=lambda: window.updates.check()))
|
||||
updates.add(line)
|
||||
updates.add(label("Vor der Installation wird immer gefragt. Die installierte Version aktualisiert sich über "
|
||||
"das Setup, die portable EXE tauscht sich selbst aus; danach startet die Anwendung neu.",
|
||||
muted=True, wrap=True))
|
||||
self.body.addWidget(updates)
|
||||
|
||||
about = Card("Über")
|
||||
about.add(label(f"<b>{APP_NAME}</b> Version {APP_VERSION}"))
|
||||
about.add(label(f"© {APP_PUBLISHER}", muted=True))
|
||||
@@ -90,18 +102,21 @@ class SettingsPage(Page):
|
||||
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.parallel_wmi.valueChanged.connect(lambda value: self.state.update_settings(parallel_wmi=value))
|
||||
self.auto_update.toggled.connect(lambda value: self.state.update_settings(auto_update_check=value))
|
||||
self.state.settings_changed.connect(self.load)
|
||||
self.load()
|
||||
|
||||
def load(self):
|
||||
settings = self.state.settings
|
||||
for widget in (self.parallel, self.parallel_wmi, self.enable_lldp, *self.theme_buttons.values()):
|
||||
widgets_ = (self.parallel, self.parallel_wmi, self.enable_lldp, self.auto_update, *self.theme_buttons.values())
|
||||
for widget in widgets_:
|
||||
widget.blockSignals(True)
|
||||
self.parallel.setValue(int(settings.get("parallel_ssh", 4)))
|
||||
self.parallel_wmi.setValue(int(settings.get("parallel_wmi", 8)))
|
||||
self.enable_lldp.setChecked(bool(settings.get("enable_lldp")))
|
||||
self.auto_update.setChecked(bool(settings.get("auto_update_check", True)))
|
||||
self.theme_buttons.get(settings.get("theme", "system"), self.theme_buttons["system"]).setChecked(True)
|
||||
for widget in (self.parallel, self.parallel_wmi, self.enable_lldp, *self.theme_buttons.values()):
|
||||
for widget in widgets_:
|
||||
widget.blockSignals(False)
|
||||
|
||||
def _set_theme(self, mode):
|
||||
|
||||
@@ -4,7 +4,7 @@ import uuid
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWidgets import QComboBox, QHBoxLayout, QMenu, QSplitter, QStackedWidget
|
||||
|
||||
from netbox_sync.core.switches import PLATFORMS
|
||||
from netbox_sync.core.switches import PLATFORMS, ignored_vlans, vlan_label, without_vlans
|
||||
from netbox_sync.ui import widgets
|
||||
from netbox_sync.ui.dialogs import AddSwitchesDialog, RawDataDialog, SwitchDialog
|
||||
from netbox_sync.ui.icons import icon
|
||||
@@ -108,6 +108,8 @@ class SwitchesPage(Page):
|
||||
dot=lambda row: "success" if row["connected"] else ("text_faint" if row["enabled"] else "danger")),
|
||||
Column("speed", "Geschwindigkeit", 115, value=lambda row: _speed(row.get("speed_mbps")),
|
||||
sort=lambda row: row.get("speed_mbps") or 0),
|
||||
Column("vlans", "VLANs", 110, value=lambda row: vlan_label(without_vlans(
|
||||
row.get("vlans"), ignored_vlans((self.state.profile or {}).get("vlan_map"))))),
|
||||
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", "")),
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Update check on start and on demand, download and installation."""
|
||||
|
||||
import tempfile
|
||||
import webbrowser
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import QObject, QThreadPool, QTimer
|
||||
|
||||
from netbox_sync import APP_VERSION
|
||||
from netbox_sync.core import updater
|
||||
from netbox_sync.ui import widgets
|
||||
from netbox_sync.ui.tasks import Task, logger
|
||||
|
||||
|
||||
class UpdateManager(QObject):
|
||||
def __init__(self, window):
|
||||
super().__init__(window)
|
||||
self.window = window
|
||||
self.state = window.state
|
||||
self.tasks = window.tasks
|
||||
self._check = None
|
||||
|
||||
def check_on_start(self):
|
||||
updater.remove_leftovers()
|
||||
if self.state.settings.get("auto_update_check", True):
|
||||
# A moment after start, so the window is usable right away.
|
||||
QTimer.singleShot(4000, lambda: self.check(silent=True))
|
||||
|
||||
def check(self, silent=False):
|
||||
"""Ask Gitea for a newer release without blocking other tasks."""
|
||||
if self._check is not None:
|
||||
return
|
||||
task = Task(lambda _ctx: updater.check_for_update(), "app", "Nach Updates suchen")
|
||||
self._check = task
|
||||
|
||||
def done(release):
|
||||
if release is None:
|
||||
logger("app").info("Keine neuere Version gefunden (installiert: %s)", APP_VERSION)
|
||||
if not silent:
|
||||
self.window.toast(f"{APP_VERSION} ist die aktuelle Version.", "info")
|
||||
return
|
||||
if silent and self.state.settings.get("skipped_version") == release["version"]:
|
||||
return
|
||||
self._offer(release)
|
||||
|
||||
def failed(error):
|
||||
logger("app").warning("Update-Prüfung fehlgeschlagen: %s", error)
|
||||
if not silent:
|
||||
widgets.message(self.window, "Update-Prüfung fehlgeschlagen", str(error), "warning")
|
||||
|
||||
task.signals.succeeded.connect(done)
|
||||
task.signals.failed.connect(failed)
|
||||
task.signals.finished.connect(lambda: setattr(self, "_check", None))
|
||||
QThreadPool.globalInstance().start(task)
|
||||
|
||||
def _offer(self, release):
|
||||
kind = updater.install_kind()
|
||||
asset = updater.pick_asset(release, kind) if kind else None
|
||||
text = (f"Version {release['version']} ist verfügbar (installiert: {APP_VERSION}).\n\n"
|
||||
+ ("Das Update wird heruntergeladen und installiert; die Anwendung startet danach neu."
|
||||
if asset else "Für diese Installation gibt es keine passende Datei – bitte die Release-Seite "
|
||||
"öffnen."))
|
||||
buttons = ("Später", "Diese Version überspringen", "Jetzt aktualisieren" if asset else "Release-Seite öffnen")
|
||||
choice = widgets.message(self.window, "Update verfügbar", text, "info", release["notes"] or None,
|
||||
buttons=buttons, default=2)
|
||||
if choice == 1:
|
||||
self.state.update_settings(skipped_version=release["version"])
|
||||
elif choice == 2 and asset:
|
||||
self._install(release, kind, *asset)
|
||||
elif choice == 2 and release["page"]:
|
||||
webbrowser.open(release["page"])
|
||||
|
||||
def _install(self, release, kind, name, asset):
|
||||
if self.tasks.busy:
|
||||
widgets.message(self.window, "Bitte warten", f"„{self.tasks.current.title}“ läuft noch. Das Update "
|
||||
"kann danach über Einstellungen › Updates gestartet werden.", "info")
|
||||
return
|
||||
if kind == "portable":
|
||||
target = updater.portable_download_path()
|
||||
else:
|
||||
target = Path(tempfile.mkdtemp(prefix="netbox-sync-update-")) / name
|
||||
|
||||
def work(ctx):
|
||||
ctx.log(f"Lade {name} ({release['version']}) herunter …")
|
||||
|
||||
def progress(done, total):
|
||||
ctx.progress(done // 1024, max(total // 1024, 1), f"{done / 1_048_576:.1f} MB")
|
||||
return updater.download(asset, target, progress, lambda: ctx.cancelled)
|
||||
|
||||
def downloaded(path):
|
||||
try:
|
||||
if kind == "portable":
|
||||
updater.apply_portable(path)
|
||||
else:
|
||||
updater.apply_installer(path)
|
||||
except OSError as error:
|
||||
widgets.error(self.window, "Update fehlgeschlagen", f"Das Update konnte nicht gestartet werden: "
|
||||
f"{error}")
|
||||
return
|
||||
logger("app").log(25, "Update auf %s wird installiert – Anwendung wird beendet", release["version"])
|
||||
# After the task has finished, so closing does not ask about a running task.
|
||||
QTimer.singleShot(0, self.window.close)
|
||||
|
||||
self.tasks.run(work, title=f"Update {release['version']} herunterladen", area="app",
|
||||
on_success=downloaded,
|
||||
on_error=lambda error: widgets.error(self.window, "Update fehlgeschlagen", str(error)))
|
||||
@@ -255,6 +255,28 @@ class EmptyState(QWidget):
|
||||
layout.addSpacing(6)
|
||||
layout.addLayout(buttons)
|
||||
layout.addStretch(2)
|
||||
layout.setContentsMargins(24, 16, 24, 16)
|
||||
|
||||
def _heights(self, width):
|
||||
width = max(width, 320) - 48
|
||||
core = 32 + self.title_label.heightForWidth(width) + 10
|
||||
if self.action is not None:
|
||||
core += 16 + self.action.sizeHint().height()
|
||||
return core, self.text_label.heightForWidth(min(width, 520)) + 10, 56 + 10
|
||||
|
||||
def minimumSizeHint(self):
|
||||
# Title and button always fit; icon and text are dropped when space is short.
|
||||
core, _text, _icon = self._heights(self.width())
|
||||
return QSize(260, core)
|
||||
|
||||
def resizeEvent(self, event):
|
||||
super().resizeEvent(event)
|
||||
# Word-wrapped labels report almost no minimum height, so a small card
|
||||
# would squeeze icon, title, text and button on top of each other.
|
||||
core, text, icon_height = self._heights(event.size().width())
|
||||
available = event.size().height()
|
||||
self.text_label.setVisible(available >= core + text)
|
||||
self.icon_label.setVisible(available >= core + text + icon_height)
|
||||
|
||||
def set_text(self, title=None, text=None):
|
||||
if title is not None:
|
||||
|
||||
@@ -3,3 +3,4 @@ pynetbox>=7.4
|
||||
pyvmomi>=8.0
|
||||
requests>=2.31
|
||||
paramiko>=3.4
|
||||
pywin32>=306; sys_platform == "win32"
|
||||
@@ -21,6 +21,8 @@ class Record(SimpleNamespace):
|
||||
|
||||
|
||||
def _matches(record, key, value):
|
||||
if isinstance(value, list): # pynetbox sends lists as repeated query parameters (OR)
|
||||
return any(_matches(record, key, item) for item in value)
|
||||
if key == "brief":
|
||||
return True
|
||||
if key.endswith("__ie"):
|
||||
@@ -74,7 +76,7 @@ class FakeNetBox:
|
||||
mac_addresses=Endpoint(), platforms=Endpoint(),
|
||||
manufacturers=Endpoint(), device_types=Endpoint(), device_roles=Endpoint(),
|
||||
sites=Endpoint())
|
||||
self.ipam = SimpleNamespace(ip_addresses=Endpoint(), prefixes=Endpoint(), vrfs=Endpoint())
|
||||
self.ipam = SimpleNamespace(ip_addresses=Endpoint(), prefixes=Endpoint(), vrfs=Endpoint(), vlans=Endpoint())
|
||||
self.virtualization = SimpleNamespace(clusters=Endpoint(), cluster_types=Endpoint(), virtual_machines=Endpoint(),
|
||||
interfaces=Endpoint())
|
||||
self.tenancy = SimpleNamespace(tenants=Endpoint())
|
||||
@@ -0,0 +1,117 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fake_netbox import FakeNetBox, Record
|
||||
|
||||
from netbox_sync.core.ap_sync import APImportError, APSyncEngine, ap_key, parse_csv
|
||||
|
||||
CSV = (
|
||||
'"AP Name","MAC Address","Serial Number","Internal IP address","Model","Config Status",'
|
||||
'"Active Channel for 2.4 GHz","Current Site","Firmware","Uptime"\n'
|
||||
'"Kita Sonne EG ","7c:5a:1c:00:00:01","p52000000000001","10.10.230.101","APX320","UP_TO_DATE","6",'
|
||||
'"Kita Sonnenschein","v2.3.6","1"\n'
|
||||
'"Kita Sonne OG","7C:5A:1C:00:00:02","P52000000000002","10.10.230.102","APX320","UP_TO_DATE","1",'
|
||||
'"Kita Sonnenschein","v2.3.6","1"\n'
|
||||
'"Büro ohne Standort","c8:4f:86:00:00:03","P52000000000003","10.10.230.102","AP6 420","UPDATE_PENDING","",'
|
||||
'"","v1.10.3192",""\n'
|
||||
)
|
||||
|
||||
|
||||
def _netbox():
|
||||
nb = FakeNetBox()
|
||||
group = SimpleNamespace(id=3, name="Kunde")
|
||||
nb.tenancy.tenants.records += [Record(nb.tenancy.tenants, id=7, name="Kunde RZ", group=group),
|
||||
Record(nb.tenancy.tenants, id=8, name="Kunde Kita", group=group)]
|
||||
nb.dcim.sites.records += [
|
||||
Record(nb.dcim.sites, id=20, name="Kita Sonnenschein Jena", tenant=SimpleNamespace(id=8), tenant_group=group),
|
||||
Record(nb.dcim.sites, id=21, name="Geschäftsstelle", tenant=SimpleNamespace(id=7), tenant_group=group),
|
||||
]
|
||||
nb.dcim.device_roles.records.append(Record(nb.dcim.device_roles, id=30, name="Access Point"))
|
||||
sophos = Record(nb.dcim.manufacturers, id=40, name="Sophos", slug="sophos")
|
||||
nb.dcim.manufacturers.records.append(sophos)
|
||||
# Known by serial (other spelling), known only by name, and one missing in Sophos.
|
||||
nb.dcim.devices.records += [
|
||||
Record(nb.dcim.devices, id=101, name="AP alt", serial="P52000000000002", tenant=SimpleNamespace(id=8),
|
||||
tenant_group=group, manufacturer=sophos, site=SimpleNamespace(id=20), description="Firmware v2.3.5",
|
||||
primary_ip4=None),
|
||||
Record(nb.dcim.devices, id=102, name="Kita Sonne EG", serial="", tenant=SimpleNamespace(id=8),
|
||||
tenant_group=group, manufacturer=sophos, site=SimpleNamespace(id=20), description="",
|
||||
primary_ip4=None),
|
||||
Record(nb.dcim.devices, id=103, name="Abgebaut", serial="X1", tenant=SimpleNamespace(id=8),
|
||||
tenant_group=group, manufacturer=sophos, site=SimpleNamespace(id=20), description="",
|
||||
primary_ip4=None),
|
||||
]
|
||||
return nb
|
||||
|
||||
|
||||
def test_sophos_export_is_parsed_and_checked():
|
||||
aps = parse_csv(CSV.encode("utf-8"))
|
||||
assert [ap["name"] for ap in aps] == ["Kita Sonne EG", "Kita Sonne OG", "Büro ohne Standort"]
|
||||
assert aps[1]["mac"] == "7C:5A:1C:00:00:02" and aps[0]["serial"] == "P52000000000001"
|
||||
assert aps[2]["issues"][0] == "kein Standort in Sophos"
|
||||
assert any("10.10.230.102 doppelt" in issue for issue in aps[1]["issues"])
|
||||
assert parse_csv(CSV.replace(",", ";").encode("cp1252"))[2]["name"] == "Büro ohne Standort"
|
||||
with pytest.raises(APImportError):
|
||||
parse_csv(b"foo,bar\n1,2\n")
|
||||
|
||||
|
||||
def test_existing_aps_are_found_by_serial_and_name_and_missing_ones_reported():
|
||||
nb = _netbox()
|
||||
engine = APSyncEngine(nb)
|
||||
engine.load_context(7)
|
||||
assert [site["name"] for site in engine.ap_sites] == ["Geschäftsstelle", "Kita Sonnenschein Jena"]
|
||||
assert engine.suggest_site("Kita Sonnenschein") == 20 and engine.suggest_site("") is None
|
||||
aps = parse_csv(CSV)
|
||||
only_netbox = engine.match(aps)
|
||||
assert [(ap["device"].id if ap["device"] else None, ap["method"]) for ap in aps] == [
|
||||
(102, "Name"), (101, "Seriennummer"), (None, "")]
|
||||
assert [device.name for device in only_netbox] == ["Abgebaut"]
|
||||
|
||||
|
||||
def test_sync_creates_new_aps_with_site_tenant_and_updates_existing():
|
||||
nb = _netbox()
|
||||
engine = APSyncEngine(nb)
|
||||
engine.load_context(7)
|
||||
aps = parse_csv(CSV)
|
||||
engine.match(aps)
|
||||
sites = {ap_key(aps[2]): {"site": 21}}
|
||||
|
||||
preview = engine.sync(aps, sites, role_id=30, dry_run=True)
|
||||
assert preview["errors"] == [] and preview["devices_created"] == 1 and preview["devices_updated"] == 2
|
||||
assert nb.dcim.devices.created == [] and nb.ipam.ip_addresses.created == []
|
||||
|
||||
report = engine.sync(aps, sites, role_id=30, dry_run=False)
|
||||
assert report["errors"] == []
|
||||
created = nb.dcim.devices.created[-1]
|
||||
assert created["name"] == "Büro ohne Standort" and created["site"] == 21 and created["tenant"] == 7
|
||||
assert created["serial"] == "P52000000000003" and created["description"] == "Firmware v1.10.3192"
|
||||
renamed = nb.dcim.devices.get(101)
|
||||
assert renamed.name == "Kita Sonne OG" and renamed.description == "Firmware v2.3.6"
|
||||
assert nb.dcim.devices.get(102).serial == "P52000000000001"
|
||||
assert [payload["tenant"] for payload in nb.ipam.ip_addresses.created] == [8, 8]
|
||||
# The duplicate IP of the third AP is not taken away from the second one.
|
||||
assert any("bereits einem anderen Objekt zugeordnet" in change for change in dict(report["items"])[
|
||||
"Büro ohne Standort"])
|
||||
|
||||
|
||||
def test_new_ap_without_site_is_an_error_not_a_guess():
|
||||
nb = _netbox()
|
||||
engine = APSyncEngine(nb)
|
||||
engine.load_context(7)
|
||||
aps = parse_csv(CSV)
|
||||
engine.match(aps)
|
||||
report = engine.sync(aps, {}, role_id=30, dry_run=True)
|
||||
assert report["errors"][0].startswith("Büro ohne Standort: kein Standort")
|
||||
|
||||
|
||||
def test_site_is_optional_with_default_site_and_tenant_can_be_chosen():
|
||||
nb = _netbox()
|
||||
engine = APSyncEngine(nb)
|
||||
engine.load_context(7)
|
||||
assert [tenant["name"] for tenant in engine.group_tenants] == ["Kunde Kita", "Kunde RZ"]
|
||||
aps = parse_csv(CSV)
|
||||
engine.match(aps)
|
||||
# No site for the new AP: it goes to the default site, with an own tenant.
|
||||
engine.sync(aps, {ap_key(aps[2]): {"site": None, "tenant": 8}}, role_id=30, dry_run=False, default_site=21)
|
||||
created = nb.dcim.devices.created[-1]
|
||||
assert (created["site"], created["tenant"]) == (21, 8)
|
||||
@@ -181,3 +181,44 @@ def test_profile_keeps_client_options(tmp_path, monkeypatch):
|
||||
assert "password" not in loaded["Kunde"]["clients"]
|
||||
assert settings["parallel_wmi"] == 8
|
||||
|
||||
|
||||
|
||||
INSTANCE = """<p:Win32_NetworkAdapterConfiguration xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_NetworkAdapterConfiguration" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cim="http://schemas.dmtf.org/wbem/wscim/1/common">
|
||||
<p:Description>Intel(R) Ethernet</p:Description><p:DHCPEnabled>true</p:DHCPEnabled>
|
||||
<p:IPAddress>192.168.65.43</p:IPAddress><p:IPAddress>fe80::1</p:IPAddress>
|
||||
<p:DefaultIPGateway xsi:nil="true"/>
|
||||
<p:InstallDate><cim:Datetime>2025-12-23T17:23:16Z</cim:Datetime></p:InstallDate>
|
||||
</p:Win32_NetworkAdapterConfiguration>"""
|
||||
|
||||
|
||||
def test_parse_wsman_instance():
|
||||
from netbox_sync.core import wsman
|
||||
|
||||
item = wsman.parse_instance(INSTANCE)
|
||||
assert item["Description"] == "Intel(R) Ethernet" and wsman.as_bool(item["DHCPEnabled"])
|
||||
assert item["IPAddress"] == ["192.168.65.43", "fe80::1"]
|
||||
assert item["DefaultIPGateway"] is None and wsman.as_list(item["DefaultIPGateway"]) == []
|
||||
assert item["InstallDate"] == "2025-12-23T17:23:16Z"
|
||||
|
||||
|
||||
def test_ad_location_defaults_to_own_domain(monkeypatch):
|
||||
from netbox_sync.core import clients
|
||||
|
||||
monkeypatch.setenv("USERDNSDOMAIN", "FIRMA.LOCAL")
|
||||
assert clients.ad_location({}) == "DC=FIRMA,DC=LOCAL"
|
||||
assert clients.ad_location({"ad_server": "dc01.firma.local"}) == "dc01.firma.local"
|
||||
assert clients.ad_location({"ad_server": "dc01", "ad_base": "OU=PCs,DC=firma,DC=local"}) == \
|
||||
"dc01/OU=PCs,DC=firma,DC=local"
|
||||
|
||||
|
||||
def test_scan_runs_in_process(monkeypatch):
|
||||
from netbox_sync.core import clients
|
||||
|
||||
monkeypatch.setattr(clients, "resolves", lambda host: host != "unknown")
|
||||
monkeypatch.setattr(clients, "port_open", lambda host, port: host != "off")
|
||||
rows = [new_row(host) for host in ("pc01.firma.local", "off", "unknown")]
|
||||
seen = []
|
||||
results = clients.scan_clients(rows, query=lambda host: dict(RAW, host=host), on_result=seen.append)
|
||||
status = {row["host"]: row["status"] for row in results}
|
||||
assert status == {"pc01.firma.local": "ok", "off": "offline", "unknown": "offline"}
|
||||
assert len(seen) == 3
|
||||
@@ -0,0 +1,87 @@
|
||||
import ipaddress
|
||||
import struct
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fake_netbox import FakeNetBox, Record
|
||||
|
||||
from netbox_sync.core import netscan
|
||||
|
||||
|
||||
def test_ports_and_ranges_are_parsed():
|
||||
assert netscan.parse_ports("21-23, 80;443 80") == [21, 22, 23, 80, 443]
|
||||
with pytest.raises(netscan.ScanError):
|
||||
netscan.parse_ports("70000")
|
||||
assert netscan.expand_ips("192.0.2.1-3, 192.0.2.2") == ["192.0.2.1", "192.0.2.2", "192.0.2.3"]
|
||||
assert len(netscan.expand_ips("192.0.2.0/24")) == 254
|
||||
with pytest.raises(netscan.ScanError):
|
||||
netscan.expand_ips("10.0.0.0/16")
|
||||
|
||||
|
||||
def _nbstat_answer(names, mac):
|
||||
header = b"\x13\x37\x84\x00\x00\x00\x00\x01\x00\x00\x00\x00"
|
||||
question = b"\x20" + b"CK" + b"A" * 30 + b"\x00" + b"\x00\x21\x00\x01"
|
||||
entries = b"".join(name.ljust(15).encode() + bytes([suffix]) + struct.pack(">H", flags)
|
||||
for name, suffix, flags in names)
|
||||
body = bytes([len(names)]) + entries + mac
|
||||
return header + question + b"\x00\x00\x00\x00" + struct.pack(">H", len(body)) + body
|
||||
|
||||
|
||||
def test_netbios_answer_gives_name_workgroup_and_mac():
|
||||
data = _nbstat_answer([("PC-042", 0x00, 0x0400), ("KDS", 0x00, 0x8400), ("PC-042", 0x20, 0x0400)],
|
||||
bytes.fromhex("001122aabbcc"))
|
||||
assert netscan.parse_nbstat(data) == ("PC-042", "KDS", "00:11:22:AA:BB:CC")
|
||||
assert netscan.parse_nbstat(b"\x00" * 10) == ("", "", None)
|
||||
|
||||
|
||||
def test_netbox_entries_are_found_per_block_and_compared():
|
||||
nb = FakeNetBox()
|
||||
nb.ipam.ip_addresses.records += [
|
||||
Record(nb.ipam.ip_addresses, id=1, address="192.0.2.10/24", dns_name="srv01.example.local",
|
||||
vrf=None, tenant=SimpleNamespace(id=7, name="Muster"), status=SimpleNamespace(label="Aktiv"),
|
||||
description="", assigned_object=SimpleNamespace(virtual_machine=SimpleNamespace(name="SRV01"))),
|
||||
Record(nb.ipam.ip_addresses, id=2, address="192.0.2.20/24", dns_name="", vrf=None, tenant=None,
|
||||
status=SimpleNamespace(label="Aktiv"), description="",
|
||||
assigned_object=SimpleNamespace(device=SimpleNamespace(name="drucker-3og"))),
|
||||
Record(nb.ipam.ip_addresses, id=3, address="198.51.100.1/24", dns_name="", vrf=None, tenant=None,
|
||||
status=None, description="", assigned_object=None),
|
||||
]
|
||||
queried = []
|
||||
|
||||
def by_parent(parent):
|
||||
queried.append(parent)
|
||||
network = ipaddress.ip_network(parent)
|
||||
return [record for record in nb.ipam.ip_addresses.records
|
||||
if ipaddress.ip_interface(record.address).ip in network]
|
||||
nb.ipam.ip_addresses.filter = by_parent
|
||||
|
||||
found = netscan.netbox_lookup(nb, ["192.0.2.10", "192.0.2.20", "192.0.2.30"])
|
||||
assert queried == ["192.0.2.0/24"], "one request per /24"
|
||||
assert found["192.0.2.10"][0]["object"] == "SRV01" and found["192.0.2.10"][0]["object_kind"] == "VM"
|
||||
assert found["192.0.2.20"][0]["object"] == "drucker-3og"
|
||||
assert "192.0.2.30" not in found
|
||||
|
||||
alive = {"alive": True, "dns_name": "SRV01.example.local", "netbios_name": "SRV01"}
|
||||
assert netscan.compare(alive, found["192.0.2.10"]) == "match"
|
||||
assert netscan.compare(dict(alive, dns_name="pc99", netbios_name=""), found["192.0.2.20"]) == "differs"
|
||||
assert netscan.compare(alive, []) == "missing"
|
||||
assert netscan.compare({"alive": False}, found["192.0.2.20"]) == "offline"
|
||||
assert netscan.compare({"alive": False}, []) == "unknown"
|
||||
|
||||
|
||||
def test_unreachable_host_is_reported_without_details(monkeypatch):
|
||||
monkeypatch.setattr(netscan, "ping", lambda *_args: None)
|
||||
monkeypatch.setattr(netscan, "arp_mac", lambda _ip: None)
|
||||
monkeypatch.setattr(netscan, "tcp_open", lambda *_args: False)
|
||||
assert netscan.scan_host("192.0.2.1", [80]) == {"ip": "192.0.2.1", "alive": False}
|
||||
|
||||
|
||||
def test_host_behind_firewall_is_found_by_port(monkeypatch):
|
||||
monkeypatch.setattr(netscan, "ping", lambda *_args: None)
|
||||
monkeypatch.setattr(netscan, "arp_mac", lambda _ip: None)
|
||||
monkeypatch.setattr(netscan, "tcp_open", lambda _ip, port, _timeout=0: port in (445, 3389))
|
||||
monkeypatch.setattr(netscan, "netbios", lambda _ip: ("PC-1", "KDS", "00:11:22:33:44:55"))
|
||||
monkeypatch.setattr(netscan, "reverse_dns", lambda _ip: "pc-1.kds.local")
|
||||
host = netscan.scan_host("192.0.2.5", [80, 445, 3389])
|
||||
assert host["alive"] and [item["port"] for item in host["ports"]] == [445, 3389]
|
||||
assert host["mac"] == "00:11:22:33:44:55" and host["netbios_name"] == "PC-1"
|
||||
+313
-1
@@ -2,7 +2,14 @@ from types import SimpleNamespace
|
||||
|
||||
from fake_netbox import FakeNetBox, Record
|
||||
|
||||
from netbox_sync.core.switches import build_snapshot, sync_snapshot_to_netbox
|
||||
from netbox_sync.core.switches import (
|
||||
build_snapshot,
|
||||
match_interfaces,
|
||||
parse_stack,
|
||||
plan_switch_sync,
|
||||
stack_member,
|
||||
sync_snapshot_to_netbox,
|
||||
)
|
||||
from test_switches import COMWARE_BRIEF, COMWARE_LLDP
|
||||
|
||||
|
||||
@@ -63,3 +70,308 @@ def test_offline_switch_is_resolved_by_name():
|
||||
|
||||
missing = sync_snapshot_to_netbox(nb, {"id": "s", "name": "unbekannt"}, snapshot, dry_run=True)
|
||||
assert missing["errors"] == ["NetBox-Gerät „unbekannt“ nicht gefunden"]
|
||||
|
||||
|
||||
def _numbered_setup():
|
||||
"""NetBox device type with ports "1" … "3", switch reports "1/1/x"."""
|
||||
nb = FakeNetBox()
|
||||
group = SimpleNamespace(id=3, name="Kunde")
|
||||
nb.tenancy.tenants.records.append(Record(nb.tenancy.tenants, id=7, name="Muster", group=group))
|
||||
nb.dcim.devices.records += [
|
||||
Record(nb.dcim.devices, id=1, name="access-01", tenant=SimpleNamespace(id=7), tenant_group=group),
|
||||
Record(nb.dcim.devices, id=2, name="server-01", tenant=SimpleNamespace(id=7), tenant_group=group),
|
||||
Record(nb.dcim.devices, id=3, name="fremd", tenant=None, tenant_group=None),
|
||||
]
|
||||
for index, name in enumerate(("1", "2", "3"), start=1):
|
||||
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=index, name=name, device=SimpleNamespace(id=1),
|
||||
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None,
|
||||
label=""))
|
||||
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=20, name="eth0", device=SimpleNamespace(id=2),
|
||||
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None))
|
||||
interfaces = [
|
||||
{"name": f"1/1/{number}", "enabled": True, "connected": True, "media": "1GbT", "speed_mbps": 1000,
|
||||
"ip_addresses": [], "vlans": {"untagged": [10 * number], "tagged": [], "tagged_all": False}}
|
||||
for number in (1, 2, 3)
|
||||
]
|
||||
neighbor = {"local_port": "1/1/2", "system_name": "unbekannt", "remote_port": "eth0", "port_description": "",
|
||||
"management_ip": "", "protocol": "LLDP"}
|
||||
snapshot = {"interfaces": interfaces, "neighbors": [neighbor]}
|
||||
return nb, {"id": "s", "name": "access-01", "device_id": 1}, snapshot
|
||||
|
||||
|
||||
def test_ports_are_mapped_by_number_and_labelled_with_vlans():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert report["errors"] == [] and report["interfaces_created"] == 0
|
||||
assert sorted(nb.dcim.interfaces.updates) == [(1, {"label": "10"}), (2, {"label": "20"}), (3, {"label": "30"})]
|
||||
|
||||
|
||||
def test_ports_are_mapped_by_order_and_manual_choice_wins():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
for item, name in zip(snapshot["interfaces"], ("1/0/1", "1/0/2", "2/0/1")):
|
||||
item["name"] = name # "2/0/1" breaks the unique port numbers
|
||||
matches = match_interfaces(snapshot["interfaces"], nb.dcim.interfaces.filter(device_id=1))
|
||||
assert {name: (record.name, method) for name, (record, method) in matches.items()} == {
|
||||
"1/0/1": ("1", "order"), "1/0/2": ("2", "number"), "2/0/1": ("3", "order")}
|
||||
manual = match_interfaces(snapshot["interfaces"], nb.dcim.interfaces.filter(device_id=1), {"2/0/1": ""})
|
||||
assert manual["2/0/1"] == (None, "new")
|
||||
|
||||
|
||||
def test_plan_offers_tenant_group_devices_and_manual_neighbor_creates_cable():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
plan = plan_switch_sync(nb, switch, snapshot)
|
||||
assert plan["device_scope"] == "Mandantengruppe Kunde"
|
||||
assert [device["name"] for device in plan["devices"]] == ["server-01"]
|
||||
assert plan["neighbors"][0]["device_id"] is None
|
||||
assert {item["name"]: item["method"] for item in plan["interfaces"]}["1/1/1"] == "number"
|
||||
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True)
|
||||
assert report["cables_created"] == 0
|
||||
switch["neighbor_devices"] = {"1/1/2": 2}
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot)
|
||||
cable = nb.dcim.cables.created[0]
|
||||
assert cable["a_terminations"][0]["object_id"] == 2 and cable["b_terminations"][0]["object_id"] == 20
|
||||
|
||||
|
||||
def test_missing_vlans_prefixes_and_vrfs_are_only_created_when_approved():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
nb.ipam.vlans.records.append(Record(nb.ipam.vlans, id=110, vid=10, name="Server", tenant=SimpleNamespace(id=7)))
|
||||
snapshot["interfaces"][2]["vlans"] = {"untagged": [1], "tagged": [10, 20], "tagged_all": False}
|
||||
snapshot["interfaces"][0]["ip_addresses"] = ["10.1.0.1/24"]
|
||||
snapshot["vlan_names"] = {20: "Clients"}
|
||||
|
||||
plan = plan_switch_sync(nb, switch, snapshot)
|
||||
assert [(item["vid"], item["netbox_id"], item["method"], item["new_name"]) for item in plan["vlans"]] == [
|
||||
(1, None, "new", "VLAN1"), (10, 110, "vid", "VLAN10"), (20, None, "new", "Clients")]
|
||||
assert plan["networks"] == [{"network": "10.1.0.0/24", "vrf_id": 0, "vrf_name": "", "existing": [],
|
||||
"create": True, "stored": False}]
|
||||
|
||||
# Not approved: nothing is created, only the existing VLAN 10 is assigned.
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||
assert (report["vlans_created"], report["prefixes_created"], report["vrfs_created"]) == (0, 0, 0)
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert nb.ipam.vlans.created == [] and nb.ipam.prefixes.created == []
|
||||
assert nb.dcim.interfaces.get(1).untagged_vlan == 110 and nb.dcim.interfaces.get(1).mode == "access"
|
||||
assert nb.ipam.ip_addresses.created[0]["tenant"] == 7 and nb.ipam.ip_addresses.created[0]["vrf"] is None
|
||||
|
||||
switch.update({"vlan_map": {"20": {"action": "new", "name": "Clients"}}, "network_map": {"10.1.0.0/24": {"vrf_id": None, "vrf_name": "Kunde-Mgmt", "create": True}}})
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert report["errors"] == []
|
||||
assert nb.ipam.vrfs.created == [{"name": "Kunde-Mgmt", "tenant": 7}]
|
||||
vrf_id = nb.ipam.vrfs.records[0].id
|
||||
assert nb.ipam.prefixes.created == [{"prefix": "10.1.0.0/24", "status": "active", "tenant": 7, "vrf": vrf_id}]
|
||||
assert nb.ipam.vlans.created == [{"vid": 20, "name": "Clients", "status": "active", "tenant": 7}]
|
||||
port = nb.dcim.interfaces.get(3)
|
||||
assert port.mode == "tagged" and sorted(port.tagged_vlans) == sorted([110, nb.ipam.vlans.records[1].id])
|
||||
|
||||
|
||||
def test_switch_without_tenant_is_refused():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
nb.dcim.devices.get(1).tenant = None
|
||||
assert "keinen Mandanten" in plan_switch_sync(nb, switch, snapshot)["error"]
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot)
|
||||
assert "keinen Mandanten" in report["errors"][0] and nb.dcim.interfaces.updates == []
|
||||
|
||||
|
||||
def test_vlan_names_are_parsed():
|
||||
from netbox_sync.core.switches import parse_vlan_names
|
||||
assert parse_vlan_names('vlan 10\n name "Server"\n exit\nvlan 20\n name Clients\n#\n') == {
|
||||
10: "Server", 20: "Clients"}
|
||||
|
||||
|
||||
def test_vlans_of_sibling_tenants_are_matched_by_vid_and_name():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
group = SimpleNamespace(id=3, name="Kunde")
|
||||
leo = SimpleNamespace(id=8, name="Leo")
|
||||
nb.ipam.vlans.records += [
|
||||
Record(nb.ipam.vlans, id=201, vid=2, name="Leo Server", tenant=leo, tenant_group=group),
|
||||
Record(nb.ipam.vlans, id=202, vid=2, name="Gast", tenant=SimpleNamespace(id=9), tenant_group=group),
|
||||
Record(nb.ipam.vlans, id=230, vid=30, name="Fremd", tenant=SimpleNamespace(id=99), tenant_group=None),
|
||||
]
|
||||
snapshot["interfaces"][0]["vlans"] = {"untagged": [2], "tagged": [], "tagged_all": False}
|
||||
snapshot["vlan_names"] = {2: "Server_LEO", 30: "Drucker"}
|
||||
plan = plan_switch_sync(nb, switch, snapshot)
|
||||
by_vid = {item["vid"]: item for item in plan["vlans"]}
|
||||
assert (by_vid[2]["netbox_id"], by_vid[2]["method"]) == (201, "name")
|
||||
assert [candidate["id"] for candidate in by_vid[2]["candidates"]] == [202, 201]
|
||||
assert by_vid[30]["method"] == "new", "VLANs outside the tenant group are never used"
|
||||
|
||||
switch["vlan_map"] = {"30": {"action": "new", "name": "Drucker-Netz"}, "20": {"action": "skip"}}
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert report["errors"] == []
|
||||
assert nb.ipam.vlans.created == [{"vid": 30, "name": "Drucker-Netz", "status": "active", "tenant": 7}]
|
||||
assert nb.dcim.interfaces.get(1).untagged_vlan == 201
|
||||
assert getattr(nb.dcim.interfaces.get(2), "mode", None) is None, "skipped VLAN leaves the port alone"
|
||||
|
||||
|
||||
def test_new_vlan_can_get_another_tenant_of_the_group():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
group = SimpleNamespace(id=3, name="Kunde")
|
||||
nb.tenancy.tenants.records.append(Record(nb.tenancy.tenants, id=8, name="Leo", group=group))
|
||||
nb.tenancy.tenants.records.append(Record(nb.tenancy.tenants, id=9, name="Fremd", group=None))
|
||||
plan = plan_switch_sync(nb, switch, snapshot)
|
||||
assert [row["name"] for row in plan["tenants"]] == ["Leo", "Muster"]
|
||||
assert {item["new_tenant"] for item in plan["vlans"]} == {7}
|
||||
|
||||
switch["vlan_map"] = {"10": {"action": "new", "name": "Leo Server", "tenant": 8}}
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert nb.ipam.vlans.created == [{"vid": 10, "name": "Leo Server", "status": "active", "tenant": 8}]
|
||||
# NetBox resolves the tenant group through the tenant; the fake needs it set.
|
||||
nb.ipam.vlans.records[-1].tenant_group = group
|
||||
again = plan_switch_sync(nb, switch, snapshot)["vlans"][0]
|
||||
assert (again["netbox_id"], again["method"]) == (nb.ipam.vlans.records[-1].id, "manual"), "never created twice"
|
||||
|
||||
|
||||
def test_ignored_vlans_are_left_out_everywhere():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
nb.ipam.vlans.records.append(Record(nb.ipam.vlans, id=110, vid=10, name="Server", tenant=SimpleNamespace(id=7)))
|
||||
snapshot["interfaces"][0]["vlans"] = {"untagged": [10], "tagged": [20, 30], "tagged_all": False}
|
||||
switch["vlan_map"] = {"20": {"action": "ignore"}, "30": {"action": "new", "name": "Drucker"}}
|
||||
plan = plan_switch_sync(nb, switch, snapshot)
|
||||
by_vid = {item["vid"]: item for item in plan["vlans"]}
|
||||
assert (by_vid[20]["method"], by_vid[20]["stored"]) == ("ignore", True)
|
||||
assert by_vid[10]["stored"] is False
|
||||
assert {item["name"]: item["vlan_label"] for item in plan["interfaces"]}["1/1/1"] == "10,30"
|
||||
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert report["errors"] == []
|
||||
assert [payload["vid"] for payload in nb.ipam.vlans.created] == [30]
|
||||
port = nb.dcim.interfaces.get(1)
|
||||
assert port.label == "10,30" and port.tagged_vlans == [nb.ipam.vlans.records[-1].id]
|
||||
|
||||
|
||||
def test_vlan_decisions_move_from_switches_to_the_profile(tmp_path):
|
||||
from netbox_sync.core.config import ProfileStore
|
||||
store = ProfileStore(tmp_path / "config.json")
|
||||
profile = {"name": "Kunde", "switches": [{"id": "s", "name": "sw", "password": "x",
|
||||
"vlan_map": {"5": {"action": "ignore"}}, "create_vlans": [6]}]}
|
||||
store.save({"Kunde": profile}, "Kunde")
|
||||
loaded = store.load()[0]["Kunde"]
|
||||
assert loaded["vlan_map"] == {"5": {"action": "ignore"}}
|
||||
assert "vlan_map" not in loaded["switches"][0] and "create_vlans" not in loaded["switches"][0]
|
||||
|
||||
|
||||
def test_vrfs_of_the_tenant_group_are_offered_and_found():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
group = SimpleNamespace(id=3, name="Kunde")
|
||||
rz = SimpleNamespace(id=8, name="RZ")
|
||||
nb.ipam.vrfs.records += [
|
||||
Record(nb.ipam.vrfs, id=60, name="Mgmt", tenant=rz, tenant_group=group),
|
||||
Record(nb.ipam.vrfs, id=61, name="Fremd", tenant=SimpleNamespace(id=99), tenant_group=None),
|
||||
]
|
||||
nb.ipam.prefixes.records.append(Record(nb.ipam.prefixes, id=70, prefix="10.10.167.0/24", vrf=SimpleNamespace(id=60)))
|
||||
snapshot["interfaces"][0]["ip_addresses"] = ["10.10.167.5/24"]
|
||||
|
||||
plan = plan_switch_sync(nb, switch, snapshot)
|
||||
assert plan["vrfs"] == [{"id": 60, "label": "Mgmt (RZ)"}], "group VRFs only"
|
||||
assert plan["networks"][0] == {"network": "10.10.167.0/24", "vrf_id": 60, "vrf_name": "", "existing": [60],
|
||||
"create": True, "stored": False}
|
||||
|
||||
switch["network_map"] = {"10.10.167.0/24": {"vrf_id": 60, "vrf_name": "", "create": False}}
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert report["errors"] == [] and report["prefixes_created"] == 0 and nb.ipam.vrfs.created == []
|
||||
assert nb.ipam.ip_addresses.created[0]["vrf"] == 60
|
||||
assert plan_switch_sync(nb, switch, snapshot)["networks"][0]["stored"] is True
|
||||
|
||||
|
||||
def test_legacy_network_choices_still_work_and_migrate(tmp_path):
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
snapshot["interfaces"][0]["ip_addresses"] = ["10.1.0.1/24"]
|
||||
switch.update({"network_vrfs": {"10.1.0.0/24": ""}, "create_prefixes": ["10.1.0.0/24"]})
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||
assert report["prefixes_created"] == 1
|
||||
|
||||
from netbox_sync.core.config import ProfileStore
|
||||
store = ProfileStore(tmp_path / "config.json")
|
||||
store.save({"Kunde": {"name": "Kunde", "switches": [dict(switch, password="x")]}}, "Kunde")
|
||||
loaded = store.load()[0]["Kunde"]
|
||||
assert loaded["network_map"] == {"10.1.0.0/24": {"vrf_id": None, "vrf_name": "", "create": True}}
|
||||
assert "network_vrfs" not in loaded["switches"][0]
|
||||
|
||||
|
||||
CX_STACK_CONFIG = """
|
||||
hostname Switch36
|
||||
vsf member 1
|
||||
type jl661a
|
||||
link 1 1/1/49
|
||||
link 2 1/1/50
|
||||
vsf member 2
|
||||
type jl661a
|
||||
link 1 2/1/49
|
||||
link 2 2/1/51
|
||||
interface lag 1
|
||||
no shutdown
|
||||
no routing
|
||||
vlan trunk native 1
|
||||
vlan trunk allowed 10,200-204
|
||||
interface 1/1/1
|
||||
no routing
|
||||
vlan access 10
|
||||
interface 1/1/52
|
||||
lag 1
|
||||
interface 2/1/1
|
||||
no routing
|
||||
vlan access 10
|
||||
interface 2/1/52
|
||||
lag 1
|
||||
interface vlan 201
|
||||
ip address 172.16.201.2/24
|
||||
"""
|
||||
|
||||
|
||||
def _stack_snapshot():
|
||||
interfaces = [
|
||||
{"name": name, "enabled": True, "connected": True, "media": "1GbT", "speed_mbps": 1000, "ip_addresses": [],
|
||||
"vlans": {"untagged": [10], "tagged": [], "tagged_all": False}}
|
||||
for name in ("1/1/1", "1/1/2", "2/1/1", "2/1/2")
|
||||
] + [{"name": "lag1", "enabled": True, "connected": True, "ip_addresses": [], "vlans": None}]
|
||||
return {"platform": "aruba_cx", "interfaces": interfaces, "neighbors": [],
|
||||
"stack": parse_stack(CX_STACK_CONFIG, "aruba_cx", interfaces)}
|
||||
|
||||
|
||||
def test_aruba_cx_vsf_stack_is_detected():
|
||||
stack = parse_stack(CX_STACK_CONFIG, "aruba_cx")
|
||||
assert stack == [{"member": 1, "model": "jl661a", "mac": ""}, {"member": 2, "model": "jl661a", "mac": ""}]
|
||||
assert stack_member("2/1/5", "aruba_cx") == 2 and stack_member("lag1", "aruba_cx") is None
|
||||
assert stack_member("GigabitEthernet2/0/5", "hpe_comware") == 2 and stack_member("2/A3", "aruba_aos") == 2
|
||||
assert parse_stack("vsf member 1\n type jl661a\n", "aruba_cx") == [], "one member is no stack"
|
||||
aos = 'stacking\n member 1 type "JL256A" mac-address 9020c2-000001\n member 2 type "JL256A"\n exit\n'
|
||||
assert [(item["member"], item["model"]) for item in parse_stack(aos, "aruba_aos")] == [(1, "JL256A"), (2, "JL256A")]
|
||||
|
||||
|
||||
def test_stack_members_go_to_their_own_netbox_devices():
|
||||
nb, switch, _snapshot = _numbered_setup()
|
||||
snapshot = _stack_snapshot()
|
||||
# Member 2 is its own NetBox device whose device type named the ports "1/1/x".
|
||||
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=4, name="access-01-2", tenant=SimpleNamespace(id=7)))
|
||||
for index, name in enumerate(("1/1/1", "1/1/2"), start=60):
|
||||
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=index, name=name, device=SimpleNamespace(id=4),
|
||||
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None,
|
||||
label=""))
|
||||
|
||||
plan = plan_switch_sync(nb, switch, snapshot)
|
||||
assert [(entry["member"], entry["device_id"], entry["ports"]) for entry in plan["stack"]] == [(1, 1, 2), (2, None, 2)]
|
||||
assert plan["skipped_ports"] == 2
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||
assert report["notes"] == ["Stack-Mitglied 2: kein NetBox-Gerät gewählt – 2 Ports übersprungen"]
|
||||
|
||||
switch["stack_devices"] = {"1": 1, "2": 4}
|
||||
plan = plan_switch_sync(nb, switch, snapshot)
|
||||
by_name = {item["name"]: item for item in plan["interfaces"]}
|
||||
assert by_name["2/1/1"]["owner_id"] == 4 and by_name["2/1/1"]["netbox_name"] == "1/1/1"
|
||||
assert by_name["1/1/1"]["owner_id"] == 1 and by_name["1/1/1"]["netbox_name"] == "1"
|
||||
assert plan["owner_interfaces"]["4"] == ["1/1/1", "1/1/2"]
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert nb.dcim.interfaces.get(60).label == "10" and nb.dcim.interfaces.get(1).label == "10"
|
||||
assert [(payload["device"], payload["name"]) for payload in nb.dcim.interfaces.created] == [(1, "lag1")]
|
||||
|
||||
|
||||
def test_virtual_chassis_positions_are_suggested():
|
||||
nb, switch, _snapshot = _numbered_setup()
|
||||
snapshot = _stack_snapshot()
|
||||
nb.dcim.devices.get(1).virtual_chassis = SimpleNamespace(id=9)
|
||||
nb.dcim.devices.get(1).vc_position = 1
|
||||
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=4, name="access-01-2", tenant=SimpleNamespace(id=7),
|
||||
virtual_chassis=SimpleNamespace(id=9), vc_position=2))
|
||||
plan = plan_switch_sync(nb, switch, snapshot)
|
||||
assert [entry["device_id"] for entry in plan["stack"]] == [1, 4]
|
||||
@@ -201,3 +201,103 @@ def test_speed_parsing():
|
||||
assert switches.speed_mbps("1000FDx") == 1000
|
||||
assert switches.speed_mbps("10GigFD") == 10000
|
||||
assert switches.speed_mbps("UP 1G(a) F(a)") == 1000
|
||||
|
||||
|
||||
AOS_CONFIG = """
|
||||
vlan 1
|
||||
name "DEFAULT_VLAN"
|
||||
untagged 1,3-4,Trk1
|
||||
no untagged 2
|
||||
exit
|
||||
vlan 10
|
||||
name "Server"
|
||||
untagged 2
|
||||
tagged 49,Trk1
|
||||
exit
|
||||
vlan 20
|
||||
tagged 1/1-1/2,49
|
||||
exit
|
||||
"""
|
||||
|
||||
CX_CONFIG = """
|
||||
interface 1/1/1
|
||||
no shutdown
|
||||
no routing
|
||||
vlan access 10
|
||||
interface 1/1/2
|
||||
no routing
|
||||
vlan trunk native 1
|
||||
vlan trunk allowed 1,20-22
|
||||
interface 1/1/3
|
||||
no routing
|
||||
interface 1/1/49
|
||||
ip address 10.0.0.1/24
|
||||
interface lag 1
|
||||
no routing
|
||||
vlan trunk native 5 tag
|
||||
vlan trunk allowed all
|
||||
"""
|
||||
|
||||
COMWARE_CONFIG = """
|
||||
#
|
||||
interface GigabitEthernet1/0/1
|
||||
port link-mode bridge
|
||||
port access vlan 10
|
||||
#
|
||||
interface GigabitEthernet1/0/2
|
||||
port link-mode bridge
|
||||
#
|
||||
interface GigabitEthernet1/0/3
|
||||
port link-type hybrid
|
||||
port hybrid vlan 30 40 tagged
|
||||
port hybrid vlan 1 untagged
|
||||
#
|
||||
interface Ten-GigabitEthernet1/0/49
|
||||
port link-mode bridge
|
||||
port link-type trunk
|
||||
undo port trunk permit vlan 1
|
||||
port trunk permit vlan 10 20 to 22
|
||||
port trunk pvid vlan 10
|
||||
#
|
||||
interface Vlan-interface10
|
||||
ip address 10.0.0.1 255.255.255.0
|
||||
#
|
||||
"""
|
||||
|
||||
|
||||
def test_parse_vlans_aruba_aos():
|
||||
vlans = switches.parse_vlans(AOS_CONFIG, "aruba_aos")
|
||||
assert vlans[interface_key("1")] == {"untagged": [1], "tagged": [], "tagged_all": False}
|
||||
assert vlans[interface_key("2")]["untagged"] == [10]
|
||||
assert vlans[interface_key("49")] == {"untagged": [], "tagged": [10, 20], "tagged_all": False}
|
||||
assert vlans[interface_key("Trk1")] == {"untagged": [1], "tagged": [10], "tagged_all": False}
|
||||
assert vlans[interface_key("1/2")]["tagged"] == [20]
|
||||
|
||||
|
||||
def test_parse_vlans_aruba_cx():
|
||||
vlans = switches.parse_vlans(CX_CONFIG, "aruba_cx")
|
||||
assert switches.vlan_label(vlans[interface_key("1/1/1")]) == "10"
|
||||
assert switches.vlan_label(vlans[interface_key("1/1/2")]) == "1,20-22"
|
||||
assert switches.vlan_label(vlans[interface_key("1/1/3")]) == "1"
|
||||
assert interface_key("1/1/49") not in vlans
|
||||
assert switches.vlan_label(vlans[interface_key("lag1")]) == "all"
|
||||
|
||||
|
||||
def test_parse_vlans_comware():
|
||||
vlans = switches.parse_vlans(COMWARE_CONFIG, "hpe_comware")
|
||||
assert switches.vlan_label(vlans[interface_key("GE1/0/1")]) == "10"
|
||||
assert switches.vlan_label(vlans[interface_key("GE1/0/2")]) == "1"
|
||||
assert vlans[interface_key("GE1/0/3")] == {"untagged": [1], "tagged": [30, 40], "tagged_all": False}
|
||||
assert vlans[interface_key("XGE1/0/49")] == {"untagged": [10], "tagged": [20, 21, 22], "tagged_all": False}
|
||||
assert interface_key("Vlan-interface10") not in vlans
|
||||
|
||||
|
||||
def test_vlan_label_is_short_and_snapshot_hides_config():
|
||||
many = {"untagged": [], "tagged": list(range(100, 400, 2)), "tagged_all": False}
|
||||
assert len(switches.vlan_label(many)) <= 64 and switches.vlan_label(many).endswith("…")
|
||||
snapshot = build_snapshot({"interfaces": COMWARE_BRIEF, "neighbors": "",
|
||||
"config": COMWARE_CONFIG + "\n local-user admin\n password hash $h$secret\n"},
|
||||
"hpe_comware")
|
||||
by_name = {item["name"]: item for item in snapshot["interfaces"]}
|
||||
assert by_name["GigabitEthernet1/0/1"]["vlans"]["untagged"] == [10]
|
||||
assert "config" not in snapshot["raw"] and "secret" not in snapshot["raw"]["vlan_config"]
|
||||
@@ -0,0 +1,75 @@
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from netbox_sync.core import updater
|
||||
|
||||
RELEASE = {
|
||||
"tag_name": "v4.7.0", "name": "Netbox-Import-Desktop v4.7.0", "body": "- neu", "draft": False,
|
||||
"prerelease": False, "html_url": "https://example.invalid/releases/tag/v4.7.0",
|
||||
"assets": [
|
||||
{"name": "NetBox VM Import.exe", "size": 4, "browser_download_url": "https://example.invalid/portable"},
|
||||
{"name": "NetBoxSynchronizer-Setup-4.7.0.exe", "size": 4, "browser_download_url": "https://example.invalid/setup"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
class _Response:
|
||||
def __init__(self, payload=None, chunks=(), length=None):
|
||||
self.payload, self.chunks = payload, chunks
|
||||
self.headers = {"Content-Length": str(length)} if length else {}
|
||||
|
||||
def raise_for_status(self):
|
||||
return None
|
||||
|
||||
def json(self):
|
||||
return self.payload
|
||||
|
||||
def iter_content(self, _size):
|
||||
return iter(self.chunks)
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *_args):
|
||||
return False
|
||||
|
||||
|
||||
def test_versions_are_compared_numerically():
|
||||
assert updater.parse_version("v4.10.0") > updater.parse_version("4.9.3")
|
||||
assert updater.parse_version("v5") == (5, 0, 0)
|
||||
|
||||
|
||||
def test_newer_release_is_offered_with_matching_assets(monkeypatch):
|
||||
monkeypatch.setattr(updater.requests, "get", lambda *_a, **_k: _Response(RELEASE))
|
||||
release = updater.check_for_update("4.6.0")
|
||||
assert release["version"] == "4.7.0" and release["notes"] == "- neu"
|
||||
assert updater.pick_asset(release, "portable")[0] == "NetBox VM Import.exe"
|
||||
assert updater.pick_asset(release, "installer")[0] == "NetBoxSynchronizer-Setup-4.7.0.exe"
|
||||
assert updater.check_for_update("4.7.0") is None
|
||||
monkeypatch.setattr(updater.requests, "get", lambda *_a, **_k: _Response(dict(RELEASE, prerelease=True)))
|
||||
assert updater.check_for_update("4.6.0") is None
|
||||
|
||||
|
||||
def test_incomplete_download_is_discarded(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(updater.requests, "get", lambda *_a, **_k: _Response(chunks=[b"ab"]))
|
||||
with pytest.raises(updater.UpdateError):
|
||||
updater.download({"url": "x", "size": 4}, tmp_path / "setup.exe")
|
||||
assert list(tmp_path.iterdir()) == []
|
||||
monkeypatch.setattr(updater.requests, "get", lambda *_a, **_k: _Response(chunks=[b"ab", b"cd"]))
|
||||
target = updater.download({"url": "x", "size": 4}, tmp_path / "setup.exe")
|
||||
assert target.read_bytes() == b"abcd"
|
||||
|
||||
|
||||
def test_portable_exe_is_swapped_and_restarted(monkeypatch, tmp_path):
|
||||
exe = tmp_path / "NetBox VM Import.exe"
|
||||
exe.write_bytes(b"old")
|
||||
new = tmp_path / "NetBox VM Import.new.exe"
|
||||
new.write_bytes(b"new")
|
||||
started = []
|
||||
monkeypatch.setattr(sys, "executable", str(exe))
|
||||
monkeypatch.setattr(updater.subprocess, "Popen", lambda args, **_kwargs: started.append(args))
|
||||
updater.apply_portable(new)
|
||||
assert exe.read_bytes() == b"new" and not new.exists()
|
||||
assert (tmp_path / "NetBox VM Import.old.exe").read_bytes() == b"old"
|
||||
assert started == [[str(exe)]]
|
||||
Reference in new issue
Block a user