Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
799a5aa007 | ||
|
|
d10190b7bc | ||
|
|
c42cedd655 |
No files matched your search
+14
-8
@@ -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,7 +87,12 @@ exe = EXE(
|
|||||||
version=version_info,
|
version=version_info,
|
||||||
)
|
)
|
||||||
|
|
||||||
coll = COLLECT(
|
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,
|
exe,
|
||||||
a.binaries,
|
a.binaries,
|
||||||
a.datas,
|
a.datas,
|
||||||
@@ -94,4 +100,4 @@ coll = COLLECT(
|
|||||||
upx=False,
|
upx=False,
|
||||||
upx_exclude=[],
|
upx_exclude=[],
|
||||||
name="NetBoxSynchronizer",
|
name="NetBoxSynchronizer",
|
||||||
)
|
)
|
||||||
@@ -105,4 +105,5 @@ Voraussetzung für den Installer ist [Inno Setup 6](https://jrsoftware.org/isinf
|
|||||||
.\build.ps1 -SkipInstaller # nur dist\NetBoxSynchronizer\
|
.\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`.
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -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,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"
|
||||||
|
|
||||||
|
|||||||
+64
-267
@@ -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("<", "<").replace(">", ">")
|
|
||||||
text = text.replace(""", '"').replace("&", "&")
|
|
||||||
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).",
|
||||||
if not port_open(host, port):
|
|
||||||
return row, f"Nicht erreichbar – ausgeschaltet oder WinRM-Port {port} geschlossen."
|
|
||||||
return row, None
|
|
||||||
|
|
||||||
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 …")
|
|
||||||
|
|
||||||
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:
|
|
||||||
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())
|
scanned_at=time.time())
|
||||||
|
if not port_open(host, port):
|
||||||
|
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
|
||||||
|
|
||||||
|
with wsman.com_thread():
|
||||||
|
raw = wsman.query_client(host, credential, use_ssl, port, timeout)
|
||||||
|
return apply_scan(row, raw)
|
||||||
|
|
||||||
|
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
|
||||||
results.append(finished)
|
results.append(finished)
|
||||||
on_result(finished)
|
on_result(finished)
|
||||||
|
if cancelled():
|
||||||
with ThreadPoolExecutor(max_workers=max(1, parallel)) as pool:
|
for pending in futures:
|
||||||
for future in as_completed([pool.submit(run_chunk, hosts) for hosts in _chunks(online, parallel)]):
|
pending.cancel()
|
||||||
future.result()
|
|
||||||
return results
|
return results
|
||||||
@@ -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__)
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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))
|
||||||
|
|||||||
@@ -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"
|
||||||
@@ -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
|
||||||
Reference in new issue
Block a user