Compare commits

...
4 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 28c6654f6b docs: translate README to English and align structure
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 20:58:21 +01:00
MrBlakeandClaude Opus 5.5 799a5aa007 chore: release 4.1.1
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 13:46:45 +02:00
MrBlakeandClaude Opus 5.5 d10190b7bc fix: query clients in-process via WSMan/ADSI COM instead of PowerShell
Endpoint protection (Sophos Application Lockdown) terminated the app when it spawned powershell.exe. WinRM and Active Directory are now accessed through Windows COM inside the process.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 13:41:52 +02:00
MrBlakeandClaude Opus 5.5 c42cedd655 build: add portable single-file EXE to the build
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 13:31:02 +02:00
11 changed files with 557 additions and 368 deletions

No files matched your search

+21 -15
View File
@@ -2,10 +2,16 @@
# Build: python -m PyInstaller --noconfirm --clean NetBoxSynchronizer.spec # Build: python -m PyInstaller --noconfirm --clean NetBoxSynchronizer.spec
# Produces a one-folder build in dist/NetBoxSynchronizer that the Inno Setup # Produces a one-folder build in dist/NetBoxSynchronizer that the Inno Setup
# installer (installer/NetBoxSynchronizer.iss) packages. # 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 re
import sys
from pathlib import Path from pathlib import Path
PORTABLE = "--portable" in sys.argv
from PyInstaller.utils.win32.versioninfo import ( from PyInstaller.utils.win32.versioninfo import (
FixedFileInfo, FixedFileInfo,
StringFileInfo, StringFileInfo,
@@ -66,12 +72,7 @@ a.datas = [
pyz = PYZ(a.pure) pyz = PYZ(a.pure)
exe = EXE( EXE_OPTIONS = dict(
pyz,
a.scripts,
[],
exclude_binaries=True,
name="NetBoxSynchronizer",
debug=False, debug=False,
bootloader_ignore_signals=False, bootloader_ignore_signals=False,
strip=False, strip=False,
@@ -86,12 +87,17 @@ exe = EXE(
version=version_info, version=version_info,
) )
coll = COLLECT( if PORTABLE:
exe, exe = EXE(pyz, a.scripts, a.binaries, a.datas, [], name="NetBox VM Import", upx_exclude=[],
a.binaries, runtime_tmpdir=None, **EXE_OPTIONS)
a.datas, else:
strip=False, exe = EXE(pyz, a.scripts, [], exclude_binaries=True, name="NetBoxSynchronizer", **EXE_OPTIONS)
upx=False, coll = COLLECT(
upx_exclude=[], exe,
name="NetBoxSynchronizer", a.binaries,
) a.datas,
strip=False,
upx=False,
upx_exclude=[],
name="NetBoxSynchronizer",
)
+119 -82
View File
@@ -1,108 +1,145 @@
# NetBox Synchronizer # NetBox Synchronizer
Windows-Desktopanwendung, die virtuelle Maschinen aus VMware vSphere und Proxmox VE, HPE-/Aruba-Switche Windows desktop application that documents virtual machines from VMware
sowie Windows-Clients in NetBox dokumentiert. vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
| | |
|---|---|
| **Type** | Desktop application (Python, PySide6) |
| **Platform** | Windows |
| **Repository** | <https://git.mrblake.cc/MrBlake/NetBox-VM-Import-Desktop> |
## Features
### General
- Customer profiles with NetBox target, virtualisation sources and switch
credentials; switch between them in the sidebar
- Automatic saving; passwords, tokens and secrets are encrypted with Windows DPAPI
- All network access runs in the background — the window stays responsive and
operations can be cancelled
- Light and dark theme (optionally following Windows)
- Log with filter, search and export, plus a rotating log file under
`%APPDATA%\NetBox VM Import\logs`
- Keyboard shortcuts: `Ctrl+1…8` navigation, `F5` reload/read, `Ctrl+F` search
### Virtual machines
- Multiple VMware and Proxmox sources per profile, read in parallel; connection
test directly in the dialog
- QEMU/KVM VMs and optionally LXC containers; IP addresses via VMware Tools or
the QEMU guest agent
- Table with search, filters (source, status, "new"/"already in NetBox") and
multi-selection
- Automatic cluster mapping: each vCenter/ESXi or Proxmox cluster is mapped to
the NetBox cluster with the same (or a uniquely similar) name; manual
mappings are remembered in the profile, and missing clusters can be created in
NetBox directly
- Four-step import wizard: **Target** (cluster mapping, tenant preselected from
the cluster, VRF or global) → **Networks** (check missing prefixes with size
and VRF, create new VRFs directly) → **Review** (summary of all changes) →
**Import** (progress, live log, cancel)
- VMs are matched uniquely per cluster; existing prefixes are reused
- MAC addresses are set correctly on NetBox ≥ 4.2 (separate MAC model)
### Switches (Aruba CX, ArubaOS-Switch/ProCurve, HPE Comware)
- Add several NetBox devices in one step — host taken from the primary IP,
platform suggested from model/manufacturer
- Platform "detect automatically" via SSH
- Parallel SSH queries; SSH host keys are stored on first contact and verified
afterwards
- Interfaces, interface IP addresses and LLDP/CDP neighbours
- **Preview before writing**: all changes are computed as a dry run and only
sent after confirmation
- Interface types from device type templates are left untouched; Comware short
names (`GE1/0/1`) are mapped to full NetBox names (`GigabitEthernet1/0/1`)
- Cables from LLDP/CDP, also with FQDN system names or via the management IP
- The switch configuration is only changed when "Enable LLDP if needed" is
explicitly switched on
### Windows clients (agentless via WMI/CIM over WinRM)
- Targets from Active Directory (optional search OU, enabled accounts only,
last logon within N days, include/exclude servers) or as a list of host
names, IP addresses, networks (`192.0.2.0/24`) and ranges (`192.0.2.10-50`)
- Sign-in via the Windows credential dialog (domain account with local admin
rights, verified against the domain) or with the current Windows session; the
password is kept in memory only
- Reads name, manufacturer, model (for Lenovo the model name instead of the
machine type), serial number, form factor, operating system with
version/build, logged-on user, CPU/RAM and physical network adapters with MAC
and IPs
- Parallel queries; unreachable clients stay visible with their AD data, errors
come with a concrete hint
- Import as NetBox devices with site, role and tenant; manufacturers, device
types and platforms are created when needed, optionally interfaces, MAC and IP
addresses — with a preview before writing
- Built-in **setup guide**: group policy (WinRM, service, firewall),
permissions, common errors, check commands and a connection test for single
clients
### Offline mode (without NetBox)
- "Offline mode (without NetBox)" checkbox in the sidebar — global, independent
of the customer profile
- VMs and switches are read without a NetBox connection; switches can then be
added manually by name
- Selected VMs, clients or read switches are exported as a JSON file
(`*.nbsync.json`) — without passwords, tokens or user names
- On a machine with NetBox access, "Load from file …" (VMs, switches and
Windows clients pages) loads the file; the import wizard or dry-run preview
then runs as usual. Switches are matched by NetBox device ID or name
### VRFs & networks
- Create several VRFs or prefixes for one tenant at once
## Installation ## 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 - installs for the current user **without administrator rights** by default
(im Assistenten kann „für alle Benutzer“ gewählt werden), ("for all users" can be selected in the wizard),
- legt einen Startmenü-Eintrag und optional eine Desktop-Verknüpfung an, - creates a Start menu entry and optionally a desktop shortcut,
- aktualisiert eine vorhandene Installation direkt, - updates an existing installation in place,
- fragt bei der Deinstallation, ob Kundenprofile und Protokolle ebenfalls gelöscht werden sollen. - 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 ## Development
**Allgemein**
- Kundenprofile mit NetBox-Ziel, Virtualisierungsquellen und Switch-Zugängen; Wechsel über die Seitenleiste
- Automatisches Speichern; Passwörter, Tokens und Secrets mit Windows DPAPI verschlüsselt
- Alle Netzwerkzugriffe laufen im Hintergrund – das Fenster bleibt bedienbar, Vorgänge lassen sich abbrechen
- Helles und dunkles Design (folgt auf Wunsch Windows)
- Protokoll mit Filter, Suche und Export; zusätzlich rotierende Logdatei unter `%APPDATA%\NetBox VM Import\logs`
- Tastenkürzel: `Strg+1…8` Navigation, `F5` neu laden/auslesen, `Strg+F` Suche
**Virtuelle Maschinen**
- Mehrere VMware- und Proxmox-Quellen pro Profil, parallel ausgelesen; Verbindungstest direkt im Dialog
- QEMU/KVM-VMs und optional LXC-Container; IP-Adressen über VMware Tools bzw. QEMU Guest Agent
- Tabelle mit Suche, Filtern (Quelle, Status, „neu“/„bereits in NetBox“) und Mehrfachauswahl
- Automatische Cluster-Zuordnung: Jeder vCenter-/ESXi- bzw. Proxmox-Cluster wird dem gleichnamigen (oder eindeutig
ähnlichen) NetBox-Cluster zugeordnet; manuelle Zuordnungen merkt sich das Kundenprofil, fehlende Cluster können
direkt in NetBox angelegt werden
- Import-Assistent in vier Schritten: **Ziel** (Cluster-Zuordnung, Mandant aus dem Cluster vorausgewählt, VRF oder global)
→ **Netzwerke** (fehlende Präfixe mit Größe und VRF prüfen, neue VRFs direkt anlegen)
→ **Prüfen** (Zusammenfassung aller Änderungen) → **Import** (Fortschritt, Live-Protokoll, Abbrechen)
- VMs werden pro Cluster eindeutig zugeordnet; vorhandene Präfixe werden wiederverwendet
- MAC-Adressen werden auch mit NetBox ≥ 4.2 (eigenes MAC-Modell) korrekt gesetzt
**Switche** (Aruba CX, ArubaOS-Switch/ProCurve, HPE Comware)
- Mehrere NetBox-Geräte in einem Schritt hinzufügen – Host aus der primären IP, Plattform aus Modell/Hersteller vorgeschlagen
- Plattform „Automatisch erkennen“ per SSH
- Parallele SSH-Abfragen; SSH-Hostschlüssel werden beim ersten Kontakt gespeichert und danach geprüft
- Schnittstellen, Interface-IP-Adressen sowie LLDP-/CDP-Nachbarn
- **Vorschau vor dem Schreiben**: alle Änderungen werden als Dry-Run berechnet und erst nach Bestätigung übertragen
- Interface-Typen aus Gerätetyp-Vorlagen bleiben unangetastet; Comware-Kurznamen (`GE1/0/1`) werden den
vollständigen NetBox-Namen (`GigabitEthernet1/0/1`) zugeordnet
- Kabel aus LLDP/CDP auch bei FQDN-Systemnamen oder über die Management-IP
- Die Switch-Konfiguration wird nur verändert, wenn „LLDP bei Bedarf aktivieren“ ausdrücklich eingeschaltet ist
**Windows-Clients** (agentlos per WMI/CIM über WinRM)
- Ziele aus dem Active Directory (optional Such-OU, nur aktivierte Konten, letzte Anmeldung innerhalb von N Tagen,
Server ein-/ausschließen) oder als Liste von Hostnamen, IP-Adressen, Netzen (`10.0.10.0/24`) und Bereichen
(`10.0.20.10-50`)
- Anmeldung über das Windows-Anmeldefenster (Domänenkonto mit lokalen Adminrechten, wird gegen die Domäne geprüft)
oder mit der aktuellen Windows-Anmeldung; das Kennwort bleibt nur im Arbeitsspeicher
- Liest Name, Hersteller, Modell (bei Lenovo der Modellname statt des Maschinentyps), Seriennummer, Bauform,
Betriebssystem mit Version/Build, angemeldeten Benutzer, CPU/RAM sowie physische Netzwerkkarten mit MAC und IPs
- Parallele Abfrage; nicht erreichbare Clients bleiben mit den AD-Daten sichtbar, Fehler mit konkretem Hinweis
- Übernahme als NetBox-Geräte mit Standort, Rolle und Mandant; Hersteller, Gerätetypen und Plattformen werden bei
Bedarf angelegt, optional Schnittstellen, MAC- und IP-Adressen – mit Vorschau vor dem Schreiben
- **Einrichtungshilfe** im Programm: Gruppenrichtlinie (WinRM, Dienst, Firewall), Berechtigungen, Fehlerbilder,
Prüfbefehle und ein Verbindungstest für einzelne Clients
**Offline-Modus (ohne NetBox)**
- Checkbox „Offline-Modus (ohne NetBox)“ in der Seitenleiste – gilt global, unabhängig vom Kundenprofil
- VMs und Switche werden ohne NetBox-Verbindung ausgelesen; Switche lassen sich dann manuell per Name anlegen
- Ausgewählte VMs, Clients bzw. ausgelesene Switche werden als JSON-Datei (`*.nbsync.json`) exportiert – ohne Passwörter,
Tokens oder Benutzernamen
- Auf einem Rechner mit NetBox-Zugang lädt „Aus Datei laden …“ (Seiten VMs, Switche und Windows-Clients) die Datei; danach laufen
Import-Assistent bzw. Dry-Run-Vorschau wie gewohnt. Switche werden über NetBox-Geräte-ID oder Namen zugeordnet
**VRFs & Netze**
- Mehrere VRFs oder Präfixe für einen Mandanten gesammelt anlegen
## Entwicklung
```powershell ```powershell
py -3 -m venv .venv py -3 -m venv .venv
.\.venv\Scripts\Activate.ps1 .\.venv\Scripts\Activate.ps1
pip install -r requirements-dev.txt pip install -r requirements-dev.txt
python main.py # Anwendung starten python main.py # start the application
python -m pytest # Tests python -m pytest # tests
``` ```
Projektstruktur: Project layout:
``` ```
netbox_sync/ netbox_sync/
core/ UI-unabhängige Logik: Konfiguration, NetBox, VMware/Proxmox, VM-Import, Switche, Windows-Clients core/ UI-independent logic: configuration, NetBox, VMware/Proxmox, VM import, switches, Windows clients
ui/ Qt-Oberfläche (PySide6): Hauptfenster, Seiten, Dialoge, Import-Assistent, Theme ui/ Qt interface (PySide6): main window, pages, dialogs, import wizard, theme
resources/ Icons resources/ icons
installer/ Inno-Setup-Skript installer/ Inno Setup script
tests/ pytest (Parser, Konfiguration, Sync gegen eine In-Memory-NetBox) 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`). (`winget install JRSoftware.InnoSetup`).
```powershell ```powershell
.\build.ps1 # Tests, PyInstaller-Build und Installer .\build.ps1 # tests, PyInstaller build and installer
.\build.ps1 -SkipInstaller # nur dist\NetBoxSynchronizer\ .\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`.
+11 -2
View File
@@ -1,15 +1,17 @@
<# <#
.SYNOPSIS .SYNOPSIS
Baut NetBox Synchronizer: Tests, PyInstaller-Build und Inno-Setup-Installer. Baut NetBox Synchronizer: Tests, PyInstaller-Build, Inno-Setup-Installer und portable EXE.
.EXAMPLE .EXAMPLE
.\build.ps1 # alles .\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 .\build.ps1 -SkipTests
#> #>
param( param(
[switch]$SkipTests, [switch]$SkipTests,
[switch]$SkipInstaller, [switch]$SkipInstaller,
[switch]$SkipPortable,
[string]$InnoSetupCompiler [string]$InnoSetupCompiler
) )
@@ -38,6 +40,13 @@ Write-Host "Baue NetBox Synchronizer $version …" -ForegroundColor Cyan
& $python -m PyInstaller --noconfirm --clean --log-level WARN NetBoxSynchronizer.spec & $python -m PyInstaller --noconfirm --clean --log-level WARN NetBoxSynchronizer.spec
if ($LASTEXITCODE) { throw "PyInstaller fehlgeschlagen." } 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) { if ($SkipInstaller) {
Write-Host "Fertig: dist\NetBoxSynchronizer\NetBoxSynchronizer.exe" -ForegroundColor Green Write-Host "Fertig: dist\NetBoxSynchronizer\NetBoxSynchronizer.exe" -ForegroundColor Green
return return
+2 -2
View File
@@ -1,9 +1,9 @@
; Inno Setup 6 script for NetBox Synchronizer. ; 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" #define AppName "NetBox Synchronizer"
#ifndef AppVersion #ifndef AppVersion
#define AppVersion "4.1.0" #define AppVersion "4.1.1"
#endif #endif
#define AppPublisher "Louis-Alexander Kerst" #define AppPublisher "Louis-Alexander Kerst"
#define AppExeName "NetBoxSynchronizer.exe" #define AppExeName "NetBoxSynchronizer.exe"
+1 -1
View File
@@ -1,7 +1,7 @@
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox.""" """NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
APP_NAME = "NetBox Synchronizer" APP_NAME = "NetBox Synchronizer"
APP_VERSION = "4.1.0" APP_VERSION = "4.1.1"
APP_PUBLISHER = "Louis-Alexander Kerst" APP_PUBLISHER = "Louis-Alexander Kerst"
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer" APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
+61 -264
View File
@@ -1,21 +1,16 @@
"""Agentless inventory of Windows clients via WMI/CIM over WinRM. """Agentless inventory of Windows clients via WMI/CIM over WinRM.
Targets come from Active Directory (computer objects) or from a list of host Targets come from Active Directory (computer objects) or from a list of host
names, IP addresses and ranges. Each reachable client is queried with names, IP addresses and ranges. Each reachable client is queried in-process
``Get-CimInstance`` through Windows PowerShell, so authentication uses the through the Windows WSMan COM API (see :mod:`netbox_sync.core.wsman`), so
Windows stack (Kerberos/Negotiate) – either the signed-in user or credentials authentication uses Kerberos/Negotiate with either the signed-in user or
from the Windows logon prompt. Passwords are handed to PowerShell via stdin and credentials from the Windows logon prompt. No helper processes are started.
never appear on a command line or on disk.
""" """
import base64
import ipaddress import ipaddress
import json
import os import os
import re import re
import shutil
import socket import socket
import subprocess
import sys import sys
import time import time
from concurrent.futures import ThreadPoolExecutor, as_completed from concurrent.futures import ThreadPoolExecutor, as_completed
@@ -134,193 +129,6 @@ def resolves(host):
return False 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("&lt;", "<").replace("&gt;", ">")
text = text.replace("&quot;", '"').replace("&amp;", "&")
return text.strip()
# -------------------------------------------------------------------------- # --------------------------------------------------------------------------
# Active Directory # Active Directory
# -------------------------------------------------------------------------- # --------------------------------------------------------------------------
@@ -334,17 +142,24 @@ def ad_filter(options):
return "(&" + "".join(parts) + ")" 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("/") server = (options.get("ad_server") or "").strip().strip("/")
base = (options.get("ad_base") or "").strip() base = (options.get("ad_base") or "").strip()
if not server and not base and credential is None: if server and not base:
return "" # LDAP://server binds to the default naming context of that domain or DC.
if not server and credential is not None: return server
server = os.environ.get("USERDNSDOMAIN", "") if not base:
if not server and not base: domain = os.environ.get("USERDNSDOMAIN", "")
raise ClientScanError("Dieser Rechner ist keiner Domäne beigetreten. Bitte unter „Domäne / DC“ die Domäne " if not domain:
"angeben, z. B. firma.local.") raise ClientScanError("Dieser Rechner ist keiner Domäne beigetreten. Bitte unter „Domäne / DC“ die "
return "LDAP://" + "/".join(part for part in (server, base) if part) "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): 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): 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).""" """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)) from netbox_sync.core import wsman
log(f"Suche Computerkonten im Active Directory{' unter ' + payload['path'] if payload['path'] else ''} …")
process = _start_powershell(_AD_SCRIPT, payload) 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) max_age = int(options.get("max_age_days") or 0)
limit = ((now or time.time()) - max_age * 86400) if max_age else None limit = ((now or time.time()) - max_age * 86400) if max_age else None
rows, stale = [], 0 rows, stale = [], 0
for item in _read_lines(process, cancelled): for item in items:
if "fatal" in item: if cancelled():
raise ClientScanError(f"Active-Directory-Abfrage fehlgeschlagen: {friendly_error(item['fatal'])}") break
if not item.get("name"): if not item.get("name"):
continue continue
last_logon = filetime_to_unix(item.get("last_logon")) 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", ""), "os_version": item.get("os_version", ""), "last_logon": last_logon, "dn": item.get("dn", ""),
"description": item.get("description", ""), "disabled": bool(item.get("disabled")), "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)" log(f"Active Directory: {len(rows)} Computer" + (f" ({stale} ohne Anmeldung seit {max_age} Tagen ausgelassen)"
if stale else ""), "success") if stale else ""), "success")
return rows return rows
@@ -420,7 +237,7 @@ def chassis_name(types):
def apply_scan(row, raw, now=None): 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 = dict(row)
row["scanned_at"] = now or time.time() row["scanned_at"] = now or time.time()
if not raw.get("ok"): if not raw.get("ok"):
@@ -540,65 +357,45 @@ def friendly_error(text):
# Scan # 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, 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).""" """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 port = WINRM_HTTPS_PORT if use_ssl else WINRM_HTTP_PORT
by_host = {row["host"]: row for row in rows}
results = [] results = []
def reachable(row): def scan(row):
if cancelled():
return None
host = row["host"] host = row["host"]
if not is_ip(host) and not resolves(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): if not port_open(host, port):
return row, f"Nicht erreichbar – ausgeschaltet oder WinRM-Port {port} geschlossen." return dict(row, status="offline", scanned_at=time.time(),
return row, None 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} …") with wsman.com_thread():
online = [] raw = wsman.query_client(host, credential, use_ssl, port, timeout)
with ThreadPoolExecutor(max_workers=min(64, max(1, len(rows)))) as pool: return apply_scan(row, raw)
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 …")
def run_chunk(hosts): log(f"Frage {len(rows)} Client(s) über WinRM (Port {port}) ab …")
payload = dict(_credential_payload(credential), hosts=hosts, ssl=use_ssl, port=port, timeout=timeout) with ThreadPoolExecutor(max_workers=max(1, min(parallel, len(rows) or 1))) as pool:
process = _start_powershell(_SCAN_SCRIPT, payload) futures = [pool.submit(scan, row) for row in rows]
done = set() for future in as_completed(futures):
for raw in _read_lines(process, cancelled): finished = future.result()
row = by_host.get(raw.get("host")) if finished is None:
if row is None:
continue continue
done.add(raw["host"])
finished = apply_scan(row, raw)
results.append(finished) results.append(finished)
on_result(finished) on_result(finished)
if not cancelled(): if cancelled():
problem = _stderr(process) or "PowerShell wurde unerwartet beendet." for pending in futures:
for host in hosts: pending.cancel()
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()
return results return results
+1 -1
View File
@@ -20,7 +20,7 @@ DEFAULT_SETTINGS = {
"enable_lldp": False, # allow configuration changes on switches "enable_lldp": False, # allow configuration changes on switches
"create_cables": True, "create_cables": True,
"offline_mode": False, # collect and export to JSON without NetBox "offline_mode": False, # collect and export to JSON without NetBox
"parallel_wmi": 8, # concurrent PowerShell sessions for client scans "parallel_wmi": 8, # concurrent WinRM sessions for client scans
} }
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
+298
View File
@@ -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
+1 -1
View File
@@ -60,7 +60,7 @@ class SettingsPage(Page):
self.parallel_wmi.setRange(1, 32) self.parallel_wmi.setRange(1, 32)
self.parallel_wmi.setSuffix(" gleichzeitig") self.parallel_wmi.setSuffix(" gleichzeitig")
self.parallel_wmi.setFixedWidth(160) self.parallel_wmi.setFixedWidth(160)
form.addRow("PowerShell-Sitzungen", self.parallel_wmi) form.addRow("WinRM-Sitzungen", self.parallel_wmi)
clients.add(form) clients.add(form)
clients.add(label("Kennwörter aus dem Windows-Anmeldefenster werden nie gespeichert, sondern nur bis zum " 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)) "Beenden des Programms im Arbeitsspeicher gehalten.", muted=True, wrap=True))
+1
View File
@@ -3,3 +3,4 @@ pynetbox>=7.4
pyvmomi>=8.0 pyvmomi>=8.0
requests>=2.31 requests>=2.31
paramiko>=3.4 paramiko>=3.4
pywin32>=306; sys_platform == "win32"
+41
View File
@@ -181,3 +181,44 @@ def test_profile_keeps_client_options(tmp_path, monkeypatch):
assert "password" not in loaded["Kunde"]["clients"] assert "password" not in loaded["Kunde"]["clients"]
assert settings["parallel_wmi"] == 8 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