Compare commits

...
10 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 8f20bcf795 chore: release 4.8.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 16:32:11 +01:00
MrBlakeandClaude Opus 5.5 1c0a8168ed feat: read-only network scanner with automatic NetBox comparison
- New "Network scanner" page: scan IP ranges, networks and host names in
  parallel; hosts are found by ICMP (Windows API, no admin rights, no
  ping.exe), ARP and TCP ports, so hosts blocking ping show up as well
- Name from reverse DNS and NetBIOS, MAC address, open services from a
  configurable port list and response time; results stream in while scanning
- Every address is compared with NetBox automatically (one query per /24):
  NetBox object and DNS name per IP with match / name differs / not in
  NetBox / in NetBox but not reachable; nothing is written
- Double click and context menu open HTTP(S), Remote Desktop, shares or the
  IP address in NetBox

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 16:32:10 +01:00
MrBlakeandClaude Opus 5.5 8464895b06 chore: release 4.7.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 15:36:18 +01:00
MrBlakeandClaude Opus 5.5 e499d854a9 feat: tenant group VRFs for switch networks, remembered network decisions, in-app updates
- Networks tab offers the VRFs of the switch's tenant group and finds
  existing prefixes there; network decisions are stored per profile and
  shared by all switches (per-switch choices are migrated)
- Decided networks and VLANs sit in a collapsed, editable section
- Check the Gitea releases on start (or on demand in the settings); after
  confirmation the installer runs silently and restarts the application, the
  portable EXE swaps itself; a version can be skipped
- Installer restarts the application after a silent update

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 15:36:17 +01:00
MrBlakeandClaude Opus 5.5 3db5e83f0a chore: release 4.6.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 14:33:14 +01:00
MrBlakeandClaude Opus 5.5 3df4e6a9fc feat: ignore switch VLANs and remember VLAN decisions per profile
- New "ignore" choice: the VLAN is neither created nor assigned and is left
  out of interface labels and the VLAN column
- VLAN decisions are stored once per profile and shared by all switches;
  per-switch decisions from 4.5.0 are migrated on load
- Review dialog shows one row per VID; only open VLANs are listed, stored and
  unambiguous ones sit in a collapsed, editable section

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 14:33:14 +01:00
MrBlakeandClaude Opus 5.5 f729473b64 chore: release 4.5.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 14:18:10 +01:00
MrBlakeandClaude Opus 5.5 29d3724a7f feat: map switch VLANs across the tenant group, custom name and tenant for new VLANs
- Match switch VLANs to NetBox VLANs of the switch's tenant group by VID;
  own tenant, site and similar names decide between several candidates
- Review dialog: choose the NetBox VLAN per VID, skip it or create it with a
  custom name and a tenant of the tenant group
- Never create a VLAN twice when "create new" stays stored in the profile

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 14:18:09 +01:00
MrBlakeandClaude Opus 5.5 535a5e9699 chore: release 4.4.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 13:46:43 +01:00
MrBlakeandClaude Opus 5.5 83787142d3 feat: review missing prefixes, VRFs and VLANs; enforce tenants
- Review dialog gains "Networks" and "VLANs" tabs: VRF per network (global,
  tenant VRF or new VRF), missing prefixes and VLANs are only created when
  ticked; existing tenant VLANs are assigned to ports (802.1Q mode,
  untagged/tagged)
- Read VLAN names from the configuration (Comware now reads the full
  current-configuration)
- Switch IP addresses follow the chosen VRF instead of always global
- Tenant required: switches without tenant are refused; IPs, prefixes, VRFs,
  VLANs and cables get the switch's tenant; client import requires a tenant
  and client IP addresses now get it too
- Fix clipped combo boxes in the review dialog tables

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 13:46:42 +01:00
21 changed files with 1971 additions and 37 deletions

No files matched your search

