feat: scan Windows clients with the NetBox Windows Agent in listen mode
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
43c5e5e85a
commit
a67b0d3e5c
8 files changed
+521
-24
No files matched your search
@@ -0,0 +1,114 @@
|
||||
"""Query the NetBox Windows Agent in "listen" mode (protocol v1).
|
||||
|
||||
The agent answers ``GET /v1/info`` without authentication. The inventory at
|
||||
``GET /v1/inventory`` needs a signature (HMAC-SHA256 with a key derived from
|
||||
the shared scan key) over a fresh nonce and the current time, and comes back
|
||||
encrypted with AES-256-GCM, so serial numbers and software lists never cross
|
||||
the network in clear text even without TLS certificates.
|
||||
|
||||
The decrypted inventory has the same shape as the WinRM scan
|
||||
(:func:`netbox_sync.core.wsman.query_client`), so it runs through the same
|
||||
table and NetBox transfer as the agentless client scan.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import http.client
|
||||
import json
|
||||
import secrets
|
||||
import time
|
||||
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||||
|
||||
DEFAULT_PORT = 8731
|
||||
PROTOCOL = 1
|
||||
AGENT_NAME = "netbox-windows-agent"
|
||||
|
||||
|
||||
class AgentError(Exception):
|
||||
"""The host answered, but not as an agent we can read (wrong key, other service …)."""
|
||||
|
||||
|
||||
def derive_key(secret, purpose):
|
||||
return hmac.new(secret.encode(), purpose.encode(), hashlib.sha256).digest()
|
||||
|
||||
|
||||
def new_scan_key():
|
||||
"""Random shared key for the agents of one customer (URL-safe, 43 characters)."""
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def _get(host, port, path, headers=None, timeout=5.0):
|
||||
connection = http.client.HTTPConnection(host, port, timeout=timeout)
|
||||
try:
|
||||
connection.request("GET", path, headers=headers or {})
|
||||
response = connection.getresponse()
|
||||
body = response.read(16 * 1024 * 1024)
|
||||
return response.status, body
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def _json(body):
|
||||
try:
|
||||
return json.loads(body.decode("utf-8"))
|
||||
except (UnicodeDecodeError, ValueError) as error:
|
||||
raise AgentError("keine gültige Antwort (kein NetBox-Agent?)") from error
|
||||
|
||||
|
||||
def info(host, port=DEFAULT_PORT, timeout=3.0):
|
||||
status, body = _get(host, port, "/v1/info", timeout=timeout)
|
||||
data = _json(body)
|
||||
if status != 200 or data.get("agent") != AGENT_NAME:
|
||||
raise AgentError("kein NetBox-Agent auf diesem Port")
|
||||
return data
|
||||
|
||||
|
||||
def inventory(host, key, port=DEFAULT_PORT, timeout=60.0):
|
||||
"""Decrypted inventory dict of one agent."""
|
||||
nonce = secrets.token_hex(16)
|
||||
ts = str(int(time.time()))
|
||||
signature = hmac.new(derive_key(key, "netbox-agent auth v1"), f"GET\n/v1/inventory\n{nonce}\n{ts}".encode(),
|
||||
hashlib.sha256).hexdigest()
|
||||
status, body = _get(host, port, f"/v1/inventory?nonce={nonce}&ts={ts}", {"X-Agent-Signature": signature},
|
||||
timeout)
|
||||
data = _json(body)
|
||||
if status != 200:
|
||||
reason = data.get("error", f"HTTP {status}")
|
||||
raise AgentError({
|
||||
"wrong key": "Agent-Schlüssel stimmt nicht",
|
||||
"clock skew too large": "Uhrzeit von Client und diesem Rechner weicht mehr als 5 Minuten ab",
|
||||
"address not allowed": "dieser Rechner ist in allowed_networks des Agenten nicht freigegeben",
|
||||
}.get(reason, f"Agent meldet: {reason}"))
|
||||
try:
|
||||
payload = AESGCM(derive_key(key, "netbox-agent enc v1")).decrypt(
|
||||
base64.b64decode(data["iv"]), base64.b64decode(data["data"]), nonce.encode())
|
||||
except Exception as error: # noqa: BLE001 - InvalidTag, KeyError, binascii.Error
|
||||
raise AgentError("Antwort lässt sich nicht entschlüsseln (falscher Schlüssel?)") from error
|
||||
return json.loads(payload.decode("utf-8"))
|
||||
|
||||
|
||||
def query(host, key, port=DEFAULT_PORT, timeout=60.0):
|
||||
"""Raw result for :func:`netbox_sync.core.clients.apply_scan` – never raises."""
|
||||
try:
|
||||
result = inventory(host, key, port, timeout)
|
||||
except AgentError as error:
|
||||
return {"host": host, "ok": False, "error": str(error)}
|
||||
except (OSError, http.client.HTTPException) as error:
|
||||
return {"host": host, "ok": False, "error": f"Agent nicht erreichbar: {error}"}
|
||||
result.update(host=host, ok=True)
|
||||
return result
|
||||
|
||||
|
||||
def agent_config(key, port=DEFAULT_PORT, allowed_networks=(), collect_software=True):
|
||||
"""``config.json`` for agents in listen mode (no NetBox access needed on the clients)."""
|
||||
return {
|
||||
"mode": "listen",
|
||||
"listen_port": port,
|
||||
"scan_key": key,
|
||||
"allowed_networks": list(allowed_networks),
|
||||
"inventory_cache_seconds": 300,
|
||||
"collect_software": collect_software,
|
||||
"max_software_entries": 250,
|
||||
}
|
||||
@@ -21,7 +21,7 @@ WINRM_HTTPS_PORT = 5986
|
||||
MAX_RANGE = 4096
|
||||
|
||||
DEFAULT_CLIENT_OPTIONS = {
|
||||
"mode": "ad", # ad | hosts
|
||||
"mode": "ad", # ad | hosts | agent
|
||||
"ad_server": "", # domain or domain controller, empty = own domain
|
||||
"ad_base": "", # search base (OU DN), empty = whole domain
|
||||
"include_servers": False,
|
||||
@@ -31,6 +31,10 @@ DEFAULT_CLIENT_OPTIONS = {
|
||||
"use_current_user": False,
|
||||
"username": "", # remembered for the logon prompt, never the password
|
||||
"use_ssl": False,
|
||||
# NetBox Windows Agent in listen mode (the key itself is a profile secret).
|
||||
"agent_targets": "",
|
||||
"agent_port": 8731,
|
||||
"agent_networks": "", # allowed_networks written into the agent configuration
|
||||
# Last choices in the NetBox transfer dialog.
|
||||
"netbox_site": None,
|
||||
"netbox_role": "Client",
|
||||
@@ -269,6 +273,11 @@ def apply_scan(row, raw, now=None):
|
||||
"os_architecture": raw.get("os_architecture", ""),
|
||||
"installed": raw.get("installed", ""),
|
||||
"last_boot": raw.get("last_boot", ""),
|
||||
"source": raw.get("source", "winrm"),
|
||||
"agent_version": raw.get("agent_version", ""),
|
||||
"software_count": len(raw.get("software") or []),
|
||||
"disks": [{"model": disk.get("model", ""), "size": int(disk.get("size") or 0)}
|
||||
for disk in raw.get("disks") or []],
|
||||
# Only real adapters: VPN/TAP drivers report no MAC or are not physical.
|
||||
"interfaces": [_interface(nic) for nic in raw.get("nics") or [] if nic.get("physical") and nic.get("mac")],
|
||||
})
|
||||
@@ -358,11 +367,14 @@ def friendly_error(text):
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
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, query=None):
|
||||
"""Query every row's host. ``on_result`` is called for each finished row (any thread)."""
|
||||
on_result=lambda _row: None, cancelled=lambda: False, query=None, port=None, service="WinRM"):
|
||||
"""Query every row's host. ``on_result`` is called for each finished row (any thread).
|
||||
|
||||
``query``/``port``/``service`` replace the WinRM query, e.g. by the NetBox Windows Agent.
|
||||
"""
|
||||
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 = port or (WINRM_HTTPS_PORT if use_ssl else WINRM_HTTP_PORT)
|
||||
results = []
|
||||
|
||||
def scan(row):
|
||||
@@ -374,7 +386,7 @@ def scan_clients(rows, credential=None, use_ssl=False, parallel=8, timeout=30, l
|
||||
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.")
|
||||
message=f"Nicht erreichbar – ausgeschaltet oder {service}-Port {port} geschlossen.")
|
||||
if cancelled():
|
||||
return None
|
||||
if query is not None:
|
||||
@@ -386,7 +398,7 @@ def scan_clients(rows, credential=None, use_ssl=False, parallel=8, timeout=30, l
|
||||
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 …")
|
||||
log(f"Frage {len(rows)} Client(s) über {service} (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):
|
||||
|
||||
@@ -115,6 +115,8 @@ def empty_profile(name):
|
||||
"netbox_url": "",
|
||||
"netbox_token": "",
|
||||
"netbox_ignore_ssl": False,
|
||||
# Shared key of the NetBox Windows Agents of this customer (listen mode).
|
||||
"agent_key": "",
|
||||
"sources": [],
|
||||
"switches": [],
|
||||
# Remembered assignment "<source id>:<hypervisor cluster>" -> NetBox cluster name.
|
||||
@@ -176,6 +178,8 @@ class ProfileStore:
|
||||
profile.update({
|
||||
"netbox_url": record.get("netbox_url", ""),
|
||||
"netbox_token": self._decrypt(record.get("netbox_token_encrypted", ""), f"{name}: NetBox-Token"),
|
||||
"agent_key": self._decrypt(record.get("agent_key_encrypted", ""), f"{name}: Agent-Schlüssel")
|
||||
if record.get("agent_key_encrypted") else "",
|
||||
"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", {})),
|
||||
@@ -253,6 +257,7 @@ class ProfileStore:
|
||||
"name": name,
|
||||
"netbox_url": profile.get("netbox_url", ""),
|
||||
"netbox_token_encrypted": protect(profile.get("netbox_token", "")),
|
||||
"agent_key_encrypted": protect(profile.get("agent_key", "")) if profile.get("agent_key") else "",
|
||||
"netbox_ignore_ssl": bool(profile.get("netbox_ignore_ssl", False)),
|
||||
"sources": [self._encrypt_record(source) for source in profile.get("sources", [])],
|
||||
"switches": [self._encrypt_record(switch) for switch in profile.get("switches", [])],
|
||||
|
||||
@@ -9,7 +9,7 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from PySide6.QtCore import QTimer
|
||||
from PySide6.QtWidgets import QFileDialog
|
||||
|
||||
from netbox_sync.core import backups, exchange, lancom, netbox
|
||||
from netbox_sync.core import agent_client, backups, exchange, lancom, netbox
|
||||
from netbox_sync.core.client_sync import ClientSyncEngine
|
||||
from netbox_sync.core.clients import ClientScanError, expand_targets, new_row, query_ad, scan_clients
|
||||
from netbox_sync.core.config import known_hosts_path
|
||||
@@ -645,9 +645,19 @@ class Actions:
|
||||
parallel = max(1, int(self.state.settings.get("parallel_wmi", 8)))
|
||||
mode = options.get("mode", "ad")
|
||||
hosts = []
|
||||
if rows is None and mode == "hosts":
|
||||
agent = mode == "agent"
|
||||
agent_key = (self.state.profile or {}).get("agent_key", "")
|
||||
agent_port = int(options.get("agent_port") or agent_client.DEFAULT_PORT)
|
||||
if agent and not agent_key:
|
||||
widgets.message(self.window, "Agent-Schlüssel fehlt",
|
||||
"Bitte zuerst einen Agent-Schlüssel erzeugen und mit der Agent-Konfiguration verteilen.",
|
||||
"info")
|
||||
return
|
||||
if agent:
|
||||
parallel = max(parallel, 32)
|
||||
if rows is None and mode in ("hosts", "agent"):
|
||||
try:
|
||||
hosts = expand_targets(options.get("hosts", ""))
|
||||
hosts = expand_targets(options.get("agent_targets" if agent else "hosts", ""))
|
||||
except ClientScanError as error:
|
||||
widgets.error(self.window, "Ungültige Eingabe", str(error))
|
||||
return
|
||||
@@ -684,11 +694,17 @@ class Actions:
|
||||
ctx.progress(done[0], len(targets), row["name"])
|
||||
|
||||
ctx.progress(0, len(targets), "")
|
||||
extra = ({"query": lambda host: agent_client.query(host, agent_key, agent_port), "port": agent_port,
|
||||
"service": "Agent"} if agent else {})
|
||||
results = scan_clients(targets, credential, bool(options.get("use_ssl")), parallel, log=ctx.log,
|
||||
on_result=on_result, cancelled=lambda: ctx.cancelled)
|
||||
on_result=on_result, cancelled=lambda: ctx.cancelled, **extra)
|
||||
ctx.check_cancelled()
|
||||
by_host = {row["host"]: row for row in results}
|
||||
return nb, engine, [by_host.get(row["host"], row) for row in targets]
|
||||
scanned = [by_host.get(row["host"], row) for row in targets]
|
||||
if agent and targets_given is None:
|
||||
# A range scan: only hosts where an agent answered (or rejected us) are of interest.
|
||||
scanned = [row for row in scanned if row["status"] != "offline"]
|
||||
return nb, engine, scanned
|
||||
|
||||
def success(result):
|
||||
nb, engine, scanned = result
|
||||
|
||||
@@ -119,6 +119,77 @@ winrm/config/listener</span>.</td></tr>
|
||||
"""
|
||||
|
||||
|
||||
AGENT_REPO = "https://git.mrblake.cc/MrBlake/Netbox-Client-Agent-for-Windows"
|
||||
|
||||
|
||||
def _agent_html():
|
||||
accent = theme.color("accent")
|
||||
code_bg = theme.color("log_bg")
|
||||
return f"""
|
||||
<style>
|
||||
h2 {{ font-size: 13pt; margin: 14px 0 6px 0; }}
|
||||
h3 {{ font-size: 10.5pt; margin: 12px 0 4px 0; color: {accent}; }}
|
||||
p, li {{ line-height: 140%; }}
|
||||
.path {{ font-family: 'Cascadia Mono', Consolas, monospace; background: {code_bg}; }}
|
||||
td {{ padding: 3px 10px 3px 0; vertical-align: top; }}
|
||||
</style>
|
||||
|
||||
<h2>NetBox-Agent statt WinRM</h2>
|
||||
<p>Der <b>NetBox Windows Agent</b> läuft unsichtbar als SYSTEM-Aufgabe auf den Clients und stellt sein
|
||||
Inventar auf einem TCP-Port (Standard 8731) bereit. Dieser Rechner scannt IP-Bereiche und liest die Agenten
|
||||
aus – <b>ohne WinRM, ohne Administratorkonto und ohne NetBox-Zugang auf den Clients</b>. Die Abfrage ist mit
|
||||
dem Agent-Schlüssel signiert, die Antwort mit AES-256 verschlüsselt. Benutzer bemerken nichts: kein Fenster,
|
||||
keine Firewall-Abfrage.</p>
|
||||
|
||||
<h3>1. Schlüssel und Konfiguration</h3>
|
||||
<ol>
|
||||
<li>Modus <b>NetBox-Agent (Netzwerk-Scan)</b> wählen und <b>Schlüssel erzeugen</b> (einer pro Kunde,
|
||||
verschlüsselt im Profil gespeichert).</li>
|
||||
<li>Optional unter <b>Freigegebene Netze</b> das Admin-Netz eintragen – dann nehmen die Agenten nur von dort
|
||||
Verbindungen an.</li>
|
||||
<li><b>Agent-Konfiguration speichern …</b> erzeugt die fertige <span class="path">config.json</span>.</li>
|
||||
</ol>
|
||||
|
||||
<h3>2. Dateien zusammenstellen</h3>
|
||||
<p><span class="path">agent.exe</span>, <span class="path">install.ps1</span>,
|
||||
<span class="path">uninstall.ps1</span> und <span class="path">gpo-startup.ps1</span> kommen aus dem
|
||||
Agent-Projekt ({AGENT_REPO}, Ordner <span class="path">dist</span> bzw. <span class="path">scripts</span>),
|
||||
dazu die eben gespeicherte <span class="path">config.json</span>.</p>
|
||||
|
||||
<h3>3a. Verteilung per Intune</h3>
|
||||
<table>
|
||||
<tr><td>Paket</td><td>agent.exe, config.json, install.ps1, uninstall.ps1 als Win32-App (.intunewin)</td></tr>
|
||||
<tr><td>Installation</td><td><span class="path">powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\\install.ps1
|
||||
-SourceDirectory .</span></td></tr>
|
||||
<tr><td>Deinstallation</td><td><span class="path">powershell.exe -NoProfile -ExecutionPolicy Bypass -File
|
||||
.\\uninstall.ps1</span></td></tr>
|
||||
<tr><td>Verhalten</td><td>System · als <b>Erforderlich</b> einer Gerätegruppe zuweisen</td></tr>
|
||||
<tr><td>Erkennung</td><td>Datei <span class="path">C:\\Program Files\\NetBox Windows Agent</span> /
|
||||
<span class="path">agent.exe</span>, Methode „Zeichenfolge (Version)“, „Größer als oder gleich“, z. B. 0.2.0</td></tr>
|
||||
</table>
|
||||
|
||||
<h3>3b. Verteilung per Gruppenrichtlinie</h3>
|
||||
<ol>
|
||||
<li>Alle fünf Dateien in eine Freigabe legen, die „Domänencomputer“ lesen dürfen, z. B.
|
||||
<span class="path">\\\\fileserver\\NetBoxAgent$</span>.</li>
|
||||
<li>GPO für die OU der Clients: <b>Computerkonfiguration › Richtlinien › Windows-Einstellungen › Skripts ›
|
||||
Starten › PowerShell-Skripts</b> – <span class="path">\\\\fileserver\\NetBoxAgent$\\gpo-startup.ps1</span>
|
||||
ohne Parameter.</li>
|
||||
<li><b>Computerkonfiguration › Administrative Vorlagen › System › Anmelden › Beim Neustart des Computers und
|
||||
bei der Anmeldung immer auf das Netzwerk warten</b> = Aktiviert.</li>
|
||||
</ol>
|
||||
<p>Das Skript installiert beim Start nur, wenn sich agent.exe oder config.json auf der Freigabe geändert
|
||||
haben – neue Versionen oder ein neuer Schlüssel werden so automatisch verteilt.</p>
|
||||
|
||||
<h3>4. Scannen</h3>
|
||||
<p>IP-Bereiche als Ziele eintragen und <b>Abfragen</b>. Es erscheinen nur Rechner, auf denen ein Agent
|
||||
antwortet; die Übertragung nach NetBox läuft wie beim WinRM-Scan mit Vorschau.</p>
|
||||
<p>Findet der Scan keinen Agenten: Läuft die Aufgabe „NetBox Windows Agent Listener“? Ist Port 8731
|
||||
zwischen den Netzen offen (<span class="path">Test-NetConnection PC0815 -Port 8731</span>)? Liegt dieser
|
||||
Rechner in den freigegebenen Netzen? Die Firewall-Regel gilt für die Profile Domäne und Privat.</p>
|
||||
"""
|
||||
|
||||
|
||||
class ClientHelpDialog(_Dialog):
|
||||
def __init__(self, parent, state, tab=0):
|
||||
super().__init__(parent, "Einrichtungshilfe: Windows-Clients",
|
||||
@@ -169,6 +240,11 @@ class ClientHelpDialog(_Dialog):
|
||||
layout.addStretch(1)
|
||||
self.tabs.addTab(test, "Verbindung testen")
|
||||
|
||||
agent = QTextBrowser()
|
||||
agent.setOpenExternalLinks(True)
|
||||
agent.setHtml(_agent_html())
|
||||
self.tabs.addTab(agent, "NetBox-Agent")
|
||||
|
||||
self.root.addWidget(self.tabs, 1)
|
||||
self.root.addWidget(button("Schließen", variant="primary", on_click=self.accept), 0, Qt.AlignRight)
|
||||
self.tabs.setCurrentIndex(tab)
|
||||
|
||||
+155
-13
@@ -1,9 +1,13 @@
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtGui import QGuiApplication
|
||||
from PySide6.QtWidgets import (
|
||||
QButtonGroup,
|
||||
QFileDialog,
|
||||
QComboBox,
|
||||
QGridLayout,
|
||||
QHBoxLayout,
|
||||
@@ -15,6 +19,7 @@ from PySide6.QtWidgets import (
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from netbox_sync.core import agent_client
|
||||
from netbox_sync.core.client_sync import clean_manufacturer
|
||||
from netbox_sync.core.clients import WINRM_HTTP_PORT, WINRM_HTTPS_PORT, os_label, os_version_label
|
||||
from netbox_sync.ui import widgets
|
||||
@@ -22,7 +27,18 @@ from netbox_sync.ui.client_help import ClientHelpDialog
|
||||
from netbox_sync.ui.credentials import ask_credentials
|
||||
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
|
||||
from netbox_sync.ui.pages import Page
|
||||
from netbox_sync.ui.widgets import Badge, Banner, Card, EmptyState, SearchField, Table, button, checkbox, label
|
||||
from netbox_sync.ui.widgets import (
|
||||
Badge,
|
||||
Banner,
|
||||
Card,
|
||||
EmptyState,
|
||||
PasswordField,
|
||||
SearchField,
|
||||
Table,
|
||||
button,
|
||||
checkbox,
|
||||
label,
|
||||
)
|
||||
|
||||
STATUS = {
|
||||
"ok": ("OK", "success"),
|
||||
@@ -55,6 +71,9 @@ def _tooltip(row):
|
||||
("RAM", f"{row['memory'] / 1024 ** 3:.0f} GB" if row.get("memory") else ""),
|
||||
("Angemeldet", row.get("user")),
|
||||
("Letzter Start", (row.get("last_boot") or "").replace("T", " ")),
|
||||
("Quelle", f"NetBox-Agent {row.get('agent_version', '')}".strip() if row.get("source") == "agent" else ""),
|
||||
("Software", f"{row['software_count']} Programme (laut Agent)" if row.get("software_count") else ""),
|
||||
("Datenträger", ", ".join(f"{disk['model']} ({disk['size'] / 1e9:.0f} GB)" for disk in row.get("disks") or [])),
|
||||
("AD", (row.get("ad") or {}).get("dn")),
|
||||
):
|
||||
if value:
|
||||
@@ -87,7 +106,8 @@ class ClientsPage(Page):
|
||||
mode_row.addWidget(label("Ziele", object_name="CardTitle"))
|
||||
self.mode_group = QButtonGroup(self)
|
||||
self.mode_buttons = {}
|
||||
for key, text in (("ad", "Active Directory"), ("hosts", "Hostnamen / IP-Bereiche")):
|
||||
for key, text in (("ad", "Active Directory"), ("hosts", "Hostnamen / IP-Bereiche"),
|
||||
("agent", "NetBox-Agent (Netzwerk-Scan)")):
|
||||
radio = QRadioButton(text)
|
||||
radio.setCursor(Qt.PointingHandCursor)
|
||||
self.mode_group.addButton(radio)
|
||||
@@ -136,12 +156,17 @@ class ClientsPage(Page):
|
||||
"PC0815.firma.local 10.0.10.0/24 10.0.20.10-50")
|
||||
self.hosts.setFixedHeight(76)
|
||||
self.mode_stack.addWidget(self.hosts)
|
||||
self.mode_stack.addWidget(self._build_agent_panel())
|
||||
# QPlainTextEdit reports a tall size hint even with a fixed height.
|
||||
self.mode_stack.setFixedHeight(max(ad_panel.sizeHint().height(), self.hosts.height()))
|
||||
self.mode_stack.setFixedHeight(max(ad_panel.sizeHint().height(), self.hosts.height(),
|
||||
self.agent_panel.sizeHint().height()))
|
||||
targets.add(self.mode_stack)
|
||||
targets.add(widgets.hline())
|
||||
self.separator = widgets.hline()
|
||||
targets.add(self.separator)
|
||||
|
||||
logon = QHBoxLayout()
|
||||
self.logon_widget = QWidget()
|
||||
logon = QHBoxLayout(self.logon_widget)
|
||||
logon.setContentsMargins(0, 0, 0, 0)
|
||||
logon.setSpacing(10)
|
||||
logon.addWidget(label("Anmeldung", object_name="CardTitle"))
|
||||
self.account_badge = Badge("", "neutral")
|
||||
@@ -161,7 +186,7 @@ class ClientsPage(Page):
|
||||
"verschlüsselt. HTTPS erfordert einen Zertifikats-Listener auf den Clients.")
|
||||
logon.addWidget(self.current_user)
|
||||
logon.addWidget(self.use_ssl)
|
||||
targets.add(logon)
|
||||
targets.add(self.logon_widget)
|
||||
self.body.addWidget(targets)
|
||||
|
||||
self.help_banner = Banner("Die Clients müssen einmalig für WinRM vorbereitet werden (Gruppenrichtlinie, "
|
||||
@@ -250,6 +275,10 @@ class ClientsPage(Page):
|
||||
self.hosts.textChanged.connect(lambda: self._save(hosts=self.hosts.toPlainText()))
|
||||
self.current_user.toggled.connect(self._current_user_toggled)
|
||||
self.use_ssl.toggled.connect(lambda value: self._save(use_ssl=value))
|
||||
self.agent_targets.textChanged.connect(lambda: self._save(agent_targets=self.agent_targets.toPlainText()))
|
||||
self.agent_port.valueChanged.connect(lambda value: self._save(agent_port=value))
|
||||
self.agent_networks.editingFinished.connect(
|
||||
lambda: self._save(agent_networks=self.agent_networks.text().strip()))
|
||||
self.search.textChanged.connect(self.proxy.set_text)
|
||||
self.status_filter.currentIndexChanged.connect(self._apply_filters)
|
||||
self.netbox_filter.currentIndexChanged.connect(self._apply_filters)
|
||||
@@ -272,7 +301,8 @@ class ClientsPage(Page):
|
||||
def load_options(self):
|
||||
options = self.state.client_options
|
||||
controls = (self.ad_server, self.ad_base, self.only_enabled, self.include_servers, self.max_age, self.hosts,
|
||||
self.current_user, self.use_ssl, *self.mode_buttons.values())
|
||||
self.current_user, self.use_ssl, self.agent_targets, self.agent_port, self.agent_networks,
|
||||
*self.mode_buttons.values())
|
||||
for widget in controls:
|
||||
widget.blockSignals(True)
|
||||
self.ad_server.setText(options.get("ad_server", ""))
|
||||
@@ -284,17 +314,125 @@ class ClientsPage(Page):
|
||||
self.hosts.setPlainText(options.get("hosts", ""))
|
||||
self.current_user.setChecked(bool(options.get("use_current_user")))
|
||||
self.use_ssl.setChecked(bool(options.get("use_ssl")))
|
||||
if self.agent_targets.toPlainText() != options.get("agent_targets", ""):
|
||||
self.agent_targets.setPlainText(options.get("agent_targets", ""))
|
||||
self.agent_port.setValue(int(options.get("agent_port") or agent_client.DEFAULT_PORT))
|
||||
self.agent_networks.setText(options.get("agent_networks", ""))
|
||||
mode = options.get("mode", "ad")
|
||||
self.mode_buttons.get(mode, self.mode_buttons["ad"]).setChecked(True)
|
||||
self.mode_stack.setCurrentIndex(0 if mode == "ad" else 1)
|
||||
for widget in controls:
|
||||
widget.blockSignals(False)
|
||||
self._show_mode(mode)
|
||||
self._update_account()
|
||||
self._update_agent_key()
|
||||
|
||||
def _set_mode(self, mode):
|
||||
self.mode_stack.setCurrentIndex(0 if mode == "ad" else 1)
|
||||
self._show_mode(mode)
|
||||
self._save(mode=mode)
|
||||
|
||||
def _show_mode(self, mode):
|
||||
self.mode_stack.setCurrentIndex({"ad": 0, "hosts": 1, "agent": 2}.get(mode, 0))
|
||||
agent = mode == "agent"
|
||||
# The agent needs no Windows logon – its shared key replaces it.
|
||||
self.logon_widget.setVisible(not agent)
|
||||
self.separator.setVisible(not agent)
|
||||
self.help_banner.set(
|
||||
"Der NetBox-Agent wird per Intune oder GPO verteilt und stellt sein Inventar verschlüsselt bereit – "
|
||||
"ohne WinRM und ohne NetBox-Zugang auf den Clients. Die Einrichtungshilfe zeigt die Verteilung."
|
||||
if agent else
|
||||
"Die Clients müssen einmalig für WinRM vorbereitet werden (Gruppenrichtlinie, Firewall). Die "
|
||||
"Einrichtungshilfe zeigt alle Schritte.")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# NetBox Windows Agent
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _build_agent_panel(self):
|
||||
self.agent_panel = QWidget()
|
||||
grid = QGridLayout(self.agent_panel)
|
||||
grid.setContentsMargins(0, 0, 0, 0)
|
||||
grid.setHorizontalSpacing(12)
|
||||
grid.setVerticalSpacing(8)
|
||||
self.agent_targets = QPlainTextEdit()
|
||||
self.agent_targets.setPlaceholderText("IP-Bereiche oder Hostnamen, z. B. 10.0.10.0/24, 10.0.20.10-50")
|
||||
self.agent_targets.setFixedHeight(52)
|
||||
grid.addWidget(label("Ziele"), 0, 0)
|
||||
grid.addWidget(self.agent_targets, 0, 1, 1, 5)
|
||||
self.agent_key = PasswordField("noch kein Schlüssel")
|
||||
self.agent_key.setReadOnly(True)
|
||||
grid.addWidget(label("Agent-Schlüssel"), 1, 0)
|
||||
grid.addWidget(self.agent_key, 1, 1)
|
||||
self.agent_key_new = button("Neu erzeugen", "refresh", on_click=self.new_agent_key,
|
||||
tooltip="Neuen Schlüssel für die Agenten dieses Kunden erzeugen")
|
||||
self.agent_key_copy = button("Kopieren", "copy", variant="ghost", on_click=self.copy_agent_key)
|
||||
self.agent_config = button("Agent-Konfiguration speichern …", "download", on_click=self.save_agent_config,
|
||||
tooltip="config.json für die Verteilung per Intune oder GPO erzeugen")
|
||||
grid.addWidget(self.agent_key_new, 1, 2)
|
||||
grid.addWidget(self.agent_key_copy, 1, 3)
|
||||
grid.addWidget(self.agent_config, 1, 4, 1, 2)
|
||||
self.agent_port = QSpinBox()
|
||||
self.agent_port.setRange(1, 65535)
|
||||
self.agent_port.setFixedWidth(100)
|
||||
self.agent_networks = QLineEdit()
|
||||
self.agent_networks.setPlaceholderText("leer = jede Adresse, z. B. 10.0.0.0/24 (Netz dieses Rechners)")
|
||||
grid.addWidget(label("Port"), 2, 0)
|
||||
grid.addWidget(self.agent_port, 2, 1, Qt.AlignLeft)
|
||||
grid.addWidget(label("Freigegebene Netze"), 2, 2)
|
||||
grid.addWidget(self.agent_networks, 2, 3, 1, 3)
|
||||
grid.setColumnStretch(1, 1)
|
||||
grid.setColumnStretch(3, 1)
|
||||
return self.agent_panel
|
||||
|
||||
def _update_agent_key(self):
|
||||
key = (self.state.profile or {}).get("agent_key", "")
|
||||
self.agent_key.setText(key)
|
||||
self.agent_key_copy.setEnabled(bool(key))
|
||||
self.agent_config.setEnabled(bool(key))
|
||||
self.agent_key_new.setText("Neu erzeugen" if key else "Schlüssel erzeugen")
|
||||
|
||||
def new_agent_key(self):
|
||||
if self.state.profile is None:
|
||||
return
|
||||
if self.state.profile.get("agent_key") and not widgets.confirm(
|
||||
self.window, "Neuen Schlüssel erzeugen?",
|
||||
"Bereits verteilte Agenten lassen sich danach erst wieder abfragen, wenn sie die neue "
|
||||
"Konfiguration erhalten haben.", "Neu erzeugen", destructive=True):
|
||||
return
|
||||
self.state.edit_profile(agent_key=agent_client.new_scan_key())
|
||||
self._update_agent_key()
|
||||
self.window.toast("Neuer Agent-Schlüssel erzeugt – Konfiguration neu verteilen.", "info")
|
||||
|
||||
def copy_agent_key(self):
|
||||
QGuiApplication.clipboard().setText(self.agent_key.text())
|
||||
self.window.toast("Agent-Schlüssel kopiert.", "info")
|
||||
|
||||
def save_agent_config(self):
|
||||
key = (self.state.profile or {}).get("agent_key", "")
|
||||
if not key:
|
||||
return
|
||||
networks = [part.strip() for part in self.agent_networks.text().replace(";", ",").split(",") if part.strip()]
|
||||
for network in networks:
|
||||
try:
|
||||
ipaddress.ip_network(network, strict=False)
|
||||
except ValueError:
|
||||
widgets.message(self.window, "Freigegebene Netze prüfen",
|
||||
f"„{network}“ ist kein Netz in CIDR-Schreibweise (z. B. 10.0.0.0/24).", "warning")
|
||||
return
|
||||
path, _filter = QFileDialog.getSaveFileName(self.window, "Agent-Konfiguration speichern", "config.json",
|
||||
"JSON (*.json)")
|
||||
if not path:
|
||||
return
|
||||
data = agent_client.agent_config(key, self.agent_port.value(),
|
||||
[str(ipaddress.ip_network(n, strict=False)) for n in networks])
|
||||
try:
|
||||
with open(path, "w", encoding="utf-8") as stream:
|
||||
json.dump(data, stream, indent=2)
|
||||
except OSError as error:
|
||||
widgets.error(self.window, "Speichern fehlgeschlagen", str(error))
|
||||
return
|
||||
self.window.toast("config.json gespeichert – zusammen mit agent.exe per Intune oder GPO verteilen.",
|
||||
"success")
|
||||
|
||||
def _current_user_toggled(self, value):
|
||||
self._save(use_current_user=value)
|
||||
self._update_account()
|
||||
@@ -416,12 +554,14 @@ class ClientsPage(Page):
|
||||
return
|
||||
self.ad_server.editingFinished.emit()
|
||||
self.ad_base.editingFinished.emit()
|
||||
if self._ensure_logon():
|
||||
if self.state.client_options.get("mode") == "agent":
|
||||
self.actions.scan_clients()
|
||||
elif self._ensure_logon():
|
||||
self.actions.scan_clients()
|
||||
|
||||
def rescan(self):
|
||||
rows = self.model.checked_rows()
|
||||
if rows and self._ensure_logon():
|
||||
if rows and (self.state.client_options.get("mode") == "agent" or self._ensure_logon()):
|
||||
self.actions.scan_clients(rows)
|
||||
|
||||
def load_file(self):
|
||||
@@ -436,5 +576,7 @@ class ClientsPage(Page):
|
||||
else:
|
||||
self.actions.sync_clients(rows)
|
||||
|
||||
def show_help(self, tab=0):
|
||||
ClientHelpDialog(self.window, self.state, tab if isinstance(tab, int) else 0).exec()
|
||||
def show_help(self, tab=None):
|
||||
if tab is None or isinstance(tab, bool): # button signals pass "checked"
|
||||
tab = 3 if self.state.client_options.get("mode") == "agent" else 0
|
||||
ClientHelpDialog(self.window, self.state, tab).exec()
|
||||
Reference in new issue
Block a user