diff --git a/netbox_sync/core/clients.py b/netbox_sync/core/clients.py
index 3d3f871..08f2988 100644
--- a/netbox_sync/core/clients.py
+++ b/netbox_sync/core/clients.py
@@ -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'(.*?)', text, re.S)
- text = "".join(parts).replace("_x000D__x000A_", "\n").replace("<", "<").replace(">", ">")
- text = text.replace(""", '"').replace("&", "&")
- return text.strip()
-
-
# --------------------------------------------------------------------------
# Active Directory
# --------------------------------------------------------------------------
@@ -334,17 +142,24 @@ def ad_filter(options):
return "(&" + "".join(parts) + ")"
-def ad_path(options, credential):
+def domain_base(domain):
+ return ",".join(f"DC={part}" for part in domain.strip(".").split(".") if part)
+
+
+def ad_location(options):
+ """``server/base`` for the LDAP query; defaults to the domain of the signed-in user."""
server = (options.get("ad_server") or "").strip().strip("/")
base = (options.get("ad_base") or "").strip()
- if not server and not base and credential is None:
- return ""
- if not server and credential is not None:
- server = os.environ.get("USERDNSDOMAIN", "")
- if not server and not base:
- raise ClientScanError("Dieser Rechner ist keiner Domäne beigetreten. Bitte unter „Domäne / DC“ die Domäne "
- "angeben, z. B. firma.local.")
- return "LDAP://" + "/".join(part for part in (server, base) if part)
+ if server and not base:
+ # LDAP://server binds to the default naming context of that domain or DC.
+ return server
+ if not base:
+ domain = os.environ.get("USERDNSDOMAIN", "")
+ if not domain:
+ raise ClientScanError("Dieser Rechner ist keiner Domäne beigetreten. Bitte unter „Domäne / DC“ die "
+ "Domäne angeben, z. B. firma.local.")
+ base = domain_base(domain)
+ return "/".join(part for part in (server, base) if part)
def filetime_to_unix(value):
@@ -355,15 +170,21 @@ def filetime_to_unix(value):
def query_ad(options, credential=None, log=lambda *_args: None, cancelled=lambda: False, now=None):
"""Return computer objects from Active Directory as client rows (not yet scanned)."""
- payload = dict(_credential_payload(credential), path=ad_path(options, credential), filter=ad_filter(options))
- log(f"Suche Computerkonten im Active Directory{' unter ' + payload['path'] if payload['path'] else ''} …")
- process = _start_powershell(_AD_SCRIPT, payload)
+ from netbox_sync.core import wsman
+
+ location = ad_location(options)
+ log(f"Suche Computerkonten im Active Directory (LDAP://{location}) …")
+ try:
+ with wsman.com_thread():
+ items = wsman.search_ad(location, ad_filter(options), credential)
+ except wsman.WSManError as error:
+ raise ClientScanError(f"Active-Directory-Abfrage fehlgeschlagen: {friendly_error(str(error))}") from error
max_age = int(options.get("max_age_days") or 0)
limit = ((now or time.time()) - max_age * 86400) if max_age else None
rows, stale = [], 0
- for item in _read_lines(process, cancelled):
- if "fatal" in item:
- raise ClientScanError(f"Active-Directory-Abfrage fehlgeschlagen: {friendly_error(item['fatal'])}")
+ for item in items:
+ if cancelled():
+ break
if not item.get("name"):
continue
last_logon = filetime_to_unix(item.get("last_logon"))
@@ -375,10 +196,6 @@ def query_ad(options, credential=None, log=lambda *_args: None, cancelled=lambda
"os_version": item.get("os_version", ""), "last_logon": last_logon, "dn": item.get("dn", ""),
"description": item.get("description", ""), "disabled": bool(item.get("disabled")),
}))
- if process.returncode not in (0, None) and not rows:
- problem = _stderr(process)
- if problem:
- raise ClientScanError(f"Active-Directory-Abfrage fehlgeschlagen: {problem}")
log(f"Active Directory: {len(rows)} Computer" + (f" ({stale} ohne Anmeldung seit {max_age} Tagen ausgelassen)"
if stale else ""), "success")
return rows
@@ -420,7 +237,7 @@ def chassis_name(types):
def apply_scan(row, raw, now=None):
- """Merge the raw PowerShell result into a result row."""
+ """Merge the raw WinRM result into a result row."""
row = dict(row)
row["scanned_at"] = now or time.time()
if not raw.get("ok"):
@@ -540,65 +357,45 @@ def friendly_error(text):
# Scan
# --------------------------------------------------------------------------
-def _chunks(items, count):
- count = max(1, min(count, len(items)))
- return [items[index::count] for index in range(count)]
-
-
def scan_clients(rows, credential=None, use_ssl=False, parallel=8, timeout=30, log=lambda *_args: None,
- on_result=lambda _row: None, cancelled=lambda: False):
+ on_result=lambda _row: None, cancelled=lambda: False, query=None):
"""Query every row's host. ``on_result`` is called for each finished row (any thread)."""
+ if sys.platform != "win32" and query is None:
+ raise ClientScanError("Die Abfrage von Windows-Clients ist nur unter Windows verfügbar.")
port = WINRM_HTTPS_PORT if use_ssl else WINRM_HTTP_PORT
- by_host = {row["host"]: row for row in rows}
results = []
- def reachable(row):
+ def scan(row):
+ if cancelled():
+ return None
host = row["host"]
if not is_ip(host) and not resolves(host):
- return row, "Rechnername kann nicht aufgelöst werden (DNS)."
+ return dict(row, status="offline", message="Rechnername kann nicht aufgelöst werden (DNS).",
+ scanned_at=time.time())
if not port_open(host, port):
- return row, f"Nicht erreichbar – ausgeschaltet oder WinRM-Port {port} geschlossen."
- return row, None
+ return dict(row, status="offline", scanned_at=time.time(),
+ message=f"Nicht erreichbar – ausgeschaltet oder WinRM-Port {port} geschlossen.")
+ if cancelled():
+ return None
+ if query is not None:
+ raw = query(host)
+ else:
+ from netbox_sync.core import wsman
- log(f"Prüfe Erreichbarkeit von {len(rows)} Client(s) auf Port {port} …")
- online = []
- with ThreadPoolExecutor(max_workers=min(64, max(1, len(rows)))) as pool:
- for future in as_completed([pool.submit(reachable, row) for row in rows]):
- if cancelled():
- break
- row, problem = future.result()
- if problem:
- finished = dict(row, status="offline", message=problem, scanned_at=time.time())
- results.append(finished)
- on_result(finished)
- else:
- online.append(row["host"])
- if cancelled() or not online:
- return results
- log(f"{len(online)} Client(s) erreichbar, frage WMI ab …")
+ with wsman.com_thread():
+ raw = wsman.query_client(host, credential, use_ssl, port, timeout)
+ return apply_scan(row, raw)
- def run_chunk(hosts):
- payload = dict(_credential_payload(credential), hosts=hosts, ssl=use_ssl, port=port, timeout=timeout)
- process = _start_powershell(_SCAN_SCRIPT, payload)
- done = set()
- for raw in _read_lines(process, cancelled):
- row = by_host.get(raw.get("host"))
- if row is None:
+ log(f"Frage {len(rows)} Client(s) über WinRM (Port {port}) ab …")
+ with ThreadPoolExecutor(max_workers=max(1, min(parallel, len(rows) or 1))) as pool:
+ futures = [pool.submit(scan, row) for row in rows]
+ for future in as_completed(futures):
+ finished = future.result()
+ if finished is None:
continue
- done.add(raw["host"])
- finished = apply_scan(row, raw)
results.append(finished)
on_result(finished)
- if not cancelled():
- problem = _stderr(process) or "PowerShell wurde unerwartet beendet."
- for host in hosts:
- if host not in done:
- finished = dict(by_host[host], status="error", message=friendly_error(problem),
- scanned_at=time.time())
- results.append(finished)
- on_result(finished)
-
- with ThreadPoolExecutor(max_workers=max(1, parallel)) as pool:
- for future in as_completed([pool.submit(run_chunk, hosts) for hosts in _chunks(online, parallel)]):
- future.result()
+ if cancelled():
+ for pending in futures:
+ pending.cancel()
return results
diff --git a/netbox_sync/core/config.py b/netbox_sync/core/config.py
index baab5ac..2b61dcb 100644
--- a/netbox_sync/core/config.py
+++ b/netbox_sync/core/config.py
@@ -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__)
diff --git a/netbox_sync/core/wsman.py b/netbox_sync/core/wsman.py
new file mode 100644
index 0000000..6b2cd24
--- /dev/null
+++ b/netbox_sync/core/wsman.py
@@ -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.
+ 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''
+ f"{HKEY_LOCAL_MACHINE}"
+ f"{key}{value}"
+ ""
+ )
+ 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_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
diff --git a/netbox_sync/ui/pages/settings.py b/netbox_sync/ui/pages/settings.py
index 83fe2d6..0c26d1f 100644
--- a/netbox_sync/ui/pages/settings.py
+++ b/netbox_sync/ui/pages/settings.py
@@ -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))
diff --git a/requirements.txt b/requirements.txt
index 2f0a49c..3267182 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -3,3 +3,4 @@ pynetbox>=7.4
pyvmomi>=8.0
requests>=2.31
paramiko>=3.4
+pywin32>=306; sys_platform == "win32"
diff --git a/tests/test_clients.py b/tests/test_clients.py
index 9a30a09..0df3965 100644
--- a/tests/test_clients.py
+++ b/tests/test_clients.py
@@ -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 = """
+Intel(R) Ethernettrue
+192.168.65.43fe80::1
+
+2025-12-23T17:23:16Z
+"""
+
+
+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