+36 -1
View File
@@ -21,7 +21,11 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
- Light and dark theme (optionally following Windows)
- Log with filter, search and export, plus a rotating log file under
`%APPDATA%\NetBox VM Import\logs`
- Keyboard shortcuts: `Ctrl+1…8` navigation, `F5` reload/read, `Ctrl+F` search
- Keyboard shortcuts: `Ctrl+1…9` navigation, `F5` reload/read, `Ctrl+F` search
- Updates from the Gitea releases: checked on start (can be switched off in the
settings, or run on demand); after confirmation the installed version runs the
new setup silently and the portable EXE replaces itself, then the application
restarts. A version can be skipped
### Virtual machines
@@ -62,10 +66,41 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
- **Mapping review** before the preview: non-obvious port mappings and every
LLDP/CDP neighbour can be corrected; a neighbour can be assigned manually to
any device of the switch's tenant group. Choices are stored in the profile
- Networks and VLANs in the same review: per network the VRF (global, a VRF of
the tenant group or a new one) and whether a missing prefix is created. Network
decisions are stored per profile like the VLAN decisions; networks whose
prefix exists or that were decided before sit in a collapsed, editable section
- VLAN mapping: switch VLANs are matched to NetBox VLANs of the switch's tenant
group by VID (own tenant, site and similar names decide between several);
each VLAN can be mapped manually, skipped or created with a name and a tenant
of the tenant group of your choice (pre-filled from the switch configuration
and the switch's tenant). VLANs can also be **ignored** on all switches –
they are neither created nor assigned and are left out of the labels. VLAN
decisions are stored per profile (shared by all its switches); only VLANs
that still need a decision are shown, stored and unambiguous ones are in a
collapsed section that can be expanded for editing. Mapped VLANs are assigned
to the ports (802.1Q mode, untagged/tagged)
- Tenant required: a switch without tenant in NetBox is refused; every created
IP address, prefix, VRF, VLAN and cable gets the switch's tenant
- Cables from LLDP/CDP, also with FQDN system names or via the management IP
- The switch configuration is only changed when "Enable LLDP if needed" is
explicitly switched on
### Network scanner (read only)
- Scans IP ranges, networks and host names (`192.0.2.1-254`, `192.0.2.0/24`,
up to 4096 addresses) in parallel; "own network" fills in the networks of
this computer
- Finds hosts by ping (Windows ICMP API, no administrator rights), ARP in the
local subnet and TCP ports – hosts that block ping are found as well
- Shows name (reverse DNS and NetBIOS, with workgroup/domain), MAC address,
open services from a configurable port list and response time
- Compares every address with NetBox automatically: NetBox object (device or VM)
and DNS name next to each IP, with the state "matches", "name differs", "not
in NetBox" or "in NetBox, not reachable"; nothing is written to NetBox
- Filters for reachable hosts and deviations; double click or context menu opens
HTTP/HTTPS, Remote Desktop, file shares or the IP address in NetBox
### Windows clients (agentless via WMI/CIM over WinRM)
- Targets from Active Directory (optional search OU, enabled accounts only,
+3 -1
View File
@@ -3,7 +3,7 @@
#define AppName "NetBox Synchronizer"
#ifndef AppVersion
#define AppVersion "4.3.0"
#define AppVersion "4.8.0"
#endif
#define AppPublisher "Louis-Alexander Kerst"
#define AppExeName "NetBoxSynchronizer.exe"
@@ -66,6 +66,8 @@ Name: "{autodesktop}\{#AppName}"; Filename: "{app}\{#AppExeName}"; AppUserModelI
[Run]
Filename: "{app}\{#AppExeName}"; Description: "{cm:LaunchProgram,{#AppName}}"; Flags: nowait postinstall skipifsilent
; Restart after an update started from within the application (silent mode).
Filename: "{app}\{#AppExeName}"; Flags: nowait; Check: WizardSilent
[Code]
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
+1 -1
View File
@@ -1,7 +1,7 @@
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
APP_NAME = "NetBox Synchronizer"
APP_VERSION = "4.3.0"
APP_VERSION = "4.8.0"
APP_PUBLISHER = "Louis-Alexander Kerst"
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
+5 -4
View File
@@ -231,12 +231,12 @@ class ClientSyncEngine:
if not dry_run:
device.update(updates)
if interfaces:
changes.extend(self._sync_interfaces(device, client, dry_run, report))
changes.extend(self._sync_interfaces(device, client, tenant_id, dry_run, report))
if not changes:
report["devices_unchanged"] += 1
return changes
def _sync_interfaces(self, device, client, dry_run, report):
def _sync_interfaces(self, device, client, tenant_id, dry_run, report):
changes = []
existing = {str(item.name).casefold(): item for item in self.nb.dcim.interfaces.filter(device_id=device.id)}
primary = None
@@ -257,7 +257,7 @@ class ClientSyncEngine:
if record is not None and mac and not dry_run:
assign_mac(self.nb, record, mac, "dcim.interface")
for address in interface.get("ips", []):
ip, change = self._sync_ip(address, record, interface.get("dhcp"), dry_run, report)
ip, change = self._sync_ip(address, record, interface.get("dhcp"), tenant_id, dry_run, report)
if change:
changes.append(change)
if ip is not None and primary is None and ":" not in address and interface.get("gateway"):
@@ -266,7 +266,7 @@ class ClientSyncEngine:
device.update({"primary_ip4": primary.id})
return changes
def _sync_ip(self, address, interface, dhcp, dry_run, report):
def _sync_ip(self, address, interface, dhcp, tenant_id, dry_run, report):
matches = [ip for ip in self.nb.ipam.ip_addresses.filter(address=address.split("/")[0])
if related_id(ip, "vrf") is None]
if not matches:
@@ -276,6 +276,7 @@ class ClientSyncEngine:
ip = self.nb.ipam.ip_addresses.create({
"address": address, "status": "dhcp" if dhcp else "active",
"assigned_object_type": "dcim.interface", "assigned_object_id": interface.id,
**({"tenant": tenant_id} if tenant_id else {}),
})
return ip, f"IP-Adresse {address} anlegen"
ip = matches[0]
+21
View File
@@ -21,6 +21,10 @@ DEFAULT_SETTINGS = {
"create_cables": True,
"offline_mode": False, # collect and export to JSON without NetBox
"parallel_wmi": 8, # concurrent WinRM sessions for client scans
"auto_update_check": True, # look for a newer Gitea release on start
"skipped_version": "", # release the user chose to skip
"scanner_targets": "", # last IP ranges of the network scanner
"scanner_ports": "", # empty = default port list
}
log = logging.getLogger(__name__)
@@ -116,6 +120,10 @@ def empty_profile(name):
# Remembered assignment "<source id>:<hypervisor cluster>" -> NetBox cluster name.
"cluster_map": {},
"host_map": {},
# Switch VLAN decisions for all switches: "<vid>" -> {"action": "map"|"new"|"skip"|"ignore", ...}.
"vlan_map": {},
# Switch network decisions: "<network>" -> {"vrf_id", "vrf_name" (new VRF), "create": prefix}.
"network_map": {},
# Windows client scan: targets and options, never a password.
"clients": dict(DEFAULT_CLIENT_OPTIONS),
}
@@ -164,6 +172,8 @@ class ProfileStore:
"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", {})),
"vlan_map": dict(record.get("vlan_map", {})),
"network_map": dict(record.get("network_map", {})),
"clients": {**DEFAULT_CLIENT_OPTIONS, **{key: value for key, value in record.get("clients", {}).items()
if key in DEFAULT_CLIENT_OPTIONS}},
})
@@ -171,6 +181,15 @@ class ProfileStore:
profile["sources"].append(self._decrypt_record(source, f"{name}: {source.get('name', 'Quelle')}"))
for switch in record.get("switches", []):
profile["switches"].append(self._decrypt_record(switch, f"{name}: {switch.get('name', 'Switch')}"))
# Migration from 4.5/4.6: VLAN and network decisions were stored per switch.
for switch in profile["switches"]:
for vid, choice in (switch.pop("vlan_map", None) or {}).items():
profile["vlan_map"].setdefault(vid, choice)
switch.pop("create_vlans", None)
approved = switch.pop("create_prefixes", None) or []
for network, vrf_name in (switch.pop("network_vrfs", None) or {}).items():
profile["network_map"].setdefault(network, {"vrf_id": None, "vrf_name": vrf_name or "",
"create": network in approved})
# Migration from v2: one VMware source embedded in each profile.
if not profile["sources"] and record.get("esxi_host"):
@@ -228,6 +247,8 @@ class ProfileStore:
"switches": [self._encrypt_record(switch) for switch in profile.get("switches", [])],
"cluster_map": dict(profile.get("cluster_map", {})),
"host_map": dict(profile.get("host_map", {})),
"vlan_map": dict(profile.get("vlan_map", {})),
"network_map": dict(profile.get("network_map", {})),
"clients": dict(profile.get("clients", DEFAULT_CLIENT_OPTIONS)),
})
+329
View File
@@ -0,0 +1,329 @@
"""Network scanner: find hosts in IP ranges and compare them with NetBox (read only).
Reachability uses the Windows ICMP API (no administrator rights, no ping.exe),
ARP for the local subnet and TCP ports, so hosts that block ICMP are found as
well. Names come from reverse DNS and NetBIOS. Nothing is written to NetBox.
"""
import ctypes
import ipaddress
import re
import socket
import struct
import sys
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from netbox_sync.core.netbox import related_id
SERVICES = {
21: "FTP", 22: "SSH", 23: "Telnet", 25: "SMTP", 53: "DNS", 80: "HTTP", 110: "POP3", 135: "RPC",
139: "NetBIOS", 143: "IMAP", 161: "SNMP", 389: "LDAP", 443: "HTTPS", 445: "SMB", 515: "LPD", 631: "IPP",
636: "LDAPS", 993: "IMAPS", 1433: "MSSQL", 3306: "MySQL", 3389: "RDP", 5432: "PostgreSQL", 5900: "VNC",
5985: "WinRM", 5986: "WinRM-HTTPS", 8006: "Proxmox", 8080: "HTTP-Alt", 8443: "HTTPS-Alt", 9100: "Druck",
}
DEFAULT_PORTS = "21-23,25,53,80,135,139,443,445,3389,5900,5985,8006,8080,8443,9100"
# Probed on hosts that do not answer ping, to find hosts behind a firewall.
QUICK_PORTS = (445, 3389, 80, 443, 22)
MAX_HOSTS = 4096
class ScanError(ValueError):
pass
def parse_ports(text):
"""``"21-23,80, 443"`` → sorted unique port numbers."""
ports = set()
for part in re.split(r"[\s,;]+", (text or "").strip()):
if not part:
continue
match = re.fullmatch(r"(\d+)(?:-(\d+))?", part)
if not match:
raise ScanError(f"Ungültige Port-Angabe: {part}")
start, end = int(match.group(1)), int(match.group(2) or match.group(1))
if not 1 <= start <= end <= 65535:
raise ScanError(f"Ungültiger Port-Bereich: {part}")
ports.update(range(start, end + 1))
if len(ports) > 1024:
raise ScanError("Bitte höchstens 1024 Ports angeben.")
return sorted(ports)
def expand_ips(text):
"""IPv4 addresses from ranges, networks and names (names are resolved)."""
from netbox_sync.core.clients import ClientScanError, expand_targets
try:
targets = expand_targets(text)
except ClientScanError as error:
raise ScanError(str(error)) from error
result = []
for target in targets:
try:
address = ipaddress.ip_address(target)
except ValueError:
try:
address = ipaddress.ip_address(socket.gethostbyname(target))
except (OSError, ValueError) as error:
raise ScanError(f"Name nicht auflösbar: {target}") from error
if address.version != 4:
raise ScanError(f"Nur IPv4 wird gescannt: {target}")
if str(address) not in result:
result.append(str(address))
if not result:
raise ScanError("Bitte IP-Adressen, Bereiche (192.0.2.1-254) oder Netze (192.0.2.0/24) angeben.")
if len(result) > MAX_HOSTS:
raise ScanError(f"Zu viele Adressen ({len(result)}) – höchstens {MAX_HOSTS} pro Scan.")
return result
def local_networks():
"""IPv4 /24 networks of this computer (for the "own network" button)."""
addresses = set()
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as probe:
probe.connect(("192.0.2.1", 9)) # no packet is sent for UDP connect
addresses.add(probe.getsockname()[0])
except OSError:
pass
try:
addresses.update(info[4][0] for info in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET))
except OSError:
pass
networks = []
for address in sorted(addresses):
ip = ipaddress.ip_address(address)
if not (ip.is_loopback or ip.is_link_local):
network = str(ipaddress.ip_network(f"{address}/24", strict=False))
if network not in networks:
networks.append(network)
return networks
# --------------------------------------------------------------------------
# Probes
# --------------------------------------------------------------------------
def _inet_addr(ip):
return struct.unpack("<I", socket.inet_aton(ip))[0]
if sys.platform == "win32":
class _IpOptions(ctypes.Structure):
_fields_ = [("Ttl", ctypes.c_ubyte), ("Tos", ctypes.c_ubyte), ("Flags", ctypes.c_ubyte),
("OptionsSize", ctypes.c_ubyte), ("OptionsData", ctypes.c_void_p)]
class _EchoReply(ctypes.Structure):
_fields_ = [("Address", ctypes.c_ulong), ("Status", ctypes.c_ulong), ("RoundTripTime", ctypes.c_ulong),
("DataSize", ctypes.c_ushort), ("Reserved", ctypes.c_ushort), ("Data", ctypes.c_void_p),
("Options", _IpOptions)]
_iphlpapi = ctypes.windll.iphlpapi
_iphlpapi.IcmpCreateFile.restype = ctypes.c_void_p
_iphlpapi.IcmpCloseHandle.argtypes = [ctypes.c_void_p]
_iphlpapi.IcmpSendEcho.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p, ctypes.c_ushort,
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong]
_iphlpapi.SendARP.argtypes = [ctypes.c_ulong, ctypes.c_ulong, ctypes.c_void_p, ctypes.POINTER(ctypes.c_ulong)]
def ping(ip, timeout_ms=800):
"""Round-trip time in ms, or ``None`` without answer."""
if sys.platform != "win32":
return None
handle = _iphlpapi.IcmpCreateFile()
if not handle or handle == ctypes.c_void_p(-1).value:
return None
try:
payload = b"netbox-sync-scan"
buffer = ctypes.create_string_buffer(ctypes.sizeof(_EchoReply) + len(payload) + 8)
count = _iphlpapi.IcmpSendEcho(handle, _inet_addr(ip), payload, len(payload), None, buffer,
ctypes.sizeof(buffer), timeout_ms)
if count:
reply = _EchoReply.from_buffer(buffer)
if reply.Status == 0:
return int(reply.RoundTripTime)
return None
finally:
_iphlpapi.IcmpCloseHandle(handle)
def arp_mac(ip):
"""MAC address via ARP – only for hosts in a directly connected subnet."""
if sys.platform != "win32":
return None
mac = (ctypes.c_ubyte * 8)()
length = ctypes.c_ulong(8)
if _iphlpapi.SendARP(_inet_addr(ip), 0, mac, ctypes.byref(length)) != 0 or length.value < 6:
return None
value = ":".join(f"{byte:02X}" for byte in mac[:6])
return None if value == "00:00:00:00:00:00" else value
def reverse_dns(ip):
try:
return socket.gethostbyaddr(ip)[0]
except (OSError, UnicodeError):
return ""
_NBSTAT_QUERY = (b"\x13\x37\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00"
b"\x20CKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\x00\x00\x21\x00\x01")
def parse_nbstat(data):
"""``(computer name, workgroup, MAC)`` from a NetBIOS node status answer."""
if len(data) < 57:
return "", "", None
count = data[56]
offset = 57
name = group = ""
for _index in range(count):
entry = data[offset:offset + 18]
if len(entry) < 18:
break
text = entry[:15].decode("latin-1").strip()
suffix, flags = entry[15], struct.unpack(">H", entry[16:18])[0]
if suffix == 0x00 and not flags & 0x8000 and not name:
name = text
elif suffix == 0x00 and flags & 0x8000 and not group:
group = text
offset += 18
mac_bytes = data[offset:offset + 6]
mac = ":".join(f"{byte:02X}" for byte in mac_bytes) if len(mac_bytes) == 6 and any(mac_bytes) else None
return name, group, mac
def netbios(ip, timeout=0.8):
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.settimeout(timeout)
sock.sendto(_NBSTAT_QUERY, (ip, 137))
data, _address = sock.recvfrom(2048)
except OSError:
return "", "", None
return parse_nbstat(data)
def tcp_open(ip, port, timeout=0.6):
try:
with socket.create_connection((ip, port), timeout=timeout):
return True
except OSError:
return False
def scan_host(ip, ports, timeout=0.6):
"""Probe one address. ``alive`` is false when nothing answered."""
started = time.monotonic()
rtt = ping(ip, int(timeout * 1000) + 200)
mac = arp_mac(ip)
open_ports = []
alive = rtt is not None or mac is not None
if not alive:
# Windows hosts often block ping; a few typical ports reveal them anyway.
for port in QUICK_PORTS:
if tcp_open(ip, port, timeout):
open_ports.append(port)
alive = True
break
if not alive:
return {"ip": ip, "alive": False}
with ThreadPoolExecutor(max_workers=min(16, max(1, len(ports)))) as pool:
results = pool.map(lambda port: (port, tcp_open(ip, port, timeout)), [p for p in ports if p not in open_ports])
open_ports += [port for port, is_open in results if is_open]
name, workgroup, nb_mac = netbios(ip)
return {
"ip": ip, "alive": True, "rtt": rtt, "mac": mac or nb_mac, "dns_name": reverse_dns(ip),
"netbios_name": name, "workgroup": workgroup,
"ports": [{"port": port, "service": SERVICES.get(port, "")} for port in sorted(open_ports)],
"duration": round(time.monotonic() - started, 2),
}
def scan(ips, ports, on_result, cancelled=lambda: False, workers=64, timeout=0.6):
"""Scan ``ips`` in parallel; ``on_result`` gets every host as soon as it is done."""
with ThreadPoolExecutor(max_workers=min(workers, len(ips))) as pool:
futures = {pool.submit(scan_host, ip, ports, timeout): ip for ip in ips}
for future in as_completed(futures):
if cancelled():
for pending in futures:
pending.cancel()
break
try:
on_result(future.result())
except Exception as error: # noqa: BLE001 - one host must not stop the scan
on_result({"ip": futures[future], "alive": False, "error": str(error)})
# --------------------------------------------------------------------------
# NetBox comparison (read only)
# --------------------------------------------------------------------------
def _assigned_name(record):
obj = getattr(record, "assigned_object", None)
if obj is None:
return "", ""
for attribute, kind in (("device", "Gerät"), ("virtual_machine", "VM")):
parent = getattr(obj, attribute, None)
if parent is not None:
return getattr(parent, "name", "") or "", kind
return getattr(obj, "name", "") or "", ""
def netbox_lookup(nb, ips):
"""``{ip: [entry, …]}`` for all NetBox IP addresses of the scanned hosts.
Queries one ``parent`` filter per /24 instead of one request per host.
"""
wanted = set(ips)
blocks = sorted({str(ipaddress.ip_network(f"{ip}/24", strict=False)) for ip in ips})
found = {}
for block in blocks:
for record in nb.ipam.ip_addresses.filter(parent=block):
host = str(record.address).split("/")[0]
if host not in wanted:
continue
name, kind = _assigned_name(record)
vrf = getattr(getattr(record, "vrf", None), "name", None)
status = getattr(record, "status", None)
found.setdefault(host, []).append({
"id": record.id,
"dns_name": getattr(record, "dns_name", "") or "",
"object": name, "object_kind": kind,
"vrf": vrf or "", "tenant_id": related_id(record, "tenant"),
"tenant": getattr(getattr(record, "tenant", None), "name", "") or "",
"status": getattr(status, "label", None) or getattr(status, "value", None) or str(status or ""),
"description": getattr(record, "description", "") or "",
"url": getattr(record, "display_url", None) or "",
})
return found
def _short(name):
return (name or "").split(".")[0].strip().casefold()
def compare(host, entries):
"""Comparison state of one scanned host with its NetBox entries."""
alive = host.get("alive")
if not entries:
return "missing" if alive else "unknown"
if not alive:
return "offline"
names = {_short(host.get("dns_name")), _short(host.get("netbios_name"))} - {""}
if not names:
return "match" # nothing to compare against – the address is documented
for entry in entries:
if names & ({_short(entry["dns_name"]), _short(entry["object"])} - {""}):
return "match"
return "differs"
COMPARE_TEXT = {
"match": "stimmt überein",
"differs": "Name abweichend",
"missing": "nicht in NetBox",
"offline": "in NetBox, nicht erreichbar",
"unknown": "",
"pending": "…",
}
+368 -15
View File
@@ -34,7 +34,7 @@ IP_COMMANDS = {
CONFIG_COMMANDS = {
"aruba_cx": "show running-config",
"aruba_aos": "show running-config",
"hpe_comware": "display current-configuration interface",
"hpe_comware": "display current-configuration",
}
LLDP_CONTROL = {
@@ -732,6 +732,17 @@ def _parse_comware_vlans(config):
return result
def parse_vlan_names(config):
"""``{VLAN ID: name}`` from ``vlan <id>`` blocks (same syntax on all platforms)."""
names = {}
for match, body in _config_blocks(config or "", re.compile(r"^vlan\s+(\d+)\s*$", re.I)):
for line in body:
name = re.match(r'^name\s+"?(.*?)"?\s*$', line, flags=re.I)
if name and name.group(1):
names[int(match.group(1))] = name.group(1)
return names
def parse_vlans(config, platform):
"""VLAN membership per port, keyed by :func:`interface_key`."""
if not config:
@@ -810,6 +821,7 @@ def build_snapshot(outputs, platform):
"raw": {**{key: value for key, value in outputs.items() if key != "config"},
**({"vlan_config": _vlan_config_excerpt(outputs["config"])} if outputs.get("config") else {})},
"vlans_read": bool(outputs.get("config")),
"vlan_names": parse_vlan_names(outputs.get("config", "")),
"lldp_disabled": outputs.get("lldp_disabled", False),
"lldp_enabled_automatically": outputs.get("lldp_enabled_automatically", False),
"discovered_at": time.time(),
@@ -1028,9 +1040,153 @@ def candidate_devices(nb, device):
return scope, sorted(rows, key=lambda row: row["name"].casefold())
def _require_tenant(device):
tenant_id = related_id(device, "tenant")
if tenant_id:
return tenant_id, None
return None, (f"NetBox-Gerät „{device.name}“ hat keinen Mandanten – bitte zuerst in NetBox einen Mandanten "
"zuweisen. Ohne Mandant werden keine Objekte angelegt.")
def snapshot_networks(snapshot):
"""Networks of all interface IP addresses (host routes are left out)."""
networks = set()
for interface in snapshot["interfaces"]:
for address in interface.get("ip_addresses", []):
network = ipaddress.ip_interface(address).network
if network.prefixlen < network.max_prefixlen:
networks.add(network)
return [str(network) for network in sorted(networks, key=lambda item: (item.version, item))]
def snapshot_vlan_ids(snapshot):
vids = set()
for interface in snapshot["interfaces"]:
vlans = interface.get("vlans") or {}
vids.update(vlans.get("untagged", []))
vids.update(vlans.get("tagged", []))
return sorted(vids)
VLAN_METHODS = {
"vid": "gleiche VID",
"name": "VID + Name",
"ambiguous": "mehrdeutig",
"manual": "manuell",
"new": "fehlt",
"skip": "nicht zuordnen",
"ignore": "ignoriert",
}
def ignored_vlans(vlan_map):
"""VLAN IDs the user chose to ignore on all switches of the profile."""
return {int(vid) for vid, choice in (vlan_map or {}).items() if (choice or {}).get("action") == "ignore"}
def without_vlans(vlans, ignored):
"""Port VLAN membership without ignored VLANs (``None`` stays ``None``)."""
if not vlans or not ignored:
return vlans
return dict(vlans, untagged=[vid for vid in vlans.get("untagged", []) if vid not in ignored],
tagged=[vid for vid in vlans.get("tagged", []) if vid not in ignored])
def candidate_vlans(nb, tenant_id):
"""VLANs of the switch's tenant group (or tenant) – a VLAN may belong to a
sibling tenant, e.g. a school network documented under its own tenant."""
tenant = nb.tenancy.tenants.get(tenant_id)
group_id = related_id(tenant, "group") if tenant else None
found = {}
sources = [nb.ipam.vlans.filter(tenant_id=tenant_id)]
if group_id:
sources.append(nb.ipam.vlans.filter(tenant_group_id=group_id))
for source in sources:
for vlan in source:
found[vlan.id] = vlan
return list(found.values())
def candidate_tenants(nb, tenant_id):
"""Tenants a new VLAN may get: the tenant group of the switch's tenant."""
tenant = nb.tenancy.tenants.get(tenant_id)
group_id = related_id(tenant, "group") if tenant else None
tenants = {tenant_id: getattr(tenant, "name", None) or str(tenant_id)}
if group_id:
tenants.update({item.id: item.name for item in nb.tenancy.tenants.filter(group_id=group_id)})
return sorted(({"id": key, "name": value} for key, value in tenants.items()), key=lambda row: row["name"].casefold())
def _name_tokens(text):
return set(re.findall(r"[a-z]+|\d+", (text or "").casefold()))
def vlan_choice_label(vlan):
owner = getattr(getattr(vlan, "tenant", None), "name", None) or getattr(getattr(vlan, "group", None), "name", None)
return f"{vlan.vid} – {vlan.name}" + (f" ({owner})" if owner else "")
def match_vlans(vids, names, vlans, tenant_id, site_id, manual=None):
"""Assign NetBox VLANs to switch VLAN IDs.
Candidates need the same VID. With several, the own tenant, the switch's
site and similar names (``Server_LEO`` ↔ ``Leo Server``) decide.
``manual`` is ``{str(vid): {"action": "map"|"new"|"skip", "id", "name"}}``.
Returns ``{vid: (record or None, method, name for a new VLAN)}``.
"""
manual = manual or {}
by_vid, by_id = {}, {vlan.id: vlan for vlan in vlans}
for vlan in vlans:
by_vid.setdefault(vlan.vid, []).append(vlan)
result = {}
for vid in vids:
switch_name = names.get(vid) or f"VLAN{vid}"
choice = manual.get(str(vid)) or {}
if choice.get("action") == "new":
name = (choice.get("name") or switch_name)[:64]
# Created by an earlier run – use it instead of creating it again.
created = next((vlan for vlan in by_vid.get(vid, []) if vlan.name.casefold() == name.casefold()), None)
result[vid] = (created, "manual", name) if created else (None, "new", name)
continue
if choice.get("action") in ("skip", "ignore"):
result[vid] = (None, choice["action"], switch_name)
continue
if choice.get("action") == "map" and choice.get("id") in by_id:
result[vid] = (by_id[choice["id"]], "manual", switch_name)
continue
candidates = by_vid.get(vid, [])
if not candidates:
result[vid] = (None, "new", switch_name)
continue
tokens = _name_tokens(switch_name)
def score(vlan):
other = _name_tokens(vlan.name)
similarity = len(tokens & other) / len(tokens | other) if tokens | other else 0
return ((related_id(vlan, "tenant") == tenant_id) * 4 + (related_id(vlan, "site") == site_id) * 2
+ similarity * 3)
ranked = sorted(candidates, key=score, reverse=True)
if len(ranked) == 1:
method = "vid"
else:
method = "name" if score(ranked[0]) > score(ranked[1]) else "ambiguous"
result[vid] = (ranked[0], method, switch_name)
return result
def _switch_vlan_matches(nb, config, snapshot, tenant_id, site_id):
names = {int(key): value for key, value in (snapshot.get("vlan_names") or {}).items()}
vlans = candidate_vlans(nb, tenant_id)
return vlans, match_vlans(snapshot_vlan_ids(snapshot), names, vlans, tenant_id, site_id, config.get("vlan_map"))
def plan_switch_sync(nb, config, snapshot):
"""Proposed interface mapping and neighbor devices for the review dialog."""
"""Proposals for the review dialog: interface mapping, neighbor devices,
networks (VRF and missing prefixes) and missing VLANs."""
device, error = _resolve_device(nb, config)
if not error:
tenant_id, error = _require_tenant(device)
if error:
return {"error": error}
records = list(nb.dcim.interfaces.filter(device_id=device.id))
@@ -1053,12 +1209,50 @@ def plan_switch_sync(nb, config, snapshot):
known.add(remote.id)
neighbors.append(dict(neighbor, device_id=device_id, method=method))
devices.sort(key=lambda row: row["name"].casefold())
vrf_records = candidate_vrfs(nb, tenant_id)
vrfs = [{"id": vrf.id, "label": vrf_choice_label(vrf)}
for vrf in sorted(vrf_records, key=lambda item: (item.name or "").casefold())]
networks = []
for network in snapshot_networks(snapshot):
# Where the prefix already exists: 0 = global, otherwise a VRF of the tenant group.
existing = sorted({related_id(prefix, "vrf") or 0 for prefix in nb.ipam.prefixes.filter(prefix=network)}
& ({0} | {vrf.id for vrf in vrf_records}), key=lambda value: (value == 0, value))
choice = _network_choice(config, network)
if choice is not None:
vrf_id = _resolve_vrf_choice(choice, vrf_records, tenant_id)
vrf_id = vrf_id if isinstance(vrf_id, int) else 0
networks.append({"network": network, "vrf_id": vrf_id,
"vrf_name": choice.get("vrf_name") if not vrf_id else "",
"existing": existing, "create": bool(choice.get("create")), "stored": True})
else:
networks.append({"network": network, "vrf_id": existing[0] if existing else 0, "vrf_name": "",
"existing": existing, "create": True, "stored": False})
names = {int(key): value for key, value in (snapshot.get("vlan_names") or {}).items()}
candidates, vlan_matches = _switch_vlan_matches(nb, config, snapshot, tenant_id, related_id(device, "site"))
tenants = candidate_tenants(nb, tenant_id)
allowed = {row["id"] for row in tenants}
vlan_map = config.get("vlan_map") or {}
vlans = []
for vid, (record, method, new_name) in vlan_matches.items():
new_tenant = (vlan_map.get(str(vid)) or {}).get("tenant")
vlans.append({
"vid": vid, "name": names.get(vid) or f"VLAN{vid}", "method": method, "new_name": new_name,
"stored": str(vid) in vlan_map,
"new_tenant": new_tenant if new_tenant in allowed else tenant_id,
"netbox_id": record.id if record else None,
"candidates": [{"id": vlan.id, "label": vlan_choice_label(vlan)}
for vlan in sorted(candidates, key=lambda item: (item.name or "").casefold())
if vlan.vid == vid],
})
return {
"error": None,
"device": {"id": device.id, "name": device.name},
"interfaces": [
{"name": item["name"], "netbox_name": record.name if record else "", "method": method,
"physical": _physical_interface(item), "vlan_label": vlan_label(item.get("vlans"))}
"physical": _physical_interface(item),
"vlan_label": vlan_label(without_vlans(item.get("vlans"), ignored_vlans(vlan_map)))}
for item in snapshot["interfaces"]
for record, method in [matches[item["name"]]]
],
@@ -1066,6 +1260,11 @@ def plan_switch_sync(nb, config, snapshot):
"neighbors": neighbors,
"device_scope": scope,
"devices": devices,
"tenant": getattr(getattr(device, "tenant", None), "name", None) or str(tenant_id),
"vrfs": vrfs,
"networks": networks,
"vlans": vlans,
"tenants": tenants,
}
@@ -1119,11 +1318,154 @@ class _RemoteLookup:
return None
_NEW = "new" # placeholder ID of objects a dry run would create
def candidate_vrfs(nb, tenant_id):
"""VRFs of the switch's tenant and of its tenant group."""
tenant = nb.tenancy.tenants.get(tenant_id)
group_id = related_id(tenant, "group") if tenant else None
found = {vrf.id: vrf for vrf in nb.ipam.vrfs.filter(tenant_id=tenant_id)}
if group_id:
found.update({vrf.id: vrf for vrf in nb.ipam.vrfs.filter(tenant_group_id=group_id)})
return list(found.values())
def vrf_choice_label(vrf):
owner = getattr(getattr(vrf, "tenant", None), "name", None)
return vrf.name + (f" ({owner})" if owner else "")
def _network_choice(config, network):
"""Stored decision ``{"vrf_id", "vrf_name", "create"}`` for a network, or ``None``."""
choice = (config.get("network_map") or {}).get(network)
if choice is not None:
return choice
# Profiles up to 4.6.0 stored a VRF name and approved prefixes per switch.
legacy_vrfs, legacy_create = config.get("network_vrfs") or {}, config.get("create_prefixes")
if network not in legacy_vrfs and legacy_create is None:
return None
return {"vrf_id": None, "vrf_name": legacy_vrfs.get(network) or "", "create": network in (legacy_create or [])}
def _resolve_vrf_choice(choice, vrf_records, tenant_id):
"""Existing VRF ID, ``None`` for global or the name of a VRF still to create."""
by_id = {vrf.id: vrf for vrf in vrf_records}
if choice.get("vrf_id") in by_id:
return choice["vrf_id"]
name = (choice.get("vrf_name") or "").strip()
if not name:
return None
named = sorted((vrf for vrf in vrf_records if vrf.name.casefold() == name.casefold()),
key=lambda vrf: related_id(vrf, "tenant") != tenant_id)
return named[0].id if named else name
def _sync_vrfs(nb, config, snapshot, tenant_id, dry_run, report):
"""``{network: VRF ID or None}``; new VRFs are created for the switch's tenant."""
vrf_records = candidate_vrfs(nb, tenant_id)
created = {}
result = {}
for network in snapshot_networks(snapshot):
choice = _network_choice(config, network) or {}
resolved = _resolve_vrf_choice(choice, vrf_records, tenant_id)
if isinstance(resolved, str):
if resolved not in created:
report["vrfs_created"] += 1
report["changes"].append(f"VRF {resolved} neu")
created[resolved] = _NEW if dry_run else nb.ipam.vrfs.create({"name": resolved, "tenant": tenant_id}).id
resolved = created[resolved]
result[network] = resolved
return result
def _sync_prefixes(nb, config, snapshot, tenant_id, vrf_ids, dry_run, report):
"""Create missing prefixes that were approved; existing ones stay untouched."""
for network in snapshot_networks(snapshot):
vrf_id = vrf_ids.get(network)
if not (_network_choice(config, network) or {}).get("create"):
continue
if vrf_id != _NEW and list(nb.ipam.prefixes.filter(prefix=network, vrf_id=vrf_id or "null")):
continue
try:
report["prefixes_created"] += 1
if not vrf_id:
vrf_name = "global"
elif vrf_id == _NEW:
vrf_name = f"VRF {_network_choice(config, network).get('vrf_name')}"
else:
vrf_name = f"VRF {getattr(nb.ipam.vrfs.get(vrf_id), 'name', vrf_id)}"
report["changes"].append(f"Prefix {network} neu ({vrf_name})")
if not dry_run:
nb.ipam.prefixes.create({"prefix": network, "status": "active", "tenant": tenant_id, "vrf": vrf_id})
except Exception as error: # noqa: BLE001
report["errors"].append(f"Prefix {network}: {error}")
def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report):
"""``{VLAN ID: NetBox ID}``; missing VLANs are only created when approved."""
_vlans, matches = _switch_vlan_matches(nb, config, snapshot, tenant_id, site_id)
approved = {int(vid) for vid, choice in (config.get("vlan_map") or {}).items() if choice.get("action") == "new"}
approved |= {int(vid) for vid in config.get("create_vlans") or []} # profiles of version 4.4.0
present = {}
for vid, (record, method, name) in matches.items():
if record is not None:
present[vid] = record.id
continue
if method != "new" or vid not in approved:
continue
try:
report["vlans_created"] += 1
report["changes"].append(f"VLAN {vid} „{name}“ neu")
# A different tenant may be chosen per VLAN in the review dialog.
chosen_tenant = ((config.get("vlan_map") or {}).get(str(vid)) or {}).get("tenant") or tenant_id
payload = {"vid": vid, "name": name[:64], "status": "active", "tenant": chosen_tenant}
if site_id:
payload["site"] = site_id
present[vid] = _NEW if dry_run else nb.ipam.vlans.create(payload).id
except Exception as error: # noqa: BLE001
report["errors"].append(f"VLAN {vid}: {error}")
return present
def _record_mode(record):
mode = getattr(record, "mode", None)
return getattr(mode, "value", mode) or ""
def _vlan_assignment(interface, vlan_ids, record=None):
"""802.1Q mode and VLANs of an interface; empty when ``record`` already matches."""
vlans = interface.get("vlans")
if not vlans or netbox_interface_type(interface) == "virtual":
return {}
untagged = next((vlan_ids[vid] for vid in vlans.get("untagged", []) if vid in vlan_ids), None)
tagged = sorted((vlan_ids[vid] for vid in vlans.get("tagged", []) if vid in vlan_ids), key=str)
if untagged is None and not tagged and not vlans.get("tagged_all"):
return {} # none of its VLANs exists in NetBox – leave the port alone
if vlans.get("tagged_all"):
wanted = {"mode": "tagged-all", "untagged_vlan": untagged, "tagged_vlans": []}
elif vlans.get("tagged"):
wanted = {"mode": "tagged", "untagged_vlan": untagged, "tagged_vlans": tagged}
else:
wanted = {"mode": "access", "untagged_vlan": untagged, "tagged_vlans": []}
if record is None:
return wanted
current = {
"mode": _record_mode(record),
"untagged_vlan": related_id(record, "untagged_vlan"),
"tagged_vlans": sorted((getattr(item, "id", item) for item in getattr(record, "tagged_vlans", None) or []),
key=str),
}
# NetBox validates the VLANs against the mode, so all three are sent together.
return {} if current == wanted else wanted
def _new_report():
return {
"interfaces_created": 0, "interfaces_updated": 0, "interfaces_unchanged": 0,
"ips_created": 0, "ips_updated": 0, "ips_unchanged": 0,
"cables_created": 0, "cables_skipped": 0,
"vrfs_created": 0, "prefixes_created": 0, "vlans_created": 0,
"changes": [], "errors": [],
}
@@ -1137,11 +1479,16 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
"""
report = _new_report()
device, error = _resolve_device(nb, config)
if not error:
tenant_id, error = _require_tenant(device)
if error:
report["errors"].append(error)
return report
device_id = device.id
tenant_id = related_id(device, "tenant")
vrf_ids = _sync_vrfs(nb, config, snapshot, tenant_id, dry_run, report)
_sync_prefixes(nb, config, snapshot, tenant_id, vrf_ids, dry_run, report)
vlan_ids = _sync_vlans(nb, config, snapshot, tenant_id, related_id(device, "site"), dry_run, report)
ignored = ignored_vlans(config.get("vlan_map"))
matches = match_interfaces(snapshot["interfaces"], list(nb.dcim.interfaces.filter(device_id=device_id)),
config.get("interface_map"))
records = {}
@@ -1149,7 +1496,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
for interface in snapshot["interfaces"]:
key = interface_key(interface["name"])
record, method = matches[interface["name"]]
label = vlan_label(interface.get("vlans"))
port = dict(interface, vlans=without_vlans(interface.get("vlans"), ignored))
label = vlan_label(port["vlans"])
try:
if record:
changes = {}
@@ -1159,6 +1507,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
# routed ports and snapshots without configuration.
if label and (getattr(record, "label", "") or "") != label:
changes["label"] = label
changes.update(_vlan_assignment(port, vlan_ids, record))
if changes:
report["interfaces_updated"] += 1
texts = []
@@ -1166,6 +1515,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
texts.append("aktivieren" if changes["enabled"] else "deaktivieren")
if "label" in changes:
texts.append(f"Label „{label}“")
if "mode" in changes:
texts.append(f"VLAN-Modus {changes['mode']}")
target = record.name if method == "name" else f"{record.name} ({interface['name']})"
report["changes"].append(f"Interface {target}: {', '.join(texts)}")
if not dry_run:
@@ -1181,6 +1532,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
}
if label:
payload["label"] = label
payload.update(_vlan_assignment(port, vlan_ids))
if interface.get("description"):
payload["description"] = interface["description"][:200]
report["interfaces_created"] += 1
@@ -1201,25 +1553,25 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
record = records[key]
for address in interface.get("ip_addresses", []):
try:
host = str(ipaddress.ip_interface(address).ip)
candidates = [
item for item in nb.ipam.ip_addresses.filter(address=host)
if related_id(item, "vrf") is None
]
parsed = ipaddress.ip_interface(address)
vrf_id = vrf_ids.get(str(parsed.network))
if vrf_id == _NEW:
candidates = [] # the VRF only exists after the real run
else:
candidates = list(nb.ipam.ip_addresses.filter(address=str(parsed.ip), vrf_id=vrf_id or "null"))
if len(candidates) > 1:
raise ValueError("mehrere globale IP-Adressen mit diesem Host gefunden")
payload = {"address": address, "status": "active", "assigned_object_type": "dcim.interface"}
raise ValueError("mehrere IP-Adressen mit diesem Host in derselben VRF gefunden")
payload = {"address": address, "status": "active", "assigned_object_type": "dcim.interface",
"tenant": tenant_id, "vrf": vrf_id}
if record:
payload["assigned_object_id"] = record.id
if tenant_id:
payload["tenant"] = tenant_id
if candidates:
current = candidates[0]
differs = (
str(current.address) != address
or getattr(current, "assigned_object_type", None) != "dcim.interface"
or getattr(current, "assigned_object_id", None) != payload.get("assigned_object_id")
or (tenant_id and related_id(current, "tenant") != tenant_id)
or related_id(current, "tenant") != tenant_id
)
if differs:
report["ips_updated"] += 1
@@ -1271,6 +1623,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
"a_terminations": [{"object_type": "dcim.interface", "object_id": local.id}],
"b_terminations": [{"object_type": "dcim.interface", "object_id": remote.id}],
"status": "connected",
"tenant": tenant_id,
})
remote.cable = True # avoid a second cable from the reverse direction
except Exception as error: # noqa: BLE001
+143
View File
@@ -0,0 +1,143 @@
"""Updates from the Gitea releases of the project.
The latest release is read anonymously from the Gitea API. The installed
version updates by running the new installer silently (it restarts the
application afterwards); the portable EXE is swapped in place: Windows allows
renaming a running EXE, so the old file is moved aside and removed on the next
start.
"""
import re
import subprocess
import sys
from pathlib import Path
import requests
from netbox_sync import APP_VERSION
REPOSITORY_API = "https://git.mrblake.cc/api/v1/repos/MrBlake/NetBox-Import-Desktop"
LATEST_RELEASE_URL = f"{REPOSITORY_API}/releases/latest"
PORTABLE_ASSET = "NetBox VM Import.exe"
INSTALLER_ASSET = re.compile(r"(?i)^NetBoxSynchronizer-Setup-[\d.]+\.exe$")
INSTALLER_ARGUMENTS = ("/SILENT", "/SUPPRESSMSGBOXES", "/NORESTART", "/CLOSEAPPLICATIONS")
_DETACHED = 0x00000008 | 0x00000200 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
class UpdateError(RuntimeError):
pass
def parse_version(text):
"""``"v4.6.0"`` → ``(4, 6, 0)``."""
numbers = [int(part) for part in re.findall(r"\d+", text or "")[:3]]
return tuple(numbers + [0] * (3 - len(numbers)))
def install_kind():
"""``"installer"``, ``"portable"`` or ``None`` when running from source."""
if not getattr(sys, "frozen", False):
return None
exe_dir = Path(sys.executable).resolve().parent
bundle = Path(getattr(sys, "_MEIPASS", exe_dir)).resolve()
# A one-file (portable) build unpacks itself into a temporary folder.
return "installer" if bundle == exe_dir or exe_dir in bundle.parents else "portable"
def check_for_update(current=APP_VERSION, timeout=10):
"""Return the newer release or ``None``."""
try:
response = requests.get(LATEST_RELEASE_URL, timeout=timeout, headers={"Accept": "application/json"})
response.raise_for_status()
release = response.json()
except (requests.RequestException, ValueError) as error:
raise UpdateError(f"Update-Server nicht erreichbar: {error}") from error
if release.get("draft") or release.get("prerelease"):
return None
tag = release.get("tag_name") or ""
if parse_version(tag) <= parse_version(current):
return None
return {
"version": tag.lstrip("vV"),
"name": release.get("name") or tag,
"notes": release.get("body") or "",
"page": release.get("html_url") or "",
"assets": {asset["name"]: {"url": asset["browser_download_url"], "size": int(asset.get("size") or 0)}
for asset in release.get("assets", []) if asset.get("browser_download_url")},
}
def pick_asset(release, kind):
"""``(name, asset)`` matching the running installation, or ``None``."""
for name, asset in release["assets"].items():
if kind == "portable" and name.casefold() == PORTABLE_ASSET.casefold():
return name, asset
if kind == "installer" and INSTALLER_ASSET.match(name):
return name, asset
return None
def download(asset, target, progress=None, cancelled=None, timeout=30):
"""Stream ``asset`` to ``target``; the size is verified before the file is kept."""
target = Path(target)
partial = target.with_name(target.name + ".part")
try:
with requests.get(asset["url"], stream=True, timeout=timeout) as response:
response.raise_for_status()
total = asset.get("size") or int(response.headers.get("Content-Length") or 0)
done = 0
with partial.open("wb") as handle:
for chunk in response.iter_content(256 * 1024):
if cancelled and cancelled():
raise UpdateError("Download abgebrochen.")
handle.write(chunk)
done += len(chunk)
if progress:
progress(done, total)
except requests.RequestException as error:
partial.unlink(missing_ok=True)
raise UpdateError(f"Download fehlgeschlagen: {error}") from error
except BaseException:
partial.unlink(missing_ok=True)
raise
if total and done != total:
partial.unlink(missing_ok=True)
raise UpdateError(f"Download unvollständig ({done} von {total} Bytes).")
partial.replace(target)
return target
def portable_download_path():
exe = Path(sys.executable)
return exe.with_name(exe.stem + ".new.exe")
def apply_portable(new_exe):
"""Swap the running portable EXE for ``new_exe`` and start it."""
exe = Path(sys.executable)
old = exe.with_name(exe.stem + ".old.exe")
old.unlink(missing_ok=True)
exe.replace(old)
try:
Path(new_exe).replace(exe)
except OSError:
old.replace(exe)
raise
subprocess.Popen([str(exe)], close_fds=True, creationflags=_DETACHED) # noqa: S603
def apply_installer(setup_exe):
"""Run the installer silently; it closes and restarts the application."""
subprocess.Popen([str(setup_exe), *INSTALLER_ARGUMENTS], close_fds=True, creationflags=_DETACHED) # noqa: S603
def remove_leftovers():
"""Delete the previous portable EXE left behind by an update."""
if install_kind() != "portable":
return
exe = Path(sys.executable)
for leftover in (exe.with_name(exe.stem + ".old.exe"), portable_download_path()):
try:
leftover.unlink(missing_ok=True)
except OSError:
pass
+16 -1
View File
@@ -405,7 +405,11 @@ class Actions:
if not self.require_netbox_config():
return
by_id = {switch["id"]: switch for switch in self.state.switches}
items = [(dict(by_id[switch_id]), self.state.switch_snapshots[switch_id])
# VLAN and network decisions are shared by all switches of the profile.
vlan_map = self.state.profile.setdefault("vlan_map", {})
network_map = self.state.profile.setdefault("network_map", {})
items = [(dict(by_id[switch_id], vlan_map=dict(vlan_map), network_map=dict(network_map)),
self.state.switch_snapshots[switch_id])
for switch_id in switch_ids if switch_id in by_id and switch_id in self.state.switch_snapshots]
if not items:
widgets.message(self.window, "Keine Daten", "Bitte die Switche zuerst auslesen.", "info")
@@ -429,6 +433,8 @@ class Actions:
needs_review = any(
any(entry["method"] not in ("name", "new") or (entry["method"] == "new" and entry["physical"])
for entry in item["interfaces"]) or (create_cables and item["neighbors"])
or any(not network["stored"] and not network["existing"] for network in item["networks"])
or any(not vlan["stored"] and vlan["method"] in ("new", "ambiguous") for vlan in item["vlans"])
for _switch, item in reviewable)
def ask():
@@ -439,13 +445,22 @@ class Actions:
if not dialog.exec():
return
stored = {switch["id"]: switch for switch in self.state.switches}
vlan_map.clear()
vlan_map.update(dialog.vlan_map)
network_map.clear()
network_map.update(dialog.network_map)
for switch, _snapshot in items:
choices = dialog.result.get(switch["id"])
if choices:
switch.update(choices)
if switch["id"] in stored:
stored[switch["id"]].update(choices)
switch.update(vlan_map=dict(vlan_map), network_map=dict(network_map))
for legacy in ("network_vrfs", "create_prefixes", "create_vlans"):
switch.pop(legacy, None)
stored.get(switch["id"], {}).pop(legacy, None)
self.state.touch()
self.state.switches_changed.emit() # ignored VLANs vanish from the VLAN column
self.tasks.run(lambda ctx: preview(ctx, nb), title="Änderungen berechnen", area="switch",
on_success=show_preview, on_error=self._netbox_failed)
QTimer.singleShot(0, ask)
+1
View File
@@ -84,6 +84,7 @@ def main():
hints.colorSchemeChanged.connect(lambda _scheme: theme.mode == "system" and theme.apply())
install_excepthook(lambda: window)
window.show()
window.updates.check_on_start()
return app.exec()
+9 -4
View File
@@ -36,9 +36,9 @@ class ClientTargetDialog(_Dialog):
else:
self.role.setEditText(remembered)
form.addRow("Geräterolle *", self.role)
self.tenant = SearchableComboBox("Kein Mandant")
self.tenant.set_items([("Kein Mandant", None)] + list(engine.tenants), options.get("netbox_tenant"))
form.addRow("Mandant", self.tenant)
self.tenant = SearchableComboBox("Mandant wählen …")
self.tenant.set_items(list(engine.tenants), options.get("netbox_tenant"))
form.addRow("Mandant *", self.tenant)
self.root.addLayout(form)
self.interfaces = checkbox("Netzwerkkarten, MAC- und IP-Adressen übernehmen",
options.get("sync_interfaces", True),
@@ -60,16 +60,21 @@ class ClientTargetDialog(_Dialog):
role_text = self.role.currentText().strip()
role = self.role.valid_data()
_mark_invalid(self.site, site is None)
tenant = self.tenant.valid_data()
_mark_invalid(self.role, not role_text)
_mark_invalid(self.tenant, tenant is None)
if site is None:
self.show_error("Bitte einen vorhandenen Standort auswählen.")
return
if not role_text:
self.show_error("Bitte eine Geräterolle auswählen oder einen Namen für eine neue Rolle eingeben.")
return
if tenant is None:
self.show_error("Bitte einen Mandanten auswählen – alle Objekte in NetBox brauchen einen Mandanten.")
return
self.result = {
"site_id": site, "role_id": role, "role_name": role_text,
"tenant_id": self.tenant.valid_data(),
"tenant_id": tenant,
"interfaces": self.interfaces.isChecked(), "update_existing": self.update_existing.isChecked(),
}
super().accept()
+248 -4
View File
@@ -26,7 +26,7 @@ from PySide6.QtWidgets import (
)
from netbox_sync.core.config import known_hosts_path
from netbox_sync.core.switches import MATCH_METHODS, PLATFORMS, forget_host_key
from netbox_sync.core.switches import MATCH_METHODS, PLATFORMS, VLAN_METHODS, forget_host_key
from netbox_sync.core.virtualization import test_source
from netbox_sync.ui.icons import icon
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
@@ -527,6 +527,10 @@ class SyncPreviewDialog(_Dialog):
(f"{totals.get('interfaces_updated', 0)} Interfaces geändert", "info"),
(f"{totals.get('ips_created', 0) + totals.get('ips_updated', 0)} IP-Adressen", "info"),
]
for key, text in (("vrfs_created", "VRF(s) neu"), ("prefixes_created", "Prefix(e) neu"),
("vlans_created", "VLAN(s) neu")):
if totals.get(key):
items.append((f"{totals[key]} {text}", "info"))
if create_cables:
items.append((f"{totals.get('cables_created', 0)} Kabel", "info"))
errors = sum(len(report["errors"]) for _switch, report in reports)
@@ -580,12 +584,18 @@ class SwitchMappingDialog(_Dialog):
def __init__(self, parent, plans, create_cables):
super().__init__(parent, "Zuordnung prüfen",
"Schnittstellen, deren Name auf dem Switch anders lautet als in NetBox, wurden automatisch "
"zugeordnet. Bitte prüfen und bei Bedarf korrigieren – die Auswahl wird im Profil gespeichert.",
"Schnittstellen, Nachbarn, Netze und VLANs prüfen und bei Bedarf korrigieren. Neue Objekte "
"erhalten immer den Mandanten des Switches – die Auswahl wird im Profil gespeichert.",
width=820)
self.resize(980, 660)
self.resize(1120, 680)
self.plans = plans
self.result = None
# Profile-wide VLAN decisions; every switch config carries the same map.
self.previous_vlan_map = dict((plans[0][0].get("vlan_map") if plans else None) or {})
self.vlan_map = dict(self.previous_vlan_map)
self.previous_network_map = dict((plans[0][0].get("network_map") if plans else None) or {})
self.network_map = dict(self.previous_network_map)
self._new_vrf_names = []
tabs = QTabWidget()
# Interfaces --------------------------------------------------------
@@ -657,6 +667,75 @@ class SwitchMappingDialog(_Dialog):
found = sum(1 for _switch, neighbor, _combo in self.neighbor_rows if neighbor.get("device_id"))
tabs.addTab(neighbor_page, f"Nachbarn ({found} von {len(self.neighbor_rows)} zugeordnet)")
# Networks --------------------------------------------------------------
# Network decisions apply to all switches of the profile: one row per network.
self.network_rows = []
networks = {}
for switch, plan in plans:
for item in plan["networks"]:
entry = networks.setdefault(item["network"], {"item": item, "switches": [], "tenants": [], "vrfs": {}})
entry["switches"].append(switch["name"])
if plan["tenant"] not in entry["tenants"]:
entry["tenants"].append(plan["tenant"])
entry["vrfs"].update({vrf["id"]: vrf["label"] for vrf in plan["vrfs"]})
if networks:
network_page = QWidget()
network_layout = QVBoxLayout(network_page)
network_layout.setContentsMargins(0, 12, 0, 0)
network_layout.addWidget(label(
"Netze der Switch-IP-Adressen. Die VRF gilt für Prefix und IP-Adressen; zur Auswahl stehen die "
"globale Tabelle und die VRFs der Mandantengruppe. Fehlende Prefixe werden nur angelegt, wenn sie "
"angehakt sind – mit dem Mandanten des Switches. Die Auswahl gilt für alle Switche des Profils.",
muted=True, wrap=True))
settled = {network: entry["item"]["stored"] or bool(entry["item"]["existing"])
for network, entry in networks.items()}
self.open_network_table = self._network_table()
self.settled_network_table = self._network_table()
for network, entry in networks.items():
table = self.settled_network_table if settled[network] else self.open_network_table
self._add_network_row(table, entry)
for table in (self.open_network_table, self.settled_network_table):
self._prepare_table(table, (160, 150, 150, 300, 200))
open_count = sum(1 for value in settled.values() if not value)
self.settled_network_toggle = self._collapsible(network_layout, self.open_network_table,
self.settled_network_table, open_count,
len(networks) - open_count, "Netze")
missing = sum(1 for entry in networks.values() if not entry["item"]["existing"])
tabs.addTab(network_page, f"Netze ({open_count} zu prüfen, {missing} Prefix(e) fehlen)")
# VLANs -----------------------------------------------------------------
# VLAN decisions apply to all switches of the profile: one row per VID.
self.vlan_rows = []
merged = {}
for switch, plan in plans:
for item in plan["vlans"]:
entry = merged.setdefault(item["vid"], {"item": item, "switches": [], "candidates": {}, "tenants": {}})
entry["switches"].append(switch["name"])
entry["candidates"].update({candidate["id"]: candidate["label"] for candidate in item["candidates"]})
entry["tenants"].update({tenant["id"]: tenant["name"] for tenant in plan["tenants"]})
if merged:
vlan_page = QWidget()
vlan_layout = QVBoxLayout(vlan_page)
vlan_layout.setContentsMargins(0, 12, 0, 0)
vlan_layout.addWidget(label(
"Gesucht wird in der Mandantengruppe über die VLAN-ID; bei mehreren Treffern entscheiden Mandant, "
"Standort und Name. Neue VLANs erhalten den eingetragenen Namen und Mandanten. Ignorierte VLANs "
"werden weder angelegt noch zugeordnet und fehlen im Label. Die Auswahl gilt für alle Switche "
"des Profils und wird gespeichert.", muted=True, wrap=True))
settled = {vid: entry["item"]["stored"] or entry["item"]["method"] in ("vid", "name")
for vid, entry in merged.items()}
self.open_vlan_table = self._vlan_table()
self.settled_vlan_table = self._vlan_table()
for vid in sorted(merged):
self._add_vlan_row(self.settled_vlan_table if settled[vid] else self.open_vlan_table, merged[vid])
for table in (self.open_vlan_table, self.settled_vlan_table):
self._prepare_table(table, (130, 60, 150, 280, 190, 170, 110))
open_count = sum(1 for value in settled.values() if not value)
self.settled_toggle = self._collapsible(vlan_layout, self.open_vlan_table, self.settled_vlan_table,
open_count, len(merged) - open_count, "VLANs")
missing = sum(1 for entry in merged.values() if entry["item"]["method"] == "new")
tabs.addTab(vlan_page, f"VLANs ({open_count} zu prüfen, {missing} fehlen)")
self.root.addWidget(tabs, 1)
self.root.addWidget(self.error_banner)
buttons, _ok = form_dialog_buttons(self, "Weiter zur Vorschau")
@@ -664,6 +743,11 @@ class SwitchMappingDialog(_Dialog):
@staticmethod
def _prepare_table(table, widths):
# Rows must fit the styled combo boxes, otherwise their text is clipped.
height = max((table.cellWidget(row, column).sizeHint().height()
for row in range(min(table.rowCount(), 1)) for column in range(table.columnCount())
if table.cellWidget(row, column)), default=0)
table.verticalHeader().setDefaultSectionSize(max(height + 10, table.verticalHeader().defaultSectionSize()))
table.verticalHeader().hide()
table.setEditTriggers(QTableWidget.NoEditTriggers)
table.setSelectionMode(QTableWidget.NoSelection)
@@ -671,6 +755,140 @@ class SwitchMappingDialog(_Dialog):
for column, width in enumerate(widths):
table.setColumnWidth(column, width)
IGNORE = "\x00ignore"
@staticmethod
def _vlan_table():
table = QTableWidget(0, 7)
table.setHorizontalHeaderLabels(["Switch(e)", "VLAN", "Name (Switch)", "NetBox-VLAN",
"Name des neuen VLANs", "Mandant (neu)", "Zuordnung"])
return table
def _add_vlan_row(self, table, entry):
item = entry["item"]
row = table.rowCount()
table.insertRow(row)
switches = ", ".join(entry["switches"])
for column, text in enumerate((switches, str(item["vid"]), item["name"])):
table.setItem(row, column, QTableWidgetItem(text))
combo = QComboBox()
for candidate_id, text in sorted(entry["candidates"].items(), key=lambda pair: pair[1].casefold()):
combo.addItem(text, candidate_id)
combo.addItem("+ neu anlegen", self.NEW)
combo.addItem("– nicht zuordnen –", 0)
combo.addItem("⊘ ignorieren (auf allen Switchen)", self.IGNORE)
current = {"skip": 0, "ignore": self.IGNORE}.get(item["method"], item["netbox_id"] or self.NEW)
combo.setCurrentIndex(max(0, combo.findData(current)))
name = QLineEdit(item["new_name"])
name.setMaxLength(64)
name.setPlaceholderText(item["name"])
tenant = QComboBox()
for tenant_id, text in sorted(entry["tenants"].items(), key=lambda pair: pair[1].casefold()):
tenant.addItem(text, tenant_id)
tenant.setCurrentIndex(max(0, tenant.findData(item["new_tenant"])))
method = QTableWidgetItem(VLAN_METHODS.get(item["method"], item["method"])
+ (" · gespeichert" if item["stored"] else ""))
if not item["stored"] and item["method"] in ("ambiguous", "new"):
method.setForeground(QColor(theme.color("warning")))
table.setCellWidget(row, 3, combo)
table.setCellWidget(row, 4, name)
table.setCellWidget(row, 5, tenant)
table.setItem(row, 6, method)
def toggle(_index=None):
for widget in (name, tenant):
widget.setEnabled(combo.currentData() == self.NEW)
combo.currentIndexChanged.connect(toggle)
toggle()
self.vlan_rows.append((item, combo, name, tenant))
@staticmethod
def _collapsible(layout, open_table, settled_table, open_count, settled_count, noun):
"""Open items on top, decided ones in a collapsed section that can be expanded."""
layout.addWidget(label(f"<b>Zu prüfen ({open_count})</b>" if open_count else
f"Alle {noun} sind zugeordnet oder gespeichert.", wrap=True))
layout.addWidget(open_table, 1)
open_table.setVisible(bool(open_count))
toggle = button("", variant="link")
toggle.setCheckable(True)
def update(expanded):
arrow = "▾" if expanded else "▸"
toggle.setText(f"{arrow} Gespeicherte und eindeutig zugeordnete {noun} ({settled_count})"
+ ("" if expanded else " – zum Bearbeiten ausklappen"))
settled_table.setVisible(expanded and settled_count > 0)
toggle.toggled.connect(update)
update(False)
toggle.setVisible(settled_count > 0)
layout.addWidget(toggle, 0, Qt.AlignLeft)
layout.addWidget(settled_table, 1)
return toggle
@staticmethod
def _network_table():
table = QTableWidget(0, 5)
table.setHorizontalHeaderLabels(["Switch(e)", "Mandant", "Netz", "VRF", "Prefix in NetBox"])
return table
def _add_network_row(self, table, entry):
item = entry["item"]
row = table.rowCount()
table.insertRow(row)
texts = (", ".join(entry["switches"]), ", ".join(entry["tenants"]), item["network"])
for column, text in enumerate(texts):
table.setItem(row, column, QTableWidgetItem(text))
combo = QComboBox()
combo.addItem("Global (keine VRF)", 0)
for vrf_id, text in sorted(entry["vrfs"].items(), key=lambda pair: pair[1].casefold()):
combo.addItem(text, vrf_id)
new_names = list(self._new_vrf_names)
if item["vrf_name"] and item["vrf_name"] not in new_names:
new_names.append(item["vrf_name"])
for name in new_names:
combo.addItem(f"{name} (neu)", f"new:{name}")
combo.addItem("+ Neue VRF …", self.NEW)
current = f"new:{item['vrf_name']}" if item["vrf_name"] else item["vrf_id"]
combo.setCurrentIndex(max(0, combo.findData(current)))
combo.setProperty("previous", combo.currentIndex())
table.setCellWidget(row, 3, combo)
status = QTableWidgetItem()
table.setItem(row, 4, status)
row_entry = (item, combo, status)
self.network_rows.append(row_entry)
combo.activated.connect(lambda _index, row_entry=row_entry: self._vrf_chosen(row_entry))
self._update_network_row(row_entry, item["create"])
def _vrf_chosen(self, entry):
_item, combo, _status = entry
if combo.currentData() == self.NEW:
name = ask_text(self, "Neue VRF", "Name der neuen VRF. Sie wird beim Übertragen mit dem Mandanten "
"des Switches angelegt.")
if not name:
combo.setCurrentIndex(combo.property("previous"))
return
self._new_vrf_names.append(name)
# Offer the new VRF in every network row.
for _other_item, other, _other_status in self.network_rows:
if other.findData(f"new:{name}") < 0:
other.insertItem(other.count() - 1, f"{name} (neu)", f"new:{name}")
combo.setCurrentIndex(combo.findData(f"new:{name}"))
combo.setProperty("previous", combo.currentIndex())
self._update_network_row(entry)
def _update_network_row(self, entry, create=None):
item, combo, status = entry
if combo.currentData() in item["existing"]:
status.setText("vorhanden")
status.setFlags(Qt.ItemIsEnabled)
status.setData(Qt.CheckStateRole, None)
status.setForeground(QColor(theme.color("text_muted")))
return
status.setText("fehlt – anlegen")
status.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
if create is not None or status.data(Qt.CheckStateRole) is None:
status.setCheckState(Qt.Checked if create is not False else Qt.Unchecked)
status.setForeground(QColor(theme.color("warning")))
def _filter_interfaces(self, only_unclear):
for row, _switch, item, _combo in self.interface_rows:
self.interface_table.setRowHidden(row, only_unclear and item["method"] == "name")
@@ -703,6 +921,32 @@ class SwitchMappingDialog(_Dialog):
stored.pop(neighbor["local_port"], None)
else:
stored[neighbor["local_port"]] = chosen
network_map = dict(self.previous_network_map)
for item, combo, status in self.network_rows:
chosen = combo.currentData()
new_name = chosen[4:] if isinstance(chosen, str) and chosen.startswith("new:") else ""
network_map[item["network"]] = {
"vrf_id": chosen if isinstance(chosen, int) and chosen else None,
"vrf_name": new_name,
"create": status.data(Qt.CheckStateRole) is not None and status.checkState() == Qt.Checked,
}
self.network_map = network_map
vlan_map = dict(self.previous_vlan_map)
for item, combo, name, tenant in self.vlan_rows:
chosen = combo.currentData()
if chosen == self.NEW:
if not name.text().strip():
self.show_error(f"Bitte einen Namen für das neue VLAN {item['vid']} eingeben.")
return
choice = {"action": "new", "name": name.text().strip(), "tenant": tenant.currentData()}
elif chosen == self.IGNORE:
choice = {"action": "ignore"}
elif chosen:
choice = {"action": "map", "id": chosen}
else:
choice = {"action": "skip"}
vlan_map[str(item["vid"])] = choice
self.vlan_map = vlan_map
self.result = result
super().accept()
+8 -1
View File
@@ -28,6 +28,7 @@ from netbox_sync.ui.pages.connections import ConnectionsPage
from netbox_sync.ui.pages.ipam import IpamPage
from netbox_sync.ui.pages.log import LogPage
from netbox_sync.ui.pages.overview import OverviewPage
from netbox_sync.ui.pages.scanner import ScannerPage
from netbox_sync.ui.pages.settings import SettingsPage
from netbox_sync.ui.pages.switches import SwitchesPage
from netbox_sync.ui.pages.vms import VMsPage
@@ -35,6 +36,7 @@ from netbox_sync.ui.resources import resource_path
from netbox_sync.ui.state import AppState
from netbox_sync.ui.tasks import TaskManager, log_bus
from netbox_sync.ui.theme import theme
from netbox_sync.ui.updates import UpdateManager
from netbox_sync.ui.widgets import Badge, Toast, button, label
NAVIGATION = (
@@ -44,6 +46,7 @@ NAVIGATION = (
("switches", "Switche", "network"),
("clients", "Windows-Clients", "monitor"),
("ipam", "VRFs && Netze", "globe"),
("scanner", "Netzwerk-Scanner", "search"),
("log", "Protokoll", "list"),
)
@@ -81,6 +84,7 @@ class MainWindow(QMainWindow):
self.state = AppState()
self.tasks = TaskManager()
self.actions = Actions(self)
self.updates = UpdateManager(self)
self.pages = {}
self.nav_buttons = {}
self.unseen_errors = 0
@@ -102,7 +106,8 @@ class MainWindow(QMainWindow):
self.toast_widget = Toast(central)
for key, page_class in (("overview", OverviewPage), ("connections", ConnectionsPage), ("vms", VMsPage),
("switches", SwitchesPage), ("clients", ClientsPage), ("ipam", IpamPage), ("log", LogPage),
("switches", SwitchesPage), ("clients", ClientsPage), ("ipam", IpamPage), ("scanner", ScannerPage),
("log", LogPage),
("settings", SettingsPage)):
page = page_class(self)
self.pages[key] = page
@@ -271,6 +276,8 @@ class MainWindow(QMainWindow):
page.discover()
elif page is self.pages["clients"] and not self.tasks.busy:
page.scan()
elif page is self.pages["scanner"] and not self.tasks.busy:
page.scan()
def _focus_search(self):
search = getattr(self.current_page(), "search", None)
+338
View File
@@ -0,0 +1,338 @@
import os
import subprocess
import webbrowser
from PySide6.QtCore import QObject, Qt, QTimer, Signal
from PySide6.QtGui import QGuiApplication
from PySide6.QtWidgets import QFormLayout, QHBoxLayout, QLineEdit, QMenu, QStackedWidget
from netbox_sync.core import netscan
from netbox_sync.ui import widgets
from netbox_sync.ui.icons import icon
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
from netbox_sync.ui.pages import Page
from netbox_sync.ui.tasks import logger
from netbox_sync.ui.theme import theme
from netbox_sync.ui.widgets import Card, EmptyState, SearchField, Table, button, checkbox, label
COMPARE_DOT = {"match": "success", "differs": "warning", "missing": "danger", "offline": "text_faint"}
class _Results(QObject):
"""Carries hosts from the scan threads to the UI thread."""
host = Signal(object)
def _name(row):
return row.get("dns_name") or row.get("netbios_name") or ""
def _netbox(row, key):
return ", ".join(dict.fromkeys(entry[key] for entry in row.get("netbox", []) if entry[key]))
def _services(row):
return ", ".join(f"{item['service'] or 'TCP'} ({item['port']})" for item in row.get("ports", []))
class ScannerPage(Page):
title = "Netzwerk-Scanner"
subtitle = ("IP-Bereiche nach erreichbaren Geräten, Namen, MAC-Adressen und offenen Diensten durchsuchen. "
"Jede Adresse wird automatisch mit NetBox abgeglichen – es wird nichts geschrieben.")
def __init__(self, window):
super().__init__(window)
self.rows = {}
self.netbox = {}
self.netbox_note = ""
self.scan_task = None
self.results = _Results()
self.results.host.connect(self._host_found)
self.refresh_timer = QTimer(self)
self.refresh_timer.setSingleShot(True)
self.refresh_timer.setInterval(250)
self.refresh_timer.timeout.connect(self._refresh)
target_card = Card("Scan")
form = QFormLayout()
form.setHorizontalSpacing(18)
targets = QHBoxLayout()
self.targets = QLineEdit()
self.targets.setPlaceholderText("z. B. 192.168.1.1-254, 10.0.0.0/24, server01")
targets.addWidget(self.targets, 1)
self.own_network = button("Eigenes Netz", "network", tooltip="Netze dieses Rechners übernehmen")
self.own_network.clicked.connect(self._own_network_menu)
targets.addWidget(self.own_network)
form.addRow("IP-Bereiche", targets)
self.ports = QLineEdit()
self.ports.setPlaceholderText(netscan.DEFAULT_PORTS)
form.addRow("Ports", self.ports)
target_card.add(form)
self.scan_button = target_card.add_action(button("Scannen", "play", "primary", on_click=self.scan))
self.body.addWidget(target_card)
result_card = Card("Ergebnisse", "Name aus DNS bzw. NetBIOS; NetBox-Spalten aus den IP-Adressen in NetBox.")
filters = QHBoxLayout()
self.search = SearchField("IP, Name, MAC, Dienst, NetBox-Objekt …")
self.only_alive = checkbox("Nur erreichbare", True)
self.only_issues = checkbox("Nur Abweichungen",
tooltip="Nicht in NetBox, abweichender Name oder in NetBox, aber nicht erreichbar")
filters.addWidget(self.search, 2)
filters.addWidget(self.only_alive)
filters.addWidget(self.only_issues)
filters.addStretch(1)
result_card.add(filters)
columns = [
Column("ip", "IP-Adresse", 130, dot=lambda row: "success" if row.get("alive") else "text_faint"),
Column("name", "Name", 210, value=_name,
tooltip=lambda row: "\n".join(filter(None, (
f"DNS: {row['dns_name']}" if row.get("dns_name") else "",
f"NetBIOS: {row['netbios_name']}" if row.get("netbios_name") else "",
f"Arbeitsgruppe/Domäne: {row['workgroup']}" if row.get("workgroup") else "")))),
Column("mac", "MAC-Adresse", 140),
Column("services", "Dienste", 230, value=_services, tooltip=_services),
Column("rtt", "Antwort", 70, value=lambda row: "" if row.get("rtt") is None else f"{row['rtt']} ms",
sort=lambda row: row.get("rtt") if row.get("rtt") is not None else 99999,
color=lambda row: "text_muted"),
Column("nb_object", "NetBox-Objekt", 190, value=lambda row: _netbox(row, "object"),
tooltip=lambda row: "\n".join(
f"{entry['object_kind'] or 'IP'} {entry['object']} · {entry['vrf'] or 'global'} · "
f"{entry['tenant'] or 'ohne Mandant'} · {entry['status']}"
+ (f"\n{entry['description']}" if entry["description"] else "")
for entry in row.get("netbox", []))),
Column("nb_dns", "NetBox-DNS-Name", 190, value=lambda row: _netbox(row, "dns_name")),
Column("compare", "Abgleich", 170, value=lambda row: netscan.COMPARE_TEXT.get(row.get("compare"), ""),
dot=lambda row: COMPARE_DOT.get(row.get("compare"))),
]
self.model = RowTableModel(columns, row_id=lambda row: row["ip"])
self.proxy = FilterProxy(self.model)
self.table = Table()
self.table.setModel(self.proxy)
for index, column in enumerate(columns):
self.table.setColumnWidth(index, column.width)
self.table.sortByColumn(0, Qt.AscendingOrder)
self.table.doubleClicked.connect(lambda _index: self._open_default())
self.table.setContextMenuPolicy(Qt.CustomContextMenu)
self.table.customContextMenuRequested.connect(self._context_menu)
self.stack = QStackedWidget()
self.stack.addWidget(EmptyState("search", "Noch nicht gescannt",
"IP-Bereiche eintragen und „Scannen“ wählen. Ist ein NetBox-Zugang "
"eingerichtet, erscheinen Objekt und DNS-Name aus NetBox automatisch."))
self.stack.addWidget(self.table)
result_card.add(self.stack, 1)
self.summary = label("", muted=True)
result_card.add(self.summary)
self.body.addWidget(result_card, 1)
self.search.textChanged.connect(self.proxy.set_text)
self.only_alive.toggled.connect(self._apply_filters)
self.only_issues.toggled.connect(self._apply_filters)
self.targets.editingFinished.connect(
lambda: self.state.update_settings(scanner_targets=self.targets.text().strip()))
self.ports.editingFinished.connect(lambda: self.state.update_settings(scanner_ports=self.ports.text().strip()))
self.targets.returnPressed.connect(self.scan)
self.targets.setText(self.state.settings.get("scanner_targets", ""))
self.ports.setText(self.state.settings.get("scanner_ports", ""))
self._apply_filters()
# ------------------------------------------------------------------
def on_show(self):
if not self.targets.text().strip():
networks = netscan.local_networks()
if networks:
self.targets.setText(networks[0])
def set_busy(self, busy):
scanning = busy and self.scan_task is not None and self.tasks.current is self.scan_task
self.scan_button.setText("Stopp" if scanning else "Scannen")
widgets.set_enabled(self.scan_button, scanning or not busy, "Bitte warten …")
def _own_network_menu(self):
networks = netscan.local_networks()
if not networks:
self.window.toast("Kein eigenes IPv4-Netz gefunden.", "info")
return
menu = QMenu(self)
for network in networks:
menu.addAction(network, lambda n=network: self.targets.setText(n))
if len(networks) > 1:
menu.addSeparator()
menu.addAction("Alle", lambda: self.targets.setText(", ".join(networks)))
menu.exec(self.own_network.mapToGlobal(self.own_network.rect().bottomLeft()))
def _apply_filters(self, *_args):
self.proxy.set_predicate("alive", (lambda row: row.get("alive") or row.get("compare") == "offline")
if self.only_alive.isChecked() else None)
self.proxy.set_predicate("issues", (lambda row: row.get("compare") in ("differs", "missing", "offline"))
if self.only_issues.isChecked() else None)
self._update_summary()
def _update_summary(self):
rows = list(self.rows.values())
alive = sum(1 for row in rows if row.get("alive"))
counts = {key: sum(1 for row in rows if row.get("compare") == key) for key in COMPARE_DOT}
parts = [f"{alive} erreichbar"]
if self.netbox_note:
parts.append(self.netbox_note)
else:
parts += [f"{counts['match']} stimmen mit NetBox überein", f"{counts['differs']} abweichend",
f"{counts['missing']} nicht in NetBox", f"{counts['offline']} in NetBox, nicht erreichbar"]
self.summary.setText(" · ".join(parts))
# ------------------------------------------------------------------
# Scan
# ------------------------------------------------------------------
def scan(self):
if self.scan_task is not None and self.tasks.current is self.scan_task:
self.tasks.cancel()
return
if self.tasks.busy:
return
try:
ips = netscan.expand_ips(self.targets.text())
ports = netscan.parse_ports(self.ports.text().strip() or netscan.DEFAULT_PORTS)
except netscan.ScanError as error:
widgets.message(self.window, "Eingabe prüfen", str(error), "warning")
return
self.state.update_settings(scanner_targets=self.targets.text().strip(), scanner_ports=self.ports.text().strip())
compare = bool(self.state.profile) and not self.state.offline and self.state.netbox_configured()
connect = self.actions._connector() if compare else None
self.rows, self.netbox = {}, {}
self.netbox_note = "" if compare else "kein NetBox-Abgleich (kein Zugang im Profil oder Offline-Modus)"
self.model.set_rows([])
self.stack.setCurrentIndex(1)
results = self.results
def work(ctx):
netbox_map, note = {}, ""
if connect:
try:
ctx.progress(0, len(ips), "NetBox-Abgleich …")
netbox_map = netscan.netbox_lookup(connect(ctx), ips)
ctx.log(f"NetBox: {sum(len(items) for items in netbox_map.values())} IP-Adressen in den "
"gescannten Bereichen")
except Exception as error: # noqa: BLE001 - the scan works without NetBox
note = f"NetBox-Abgleich nicht möglich: {error}"
ctx.log(note, "warning")
results.host.emit({"__netbox__": netbox_map, "__note__": note})
ctx.log(f"Scanne {len(ips)} Adressen, {len(ports)} Ports …")
done = [0]
def found(host):
done[0] += 1
ctx.progress(done[0], len(ips), host["ip"])
results.host.emit(host)
netscan.scan(ips, ports, found, lambda: ctx.cancelled)
ctx.check_cancelled()
return len(ips)
def finished(count):
self._finish()
alive = sum(1 for row in self.rows.values() if row.get("alive"))
logger("app").log(25, "Scan abgeschlossen: %s von %s Adressen erreichbar", alive, count)
self.window.toast(f"{alive} von {count} Adressen erreichbar")
self.scan_task = self.tasks.run(work, title=f"{len(ips)} Adressen scannen", area="app",
on_success=finished, on_error=lambda error: widgets.error(
self.window, "Scan fehlgeschlagen", str(error)),
on_finished=self._scan_ended)
self.set_busy(True)
def _scan_ended(self):
self.scan_task = None
self._finish()
self.set_busy(self.tasks.busy)
def _host_found(self, host):
if "__netbox__" in host:
self.netbox = host["__netbox__"]
if host["__note__"]:
self.netbox_note = host["__note__"]
return
row = dict(host, netbox=self.netbox.get(host["ip"], []))
row["compare"] = netscan.compare(row, row["netbox"]) if not self.netbox_note else ""
if row["alive"] or row["netbox"]:
self.rows[row["ip"]] = row
if not self.refresh_timer.isActive():
self.refresh_timer.start()
def _finish(self):
# Documented addresses that never answered are listed as "not reachable".
for ip, entries in self.netbox.items():
if ip not in self.rows:
self.rows[ip] = {"ip": ip, "alive": False, "netbox": entries, "compare": "offline"}
self._refresh()
def _refresh(self):
self.model.set_rows(list(self.rows.values()))
self._update_summary()
# ------------------------------------------------------------------
# Actions on hosts
# ------------------------------------------------------------------
def _selected(self):
rows = self.table.selectionModel().selectedRows()
return [self.proxy.row_at(index) for index in rows]
def _netbox_url(self, entry):
base = (self.state.profile or {}).get("netbox_url", "").rstrip("/")
return f"{base}/ipam/ip-addresses/{entry['id']}/" if base else entry.get("url")
def _open_default(self):
selected = self._selected()
if not selected:
return
row = selected[0]
ports = {item["port"] for item in row.get("ports", [])}
if ports & {443, 8443, 8006}:
port = min(ports & {443, 8443, 8006})
webbrowser.open(f"https://{row['ip']}" + ("" if port == 443 else f":{port}"))
elif ports & {80, 8080}:
port = min(ports & {80, 8080})
webbrowser.open(f"http://{row['ip']}" + ("" if port == 80 else f":{port}"))
elif 3389 in ports:
self._rdp(row)
elif 445 in ports:
os.startfile(f"\\\\{row['ip']}") # noqa: S606 - Windows Explorer
elif row.get("netbox"):
webbrowser.open(self._netbox_url(row["netbox"][0]))
@staticmethod
def _rdp(row):
subprocess.Popen(["mstsc", f"/v:{row['ip']}"]) # noqa: S603, S607 - user action
def _context_menu(self, position):
selected = self._selected()
if not selected:
return
row = selected[0]
ports = {item["port"] for item in row.get("ports", [])}
muted = theme.color("text_muted")
menu = QMenu(self)
for port, scheme in ((443, "https"), (8443, "https"), (8006, "https"), (80, "http"), (8080, "http")):
if port in ports:
suffix = "" if port in (80, 443) else f":{port}"
url = f"{scheme}://{row['ip']}{suffix}"
menu.addAction(icon("globe", muted), f"Im Browser öffnen ({url})", lambda u=url: webbrowser.open(u))
if 3389 in ports:
menu.addAction(icon("monitor", muted), "Remotedesktop verbinden", lambda: self._rdp(row))
if 445 in ports or 139 in ports:
menu.addAction(icon("folder", muted), "Freigaben öffnen",
lambda: os.startfile(f"\\\\{row['ip']}")) # noqa: S606
for entry in row.get("netbox", []):
menu.addAction(icon("upload", muted), f"In NetBox öffnen ({entry['object'] or entry['dns_name'] or 'IP'})",
lambda e=entry: webbrowser.open(self._netbox_url(e)))
if not menu.isEmpty():
menu.addSeparator()
clipboard = QGuiApplication.clipboard()
menu.addAction(icon("copy", muted), "IP-Adresse kopieren",
lambda: clipboard.setText("\n".join(item["ip"] for item in selected)))
if _name(row):
menu.addAction(icon("copy", muted), "Name kopieren", lambda: clipboard.setText(_name(row)))
if row.get("mac"):
menu.addAction(icon("copy", muted), "MAC-Adresse kopieren", lambda: clipboard.setText(row["mac"]))
menu.exec(self.table.viewport().mapToGlobal(position))
+17 -2
View File
@@ -81,6 +81,18 @@ class SettingsPage(Page):
"nicht auf einem anderen Rechner entschlüsselt werden.", muted=True, wrap=True))
self.body.addWidget(data)
updates = Card("Updates", "Neue Versionen kommen aus den Releases von Netbox-Import-Desktop (Gitea).")
line = QHBoxLayout()
self.auto_update = checkbox("Beim Start nach Updates suchen")
line.addWidget(self.auto_update)
line.addStretch(1)
line.addWidget(button("Jetzt nach Updates suchen", "refresh", on_click=lambda: window.updates.check()))
updates.add(line)
updates.add(label("Vor der Installation wird immer gefragt. Die installierte Version aktualisiert sich über "
"das Setup, die portable EXE tauscht sich selbst aus; danach startet die Anwendung neu.",
muted=True, wrap=True))
self.body.addWidget(updates)
about = Card("Über")
about.add(label(f"<b>{APP_NAME}</b> Version {APP_VERSION}"))
about.add(label(f"© {APP_PUBLISHER}", muted=True))
@@ -90,18 +102,21 @@ class SettingsPage(Page):
self.parallel.valueChanged.connect(lambda value: self.state.update_settings(parallel_ssh=value))
self.enable_lldp.toggled.connect(lambda value: self.state.update_settings(enable_lldp=value))
self.parallel_wmi.valueChanged.connect(lambda value: self.state.update_settings(parallel_wmi=value))
self.auto_update.toggled.connect(lambda value: self.state.update_settings(auto_update_check=value))
self.state.settings_changed.connect(self.load)
self.load()
def load(self):
settings = self.state.settings
for widget in (self.parallel, self.parallel_wmi, self.enable_lldp, *self.theme_buttons.values()):
widgets_ = (self.parallel, self.parallel_wmi, self.enable_lldp, self.auto_update, *self.theme_buttons.values())
for widget in widgets_:
widget.blockSignals(True)
self.parallel.setValue(int(settings.get("parallel_ssh", 4)))
self.parallel_wmi.setValue(int(settings.get("parallel_wmi", 8)))
self.enable_lldp.setChecked(bool(settings.get("enable_lldp")))
self.auto_update.setChecked(bool(settings.get("auto_update_check", True)))
self.theme_buttons.get(settings.get("theme", "system"), self.theme_buttons["system"]).setChecked(True)
for widget in (self.parallel, self.parallel_wmi, self.enable_lldp, *self.theme_buttons.values()):
for widget in widgets_:
widget.blockSignals(False)
def _set_theme(self, mode):
+3 -2
View File
@@ -4,7 +4,7 @@ import uuid
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QComboBox, QHBoxLayout, QMenu, QSplitter, QStackedWidget
from netbox_sync.core.switches import PLATFORMS, vlan_label
from netbox_sync.core.switches import PLATFORMS, ignored_vlans, vlan_label, without_vlans
from netbox_sync.ui import widgets
from netbox_sync.ui.dialogs import AddSwitchesDialog, RawDataDialog, SwitchDialog
from netbox_sync.ui.icons import icon
@@ -108,7 +108,8 @@ class SwitchesPage(Page):
dot=lambda row: "success" if row["connected"] else ("text_faint" if row["enabled"] else "danger")),
Column("speed", "Geschwindigkeit", 115, value=lambda row: _speed(row.get("speed_mbps")),
sort=lambda row: row.get("speed_mbps") or 0),
Column("vlans", "VLANs", 110, value=lambda row: vlan_label(row.get("vlans"))),
Column("vlans", "VLANs", 110, value=lambda row: vlan_label(without_vlans(
row.get("vlans"), ignored_vlans((self.state.profile or {}).get("vlan_map"))))),
Column("ips", "IP-Adressen", 160, value=lambda row: ", ".join(row.get("ip_addresses", []))),
Column("neighbor", "Nachbar", 170, value=lambda row: (row.get("neighbor") or {}).get("system_name", "")),
Column("remote_port", "Nachbar-Port", 110, value=lambda row: (row.get("neighbor") or {}).get("remote_port", "")),
+106
View File
@@ -0,0 +1,106 @@
"""Update check on start and on demand, download and installation."""
import tempfile
import webbrowser
from pathlib import Path
from PySide6.QtCore import QObject, QThreadPool, QTimer
from netbox_sync import APP_VERSION
from netbox_sync.core import updater
from netbox_sync.ui import widgets
from netbox_sync.ui.tasks import Task, logger
class UpdateManager(QObject):
def __init__(self, window):
super().__init__(window)
self.window = window
self.state = window.state
self.tasks = window.tasks
self._check = None
def check_on_start(self):
updater.remove_leftovers()
if self.state.settings.get("auto_update_check", True):
# A moment after start, so the window is usable right away.
QTimer.singleShot(4000, lambda: self.check(silent=True))
def check(self, silent=False):
"""Ask Gitea for a newer release without blocking other tasks."""
if self._check is not None:
return
task = Task(lambda _ctx: updater.check_for_update(), "app", "Nach Updates suchen")
self._check = task
def done(release):
if release is None:
logger("app").info("Keine neuere Version gefunden (installiert: %s)", APP_VERSION)
if not silent:
self.window.toast(f"{APP_VERSION} ist die aktuelle Version.", "info")
return
if silent and self.state.settings.get("skipped_version") == release["version"]:
return
self._offer(release)
def failed(error):
logger("app").warning("Update-Prüfung fehlgeschlagen: %s", error)
if not silent:
widgets.message(self.window, "Update-Prüfung fehlgeschlagen", str(error), "warning")
task.signals.succeeded.connect(done)
task.signals.failed.connect(failed)
task.signals.finished.connect(lambda: setattr(self, "_check", None))
QThreadPool.globalInstance().start(task)
def _offer(self, release):
kind = updater.install_kind()
asset = updater.pick_asset(release, kind) if kind else None
text = (f"Version {release['version']} ist verfügbar (installiert: {APP_VERSION}).\n\n"
+ ("Das Update wird heruntergeladen und installiert; die Anwendung startet danach neu."
if asset else "Für diese Installation gibt es keine passende Datei – bitte die Release-Seite "
"öffnen."))
buttons = ("Später", "Diese Version überspringen", "Jetzt aktualisieren" if asset else "Release-Seite öffnen")
choice = widgets.message(self.window, "Update verfügbar", text, "info", release["notes"] or None,
buttons=buttons, default=2)
if choice == 1:
self.state.update_settings(skipped_version=release["version"])
elif choice == 2 and asset:
self._install(release, kind, *asset)
elif choice == 2 and release["page"]:
webbrowser.open(release["page"])
def _install(self, release, kind, name, asset):
if self.tasks.busy:
widgets.message(self.window, "Bitte warten", f"„{self.tasks.current.title}“ läuft noch. Das Update "
"kann danach über Einstellungen › Updates gestartet werden.", "info")
return
if kind == "portable":
target = updater.portable_download_path()
else:
target = Path(tempfile.mkdtemp(prefix="netbox-sync-update-")) / name
def work(ctx):
ctx.log(f"Lade {name} ({release['version']}) herunter …")
def progress(done, total):
ctx.progress(done // 1024, max(total // 1024, 1), f"{done / 1_048_576:.1f} MB")
return updater.download(asset, target, progress, lambda: ctx.cancelled)
def downloaded(path):
try:
if kind == "portable":
updater.apply_portable(path)
else:
updater.apply_installer(path)
except OSError as error:
widgets.error(self.window, "Update fehlgeschlagen", f"Das Update konnte nicht gestartet werden: "
f"{error}")
return
logger("app").log(25, "Update auf %s wird installiert – Anwendung wird beendet", release["version"])
# After the task has finished, so closing does not ask about a running task.
QTimer.singleShot(0, self.window.close)
self.tasks.run(work, title=f"Update {release['version']} herunterladen", area="app",
on_success=downloaded,
on_error=lambda error: widgets.error(self.window, "Update fehlgeschlagen", str(error)))
+1 -1
View File
@@ -74,7 +74,7 @@ class FakeNetBox:
mac_addresses=Endpoint(), platforms=Endpoint(),
manufacturers=Endpoint(), device_types=Endpoint(), device_roles=Endpoint(),
sites=Endpoint())
self.ipam = SimpleNamespace(ip_addresses=Endpoint(), prefixes=Endpoint(), vrfs=Endpoint())
self.ipam = SimpleNamespace(ip_addresses=Endpoint(), prefixes=Endpoint(), vrfs=Endpoint(), vlans=Endpoint())
self.virtualization = SimpleNamespace(clusters=Endpoint(), cluster_types=Endpoint(), virtual_machines=Endpoint(),
interfaces=Endpoint())
self.tenancy = SimpleNamespace(tenants=Endpoint())
+87
View File
@@ -0,0 +1,87 @@
import ipaddress
import struct
from types import SimpleNamespace
import pytest
from fake_netbox import FakeNetBox, Record
from netbox_sync.core import netscan
def test_ports_and_ranges_are_parsed():
assert netscan.parse_ports("21-23, 80;443 80") == [21, 22, 23, 80, 443]
with pytest.raises(netscan.ScanError):
netscan.parse_ports("70000")
assert netscan.expand_ips("192.0.2.1-3, 192.0.2.2") == ["192.0.2.1", "192.0.2.2", "192.0.2.3"]
assert len(netscan.expand_ips("192.0.2.0/24")) == 254
with pytest.raises(netscan.ScanError):
netscan.expand_ips("10.0.0.0/16")
def _nbstat_answer(names, mac):
header = b"\x13\x37\x84\x00\x00\x00\x00\x01\x00\x00\x00\x00"
question = b"\x20" + b"CK" + b"A" * 30 + b"\x00" + b"\x00\x21\x00\x01"
entries = b"".join(name.ljust(15).encode() + bytes([suffix]) + struct.pack(">H", flags)
for name, suffix, flags in names)
body = bytes([len(names)]) + entries + mac
return header + question + b"\x00\x00\x00\x00" + struct.pack(">H", len(body)) + body
def test_netbios_answer_gives_name_workgroup_and_mac():
data = _nbstat_answer([("PC-042", 0x00, 0x0400), ("KDS", 0x00, 0x8400), ("PC-042", 0x20, 0x0400)],
bytes.fromhex("001122aabbcc"))
assert netscan.parse_nbstat(data) == ("PC-042", "KDS", "00:11:22:AA:BB:CC")
assert netscan.parse_nbstat(b"\x00" * 10) == ("", "", None)
def test_netbox_entries_are_found_per_block_and_compared():
nb = FakeNetBox()
nb.ipam.ip_addresses.records += [
Record(nb.ipam.ip_addresses, id=1, address="192.0.2.10/24", dns_name="srv01.example.local",
vrf=None, tenant=SimpleNamespace(id=7, name="Muster"), status=SimpleNamespace(label="Aktiv"),
description="", assigned_object=SimpleNamespace(virtual_machine=SimpleNamespace(name="SRV01"))),
Record(nb.ipam.ip_addresses, id=2, address="192.0.2.20/24", dns_name="", vrf=None, tenant=None,
status=SimpleNamespace(label="Aktiv"), description="",
assigned_object=SimpleNamespace(device=SimpleNamespace(name="drucker-3og"))),
Record(nb.ipam.ip_addresses, id=3, address="198.51.100.1/24", dns_name="", vrf=None, tenant=None,
status=None, description="", assigned_object=None),
]
queried = []
def by_parent(parent):
queried.append(parent)
network = ipaddress.ip_network(parent)
return [record for record in nb.ipam.ip_addresses.records
if ipaddress.ip_interface(record.address).ip in network]
nb.ipam.ip_addresses.filter = by_parent
found = netscan.netbox_lookup(nb, ["192.0.2.10", "192.0.2.20", "192.0.2.30"])
assert queried == ["192.0.2.0/24"], "one request per /24"
assert found["192.0.2.10"][0]["object"] == "SRV01" and found["192.0.2.10"][0]["object_kind"] == "VM"
assert found["192.0.2.20"][0]["object"] == "drucker-3og"
assert "192.0.2.30" not in found
alive = {"alive": True, "dns_name": "SRV01.example.local", "netbios_name": "SRV01"}
assert netscan.compare(alive, found["192.0.2.10"]) == "match"
assert netscan.compare(dict(alive, dns_name="pc99", netbios_name=""), found["192.0.2.20"]) == "differs"
assert netscan.compare(alive, []) == "missing"
assert netscan.compare({"alive": False}, found["192.0.2.20"]) == "offline"
assert netscan.compare({"alive": False}, []) == "unknown"
def test_unreachable_host_is_reported_without_details(monkeypatch):
monkeypatch.setattr(netscan, "ping", lambda *_args: None)
monkeypatch.setattr(netscan, "arp_mac", lambda _ip: None)
monkeypatch.setattr(netscan, "tcp_open", lambda *_args: False)
assert netscan.scan_host("192.0.2.1", [80]) == {"ip": "192.0.2.1", "alive": False}
def test_host_behind_firewall_is_found_by_port(monkeypatch):
monkeypatch.setattr(netscan, "ping", lambda *_args: None)
monkeypatch.setattr(netscan, "arp_mac", lambda _ip: None)
monkeypatch.setattr(netscan, "tcp_open", lambda _ip, port, _timeout=0: port in (445, 3389))
monkeypatch.setattr(netscan, "netbios", lambda _ip: ("PC-1", "KDS", "00:11:22:33:44:55"))
monkeypatch.setattr(netscan, "reverse_dns", lambda _ip: "pc-1.kds.local")
host = netscan.scan_host("192.0.2.5", [80, 445, 3389])
assert host["alive"] and [item["port"] for item in host["ports"]] == [445, 3389]
assert host["mac"] == "00:11:22:33:44:55" and host["netbios_name"] == "PC-1"
+156
View File
@@ -124,3 +124,159 @@ def test_plan_offers_tenant_group_devices_and_manual_neighbor_creates_cable():
report = sync_snapshot_to_netbox(nb, switch, snapshot)
cable = nb.dcim.cables.created[0]
assert cable["a_terminations"][0]["object_id"] == 2 and cable["b_terminations"][0]["object_id"] == 20
def test_missing_vlans_prefixes_and_vrfs_are_only_created_when_approved():
nb, switch, snapshot = _numbered_setup()
nb.ipam.vlans.records.append(Record(nb.ipam.vlans, id=110, vid=10, name="Server", tenant=SimpleNamespace(id=7)))
snapshot["interfaces"][2]["vlans"] = {"untagged": [1], "tagged": [10, 20], "tagged_all": False}
snapshot["interfaces"][0]["ip_addresses"] = ["10.1.0.1/24"]
snapshot["vlan_names"] = {20: "Clients"}
plan = plan_switch_sync(nb, switch, snapshot)
assert [(item["vid"], item["netbox_id"], item["method"], item["new_name"]) for item in plan["vlans"]] == [
(1, None, "new", "VLAN1"), (10, 110, "vid", "VLAN10"), (20, None, "new", "Clients")]
assert plan["networks"] == [{"network": "10.1.0.0/24", "vrf_id": 0, "vrf_name": "", "existing": [],
"create": True, "stored": False}]
# Not approved: nothing is created, only the existing VLAN 10 is assigned.
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
assert (report["vlans_created"], report["prefixes_created"], report["vrfs_created"]) == (0, 0, 0)
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert nb.ipam.vlans.created == [] and nb.ipam.prefixes.created == []
assert nb.dcim.interfaces.get(1).untagged_vlan == 110 and nb.dcim.interfaces.get(1).mode == "access"
assert nb.ipam.ip_addresses.created[0]["tenant"] == 7 and nb.ipam.ip_addresses.created[0]["vrf"] is None
switch.update({"vlan_map": {"20": {"action": "new", "name": "Clients"}}, "network_map": {"10.1.0.0/24": {"vrf_id": None, "vrf_name": "Kunde-Mgmt", "create": True}}})
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert report["errors"] == []
assert nb.ipam.vrfs.created == [{"name": "Kunde-Mgmt", "tenant": 7}]
vrf_id = nb.ipam.vrfs.records[0].id
assert nb.ipam.prefixes.created == [{"prefix": "10.1.0.0/24", "status": "active", "tenant": 7, "vrf": vrf_id}]
assert nb.ipam.vlans.created == [{"vid": 20, "name": "Clients", "status": "active", "tenant": 7}]
port = nb.dcim.interfaces.get(3)
assert port.mode == "tagged" and sorted(port.tagged_vlans) == sorted([110, nb.ipam.vlans.records[1].id])
def test_switch_without_tenant_is_refused():
nb, switch, snapshot = _numbered_setup()
nb.dcim.devices.get(1).tenant = None
assert "keinen Mandanten" in plan_switch_sync(nb, switch, snapshot)["error"]
report = sync_snapshot_to_netbox(nb, switch, snapshot)
assert "keinen Mandanten" in report["errors"][0] and nb.dcim.interfaces.updates == []
def test_vlan_names_are_parsed():
from netbox_sync.core.switches import parse_vlan_names
assert parse_vlan_names('vlan 10\n name "Server"\n exit\nvlan 20\n name Clients\n#\n') == {
10: "Server", 20: "Clients"}
def test_vlans_of_sibling_tenants_are_matched_by_vid_and_name():
nb, switch, snapshot = _numbered_setup()
group = SimpleNamespace(id=3, name="Kunde")
leo = SimpleNamespace(id=8, name="Leo")
nb.ipam.vlans.records += [
Record(nb.ipam.vlans, id=201, vid=2, name="Leo Server", tenant=leo, tenant_group=group),
Record(nb.ipam.vlans, id=202, vid=2, name="Gast", tenant=SimpleNamespace(id=9), tenant_group=group),
Record(nb.ipam.vlans, id=230, vid=30, name="Fremd", tenant=SimpleNamespace(id=99), tenant_group=None),
]
snapshot["interfaces"][0]["vlans"] = {"untagged": [2], "tagged": [], "tagged_all": False}
snapshot["vlan_names"] = {2: "Server_LEO", 30: "Drucker"}
plan = plan_switch_sync(nb, switch, snapshot)
by_vid = {item["vid"]: item for item in plan["vlans"]}
assert (by_vid[2]["netbox_id"], by_vid[2]["method"]) == (201, "name")
assert [candidate["id"] for candidate in by_vid[2]["candidates"]] == [202, 201]
assert by_vid[30]["method"] == "new", "VLANs outside the tenant group are never used"
switch["vlan_map"] = {"30": {"action": "new", "name": "Drucker-Netz"}, "20": {"action": "skip"}}
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert report["errors"] == []
assert nb.ipam.vlans.created == [{"vid": 30, "name": "Drucker-Netz", "status": "active", "tenant": 7}]
assert nb.dcim.interfaces.get(1).untagged_vlan == 201
assert getattr(nb.dcim.interfaces.get(2), "mode", None) is None, "skipped VLAN leaves the port alone"
def test_new_vlan_can_get_another_tenant_of_the_group():
nb, switch, snapshot = _numbered_setup()
group = SimpleNamespace(id=3, name="Kunde")
nb.tenancy.tenants.records.append(Record(nb.tenancy.tenants, id=8, name="Leo", group=group))
nb.tenancy.tenants.records.append(Record(nb.tenancy.tenants, id=9, name="Fremd", group=None))
plan = plan_switch_sync(nb, switch, snapshot)
assert [row["name"] for row in plan["tenants"]] == ["Leo", "Muster"]
assert {item["new_tenant"] for item in plan["vlans"]} == {7}
switch["vlan_map"] = {"10": {"action": "new", "name": "Leo Server", "tenant": 8}}
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert nb.ipam.vlans.created == [{"vid": 10, "name": "Leo Server", "status": "active", "tenant": 8}]
# NetBox resolves the tenant group through the tenant; the fake needs it set.
nb.ipam.vlans.records[-1].tenant_group = group
again = plan_switch_sync(nb, switch, snapshot)["vlans"][0]
assert (again["netbox_id"], again["method"]) == (nb.ipam.vlans.records[-1].id, "manual"), "never created twice"
def test_ignored_vlans_are_left_out_everywhere():
nb, switch, snapshot = _numbered_setup()
nb.ipam.vlans.records.append(Record(nb.ipam.vlans, id=110, vid=10, name="Server", tenant=SimpleNamespace(id=7)))
snapshot["interfaces"][0]["vlans"] = {"untagged": [10], "tagged": [20, 30], "tagged_all": False}
switch["vlan_map"] = {"20": {"action": "ignore"}, "30": {"action": "new", "name": "Drucker"}}
plan = plan_switch_sync(nb, switch, snapshot)
by_vid = {item["vid"]: item for item in plan["vlans"]}
assert (by_vid[20]["method"], by_vid[20]["stored"]) == ("ignore", True)
assert by_vid[10]["stored"] is False
assert {item["name"]: item["vlan_label"] for item in plan["interfaces"]}["1/1/1"] == "10,30"
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert report["errors"] == []
assert [payload["vid"] for payload in nb.ipam.vlans.created] == [30]
port = nb.dcim.interfaces.get(1)
assert port.label == "10,30" and port.tagged_vlans == [nb.ipam.vlans.records[-1].id]
def test_vlan_decisions_move_from_switches_to_the_profile(tmp_path):
from netbox_sync.core.config import ProfileStore
store = ProfileStore(tmp_path / "config.json")
profile = {"name": "Kunde", "switches": [{"id": "s", "name": "sw", "password": "x",
"vlan_map": {"5": {"action": "ignore"}}, "create_vlans": [6]}]}
store.save({"Kunde": profile}, "Kunde")
loaded = store.load()[0]["Kunde"]
assert loaded["vlan_map"] == {"5": {"action": "ignore"}}
assert "vlan_map" not in loaded["switches"][0] and "create_vlans" not in loaded["switches"][0]
def test_vrfs_of_the_tenant_group_are_offered_and_found():
nb, switch, snapshot = _numbered_setup()
group = SimpleNamespace(id=3, name="Kunde")
rz = SimpleNamespace(id=8, name="RZ")
nb.ipam.vrfs.records += [
Record(nb.ipam.vrfs, id=60, name="Mgmt", tenant=rz, tenant_group=group),
Record(nb.ipam.vrfs, id=61, name="Fremd", tenant=SimpleNamespace(id=99), tenant_group=None),
]
nb.ipam.prefixes.records.append(Record(nb.ipam.prefixes, id=70, prefix="10.10.167.0/24", vrf=SimpleNamespace(id=60)))
snapshot["interfaces"][0]["ip_addresses"] = ["10.10.167.5/24"]
plan = plan_switch_sync(nb, switch, snapshot)
assert plan["vrfs"] == [{"id": 60, "label": "Mgmt (RZ)"}], "group VRFs only"
assert plan["networks"][0] == {"network": "10.10.167.0/24", "vrf_id": 60, "vrf_name": "", "existing": [60],
"create": True, "stored": False}
switch["network_map"] = {"10.10.167.0/24": {"vrf_id": 60, "vrf_name": "", "create": False}}
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert report["errors"] == [] and report["prefixes_created"] == 0 and nb.ipam.vrfs.created == []
assert nb.ipam.ip_addresses.created[0]["vrf"] == 60
assert plan_switch_sync(nb, switch, snapshot)["networks"][0]["stored"] is True
def test_legacy_network_choices_still_work_and_migrate(tmp_path):
nb, switch, snapshot = _numbered_setup()
snapshot["interfaces"][0]["ip_addresses"] = ["10.1.0.1/24"]
switch.update({"network_vrfs": {"10.1.0.0/24": ""}, "create_prefixes": ["10.1.0.0/24"]})
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
assert report["prefixes_created"] == 1
from netbox_sync.core.config import ProfileStore
store = ProfileStore(tmp_path / "config.json")
store.save({"Kunde": {"name": "Kunde", "switches": [dict(switch, password="x")]}}, "Kunde")
loaded = store.load()[0]["Kunde"]
assert loaded["network_map"] == {"10.1.0.0/24": {"vrf_id": None, "vrf_name": "", "create": True}}
assert "network_vrfs" not in loaded["switches"][0]
+75
View File
@@ -0,0 +1,75 @@
import sys
import pytest
from netbox_sync.core import updater
RELEASE = {
"tag_name": "v4.7.0", "name": "Netbox-Import-Desktop v4.7.0", "body": "- neu", "draft": False,
"prerelease": False, "html_url": "https://example.invalid/releases/tag/v4.7.0",
"assets": [
{"name": "NetBox VM Import.exe", "size": 4, "browser_download_url": "https://example.invalid/portable"},
{"name": "NetBoxSynchronizer-Setup-4.7.0.exe", "size": 4, "browser_download_url": "https://example.invalid/setup"},
],
}
class _Response:
def __init__(self, payload=None, chunks=(), length=None):
self.payload, self.chunks = payload, chunks
self.headers = {"Content-Length": str(length)} if length else {}
def raise_for_status(self):
return None
def json(self):
return self.payload
def iter_content(self, _size):
return iter(self.chunks)
def __enter__(self):
return self
def __exit__(self, *_args):
return False
def test_versions_are_compared_numerically():
assert updater.parse_version("v4.10.0") > updater.parse_version("4.9.3")
assert updater.parse_version("v5") == (5, 0, 0)
def test_newer_release_is_offered_with_matching_assets(monkeypatch):
monkeypatch.setattr(updater.requests, "get", lambda *_a, **_k: _Response(RELEASE))
release = updater.check_for_update("4.6.0")
assert release["version"] == "4.7.0" and release["notes"] == "- neu"
assert updater.pick_asset(release, "portable")[0] == "NetBox VM Import.exe"
assert updater.pick_asset(release, "installer")[0] == "NetBoxSynchronizer-Setup-4.7.0.exe"
assert updater.check_for_update("4.7.0") is None
monkeypatch.setattr(updater.requests, "get", lambda *_a, **_k: _Response(dict(RELEASE, prerelease=True)))
assert updater.check_for_update("4.6.0") is None
def test_incomplete_download_is_discarded(monkeypatch, tmp_path):
monkeypatch.setattr(updater.requests, "get", lambda *_a, **_k: _Response(chunks=[b"ab"]))
with pytest.raises(updater.UpdateError):
updater.download({"url": "x", "size": 4}, tmp_path / "setup.exe")
assert list(tmp_path.iterdir()) == []
monkeypatch.setattr(updater.requests, "get", lambda *_a, **_k: _Response(chunks=[b"ab", b"cd"]))
target = updater.download({"url": "x", "size": 4}, tmp_path / "setup.exe")
assert target.read_bytes() == b"abcd"
def test_portable_exe_is_swapped_and_restarted(monkeypatch, tmp_path):
exe = tmp_path / "NetBox VM Import.exe"
exe.write_bytes(b"old")
new = tmp_path / "NetBox VM Import.new.exe"
new.write_bytes(b"new")
started = []
monkeypatch.setattr(sys, "executable", str(exe))
monkeypatch.setattr(updater.subprocess, "Popen", lambda args, **_kwargs: started.append(args))
updater.apply_portable(new)
assert exe.read_bytes() == b"new" and not new.exists()
assert (tmp_path / "NetBox VM Import.old.exe").read_bytes() == b"old"
assert started == [[str(exe)]]