Compare commits

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

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

No files matched your search

+21 -15
View File
@@ -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",
)
+2 -1
View File
@@ -105,4 +105,5 @@ Voraussetzung für den Installer ist [Inno Setup 6](https://jrsoftware.org/isinf
.\build.ps1 -SkipInstaller # nur dist\NetBoxSynchronizer\
```
Ergebnis: `dist\installer\NetBoxSynchronizer-Setup-<version>.exe`. Die Version steht in `netbox_sync/__init__.py`.
Ergebnis: `dist\installer\NetBoxSynchronizer-Setup-<version>.exe` sowie die portable Variante
`dist\portable\NetBox VM Import.exe` (ohne Installation lauffähig; `-SkipPortable` lässt sie weg). Die Version steht in `netbox_sync/__init__.py`.
+11 -2
View File
@@ -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
+2 -2
View File
@@ -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.2.0"
#endif
#define AppPublisher "Louis-Alexander Kerst"
#define AppExeName "NetBoxSynchronizer.exe"
+1 -1
View File
@@ -1,7 +1,7 @@
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
APP_NAME = "NetBox Synchronizer"
APP_VERSION = "4.1.0"
APP_VERSION = "4.2.0"
APP_PUBLISHER = "Louis-Alexander Kerst"
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.
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("&lt;", "<").replace("&gt;", ">")
text = text.replace("&quot;", '"').replace("&amp;", "&")
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
+4 -1
View File
@@ -20,7 +20,7 @@ DEFAULT_SETTINGS = {
"enable_lldp": False, # allow configuration changes on switches
"create_cables": True,
"offline_mode": False, # collect and export to JSON without NetBox
"parallel_wmi": 8, # concurrent PowerShell sessions for client scans
"parallel_wmi": 8, # concurrent WinRM sessions for client scans
}
log = logging.getLogger(__name__)
@@ -115,6 +115,7 @@ def empty_profile(name):
"switches": [],
# Remembered assignment "<source id>:<hypervisor cluster>" -> NetBox cluster name.
"cluster_map": {},
"host_map": {},
# Windows client scan: targets and options, never a password.
"clients": dict(DEFAULT_CLIENT_OPTIONS),
}
@@ -162,6 +163,7 @@ class ProfileStore:
"netbox_token": self._decrypt(record.get("netbox_token_encrypted", ""), f"{name}: NetBox-Token"),
"netbox_ignore_ssl": bool(record.get("netbox_ignore_ssl", record.get("ignore_ssl_errors", False))),
"cluster_map": dict(record.get("cluster_map", {})),
"host_map": dict(record.get("host_map", {})),
"clients": {**DEFAULT_CLIENT_OPTIONS, **{key: value for key, value in record.get("clients", {}).items()
if key in DEFAULT_CLIENT_OPTIONS}},
})
@@ -225,6 +227,7 @@ class ProfileStore:
"sources": [self._encrypt_record(source) for source in profile.get("sources", [])],
"switches": [self._encrypt_record(switch) for switch in profile.get("switches", [])],
"cluster_map": dict(profile.get("cluster_map", {})),
"host_map": dict(profile.get("host_map", {})),
"clients": dict(profile.get("clients", DEFAULT_CLIENT_OPTIONS)),
})
+1
View File
@@ -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)
+4 -3
View File
@@ -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")
+38 -2
View File
@@ -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:
+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
+68 -2
View File
@@ -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}")
+1 -1
View File
@@ -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))
+1
View File
@@ -3,3 +3,4 @@ pynetbox>=7.4
pyvmomi>=8.0
requests>=2.31
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 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