Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f400795cb5 | ||
|
|
9ce25d820a | ||
|
|
8f20bcf795 | ||
|
|
1c0a8168ed |
No files matched your search
@@ -21,7 +21,7 @@ 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…8` navigation, `Ctrl+9` settings, `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
|
||||
@@ -86,6 +86,37 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
|
||||
- The switch configuration is only changed when "Enable LLDP if needed" is
|
||||
explicitly switched on
|
||||
|
||||
### Sophos access points (CSV from Sophos Central)
|
||||
|
||||
- Loads the access point export of Sophos Central (comma or semicolon, UTF-8 or
|
||||
Windows encoding) and checks it: missing site, duplicate IP, serial number or
|
||||
MAC address
|
||||
- Finds existing APs in NetBox globally by serial number and MAC address and by
|
||||
name within the tenant group; NetBox APs of the tenant group that are missing
|
||||
in the export are listed as "only in NetBox"
|
||||
- Sophos sites are mapped to NetBox sites of the tenant group (suggested by
|
||||
name, stored per profile); APs without a Sophos site get a site per AP
|
||||
- New APs are created with Sophos device type, role, site, serial number,
|
||||
firmware, interface with MAC and IP address (primary IPv4); existing ones get
|
||||
missing serial numbers and tenants, optionally the Sophos name. Tenant comes
|
||||
from the NetBox site, otherwise the selected tenant; devices of other tenants
|
||||
are never changed. Preview before writing
|
||||
|
||||
### 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,7 +3,7 @@
|
||||
|
||||
#define AppName "NetBox Synchronizer"
|
||||
#ifndef AppVersion
|
||||
#define AppVersion "4.7.0"
|
||||
#define AppVersion "4.9.0"
|
||||
#endif
|
||||
#define AppPublisher "Louis-Alexander Kerst"
|
||||
#define AppExeName "NetBoxSynchronizer.exe"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
|
||||
|
||||
APP_NAME = "NetBox Synchronizer"
|
||||
APP_VERSION = "4.7.0"
|
||||
APP_VERSION = "4.9.0"
|
||||
APP_PUBLISHER = "Louis-Alexander Kerst"
|
||||
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
|
||||
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
"""Sophos access points from a Sophos Central CSV export into NetBox.
|
||||
|
||||
Existing devices are found globally by serial number and MAC address and by
|
||||
name within the tenant group. Sites come from the Sophos "Current Site" column
|
||||
and are mapped to NetBox sites of the tenant group (remembered per profile).
|
||||
Every created object gets a tenant: the one of the NetBox site, otherwise the
|
||||
selected default tenant.
|
||||
"""
|
||||
|
||||
import csv
|
||||
import io
|
||||
import ipaddress
|
||||
import re
|
||||
|
||||
from netbox_sync.core.client_sync import ClientSyncEngine
|
||||
from netbox_sync.core.netbox import assign_mac, normalize_mac, related_id, uses_mac_objects
|
||||
|
||||
MANUFACTURER = "Sophos"
|
||||
PLATFORM = "Sophos AP"
|
||||
INTERFACE_NAME = "eth0"
|
||||
CHUNK = 50
|
||||
|
||||
COLUMNS = {
|
||||
"name": ("ap name", "name"),
|
||||
"mac": ("mac address", "mac"),
|
||||
"serial": ("serial number", "serial", "s/n"),
|
||||
"ip": ("internal ip address", "ip address", "ip"),
|
||||
"model": ("model",),
|
||||
"site_hint": ("current site", "site"),
|
||||
"firmware": ("firmware",),
|
||||
"config_status": ("config status",),
|
||||
}
|
||||
|
||||
|
||||
class APImportError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _compact(text):
|
||||
return re.sub(r"[^0-9a-z]", "", (text or "").casefold().replace("ä", "ae").replace("ö", "oe")
|
||||
.replace("ü", "ue").replace("ß", "ss"))
|
||||
|
||||
|
||||
def parse_csv(data):
|
||||
"""Access points from a Sophos Central export (bytes or text)."""
|
||||
if isinstance(data, bytes):
|
||||
for encoding in ("utf-8-sig", "cp1252"):
|
||||
try:
|
||||
data = data.decode(encoding)
|
||||
break
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
data = data.lstrip("")
|
||||
try:
|
||||
dialect = csv.Sniffer().sniff(data[:4096], delimiters=",;\t")
|
||||
except csv.Error:
|
||||
dialect = csv.excel
|
||||
reader = csv.reader(io.StringIO(data), dialect)
|
||||
header = [cell.strip().casefold() for cell in next(reader, [])]
|
||||
index = {}
|
||||
for key, names in COLUMNS.items():
|
||||
index[key] = next((header.index(name) for name in names if name in header), None)
|
||||
if index["name"] is None or (index["serial"] is None and index["mac"] is None):
|
||||
raise APImportError("Die Datei sieht nicht wie ein Sophos-AP-Export aus (Spalten „AP Name“ und "
|
||||
"„Serial Number“ bzw. „MAC Address“ fehlen).")
|
||||
aps = []
|
||||
for row in reader:
|
||||
if not any(cell.strip() for cell in row):
|
||||
continue
|
||||
|
||||
def cell(key):
|
||||
position = index[key]
|
||||
return row[position].strip() if position is not None and position < len(row) else ""
|
||||
ip = cell("ip")
|
||||
try:
|
||||
ip = str(ipaddress.ip_address(ip)) if ip else ""
|
||||
except ValueError:
|
||||
ip = ""
|
||||
aps.append({
|
||||
"name": re.sub(r"\s+", " ", cell("name")).strip(),
|
||||
"mac": normalize_mac(cell("mac")) or "",
|
||||
"serial": cell("serial").upper(),
|
||||
"ip": ip,
|
||||
"model": cell("model"),
|
||||
"site_hint": re.sub(r"\s+", " ", cell("site_hint")).strip(),
|
||||
"firmware": cell("firmware"),
|
||||
"config_status": cell("config_status"),
|
||||
})
|
||||
if not aps:
|
||||
raise APImportError("Die Datei enthält keine Access Points.")
|
||||
_mark_duplicates(aps)
|
||||
return aps
|
||||
|
||||
|
||||
def _mark_duplicates(aps):
|
||||
for ap in aps:
|
||||
ap["issues"] = []
|
||||
if not ap["site_hint"]:
|
||||
ap["issues"].append("kein Standort in Sophos")
|
||||
for key, text in (("ip", "IP-Adresse"), ("serial", "Seriennummer"), ("mac", "MAC-Adresse")):
|
||||
groups = {}
|
||||
for ap in aps:
|
||||
if ap[key]:
|
||||
groups.setdefault(ap[key], []).append(ap)
|
||||
for value, members in groups.items():
|
||||
if len(members) > 1:
|
||||
for ap in members:
|
||||
others = ", ".join(other["name"] for other in members if other is not ap)
|
||||
ap["issues"].append(f"{text} {value} doppelt (auch {others})")
|
||||
|
||||
|
||||
def ap_key(ap):
|
||||
"""Stable key of an AP for remembered choices."""
|
||||
return ap["serial"] or ap["mac"] or ap["name"]
|
||||
|
||||
|
||||
class APSyncEngine(ClientSyncEngine):
|
||||
"""Reuses the manufacturer/device type/platform helpers of the client import."""
|
||||
|
||||
def __init__(self, nb, log=None):
|
||||
super().__init__(nb, log or (lambda *_args, **_kwargs: None))
|
||||
self.tenant_id = None
|
||||
self.tenant_ids = set()
|
||||
self.ap_sites = []
|
||||
self.netbox_aps = []
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Context
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def load_context(self, tenant_id):
|
||||
"""Sites and existing Sophos devices of the tenant's tenant group."""
|
||||
self.tenant_id = tenant_id
|
||||
tenant = self.nb.tenancy.tenants.get(tenant_id)
|
||||
if tenant is None:
|
||||
raise APImportError(f"Mandant #{tenant_id} existiert nicht.")
|
||||
group_id = related_id(tenant, "group")
|
||||
scope = {"tenant_group_id": group_id} if group_id else {"tenant_id": tenant_id}
|
||||
self.tenant_ids = {tenant_id}
|
||||
if group_id:
|
||||
self.tenant_ids |= {item.id for item in self.nb.tenancy.tenants.filter(group_id=group_id)}
|
||||
tenants = {item.id: item.name for item in self.nb.tenancy.tenants.all()} if group_id else {tenant_id: tenant.name}
|
||||
self.ap_sites = sorted(({"id": site.id, "name": site.name, "tenant_id": related_id(site, "tenant"),
|
||||
"tenant": tenants.get(related_id(site, "tenant"), "")}
|
||||
for site in self.nb.dcim.sites.filter(**scope)), key=lambda row: row["name"].casefold())
|
||||
self.roles = sorted(((item.name, item.id) for item in self.nb.dcim.device_roles.all()),
|
||||
key=lambda pair: pair[0].casefold())
|
||||
manufacturer = (self.nb.dcim.manufacturers.get(slug="sophos")
|
||||
or next(iter(self.nb.dcim.manufacturers.filter(name__ie=MANUFACTURER)), None))
|
||||
self.netbox_aps = list(self.nb.dcim.devices.filter(manufacturer_id=manufacturer.id, **scope)) \
|
||||
if manufacturer else []
|
||||
return self.ap_sites
|
||||
|
||||
def suggest_site(self, hint):
|
||||
"""NetBox site for a Sophos site name, or ``None`` when unclear."""
|
||||
wanted = _compact(hint)
|
||||
if not wanted:
|
||||
return None
|
||||
exact = [site for site in self.ap_sites if _compact(site["name"]) == wanted]
|
||||
if len(exact) == 1:
|
||||
return exact[0]["id"]
|
||||
partial = [site for site in self.ap_sites
|
||||
if wanted in _compact(site["name"]) or (_compact(site["name"]) and _compact(site["name"]) in wanted)]
|
||||
return partial[0]["id"] if len(partial) == 1 else None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Matching
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _devices_by(self, field, values):
|
||||
found = {}
|
||||
values = sorted(set(filter(None, values)))
|
||||
for start in range(0, len(values), CHUNK):
|
||||
for device in self.nb.dcim.devices.filter(**{field: values[start:start + CHUNK]}):
|
||||
key = str(getattr(device, field, "") or "").upper()
|
||||
found.setdefault(key, []).append(device)
|
||||
return found
|
||||
|
||||
def _devices_by_mac(self, macs):
|
||||
found = {}
|
||||
macs = sorted(set(filter(None, macs)))
|
||||
for start in range(0, len(macs), CHUNK):
|
||||
chunk = macs[start:start + CHUNK]
|
||||
if uses_mac_objects(self.nb):
|
||||
records = self.nb.dcim.mac_addresses.filter(mac_address=chunk, assigned_object_type="dcim.interface")
|
||||
pairs = [(record.mac_address, related_id(getattr(record, "assigned_object", None), "device"))
|
||||
for record in records]
|
||||
else:
|
||||
pairs = [(record.mac_address, related_id(record, "device"))
|
||||
for record in self.nb.dcim.interfaces.filter(mac_address=chunk)]
|
||||
for mac, device_id in pairs:
|
||||
if device_id:
|
||||
found.setdefault(normalize_mac(mac), set()).add(device_id)
|
||||
return found
|
||||
|
||||
def match(self, aps):
|
||||
"""Attach ``device``/``method`` to every AP and return NetBox APs missing in Sophos."""
|
||||
by_serial = self._devices_by("serial", [ap["serial"] for ap in aps])
|
||||
by_mac = self._devices_by_mac([ap["mac"] for ap in aps])
|
||||
by_name = {}
|
||||
for device in self.netbox_aps:
|
||||
by_name.setdefault(_compact(device.name), []).append(device)
|
||||
cache = {device.id: device for device in self.netbox_aps}
|
||||
for devices in by_serial.values():
|
||||
cache.update({device.id: device for device in devices})
|
||||
matched = set()
|
||||
for ap in aps:
|
||||
device, method = None, ""
|
||||
candidates = by_serial.get(ap["serial"], []) if ap["serial"] else []
|
||||
if len(candidates) == 1:
|
||||
device, method = candidates[0], "Seriennummer"
|
||||
elif len(candidates) > 1:
|
||||
ap["issues"].append(f"Seriennummer in NetBox {len(candidates)}× vergeben")
|
||||
if device is None and ap["mac"] and len(by_mac.get(ap["mac"], ())) == 1:
|
||||
device_id = next(iter(by_mac[ap["mac"]]))
|
||||
device = cache.get(device_id) or self.nb.dcim.devices.get(device_id)
|
||||
method = "MAC-Adresse"
|
||||
if device is None and len(by_name.get(_compact(ap["name"]), [])) == 1:
|
||||
device, method = by_name[_compact(ap["name"])][0], "Name"
|
||||
ap["device"], ap["method"] = device, method
|
||||
if device is not None:
|
||||
matched.add(device.id)
|
||||
tenant = related_id(device, "tenant")
|
||||
if tenant not in self.tenant_ids:
|
||||
ap["issues"].append("NetBox-Gerät gehört " + (
|
||||
f"Mandant „{getattr(device.tenant, 'name', tenant)}“ außerhalb der Mandantengruppe"
|
||||
if tenant else "keinem Mandanten"))
|
||||
if ap["serial"] and getattr(device, "serial", "") and device.serial.upper() != ap["serial"]:
|
||||
ap["issues"].append(f"Seriennummer in NetBox abweichend ({device.serial})")
|
||||
return [device for device in self.netbox_aps if device.id not in matched]
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Sync
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _site_tenant(self, site_id):
|
||||
site = next((row for row in self.ap_sites if row["id"] == site_id), None)
|
||||
return (site or {}).get("tenant_id") or self.tenant_id
|
||||
|
||||
def sync(self, aps, sites, role_id, rename=True, dry_run=True):
|
||||
"""``sites`` maps ``ap_key`` to the NetBox site ID for new devices."""
|
||||
report = self.new_report()
|
||||
self._planned = set()
|
||||
for ap in aps:
|
||||
try:
|
||||
changes = self._sync_ap(ap, sites.get(ap_key(ap)), role_id, rename, dry_run, report)
|
||||
except Exception as error: # noqa: BLE001 - one AP must not stop the others
|
||||
report["errors"].append(f"{ap['name']}: {error}")
|
||||
changes = [f"Fehler: {error}"]
|
||||
report["items"].append((ap["name"], changes))
|
||||
return report
|
||||
|
||||
def _sync_ap(self, ap, site_id, role_id, rename, dry_run, report):
|
||||
device = ap.get("device")
|
||||
changes = []
|
||||
description = f"Firmware {ap['firmware']}" if ap["firmware"] else ""
|
||||
if device is not None:
|
||||
tenant = related_id(device, "tenant")
|
||||
if tenant is not None and tenant not in self.tenant_ids:
|
||||
report["devices_unchanged"] += 1
|
||||
return ["Übersprungen – Gerät gehört einem Mandanten außerhalb der Mandantengruppe"]
|
||||
updates = {}
|
||||
if rename and ap["name"] and device.name != ap["name"]:
|
||||
updates["name"] = ap["name"]
|
||||
if ap["serial"] and not getattr(device, "serial", ""):
|
||||
updates["serial"] = ap["serial"]
|
||||
if tenant is None:
|
||||
updates["tenant"] = self._site_tenant(related_id(device, "site"))
|
||||
if description and (getattr(device, "description", "") or "").startswith("Firmware") \
|
||||
and device.description != description:
|
||||
updates["description"] = description
|
||||
if updates:
|
||||
report["devices_updated"] += 1
|
||||
changes.append("Aktualisieren: " + ", ".join(
|
||||
f"{key} → {value}" for key, value in updates.items() if key != "tenant")
|
||||
+ (" (Mandant ergänzt)" if "tenant" in updates else ""))
|
||||
if not dry_run:
|
||||
device.update(updates)
|
||||
else:
|
||||
report["devices_unchanged"] += 1
|
||||
changes.append(f"Vorhanden – gefunden über {ap['method']}")
|
||||
tenant_id = tenant or self._site_tenant(related_id(device, "site"))
|
||||
else:
|
||||
if not site_id:
|
||||
raise APImportError("kein NetBox-Standort zugeordnet")
|
||||
if not role_id:
|
||||
raise APImportError("keine Geräterolle gewählt")
|
||||
manufacturer_id = self._manufacturer(MANUFACTURER, report, dry_run)
|
||||
type_id = self._device_type(MANUFACTURER, manufacturer_id, ap["model"] or "Access Point", report, dry_run)
|
||||
platform_id = self._platform(PLATFORM, report, dry_run)
|
||||
tenant_id = self._site_tenant(site_id)
|
||||
payload = {"name": ap["name"], "device_type": type_id, "role": role_id, "site": site_id,
|
||||
"tenant": tenant_id, "status": "active", "platform": platform_id}
|
||||
if ap["serial"]:
|
||||
payload["serial"] = ap["serial"]
|
||||
if description:
|
||||
payload["description"] = description
|
||||
report["devices_created"] += 1
|
||||
changes.append(f"Gerät anlegen ({ap['model'] or 'Access Point'})")
|
||||
if dry_run:
|
||||
if ap["mac"] or ap["ip"]:
|
||||
report["interfaces_created"] += 1
|
||||
changes.append(f"Schnittstelle {INTERFACE_NAME} anlegen" + (f" mit MAC {ap['mac']}" if ap["mac"]
|
||||
else ""))
|
||||
if ap["ip"]:
|
||||
report["ips_created"] += 1
|
||||
changes.append(f"IP-Adresse {ap['ip']} anlegen")
|
||||
return changes
|
||||
device = self.nb.dcim.devices.create(payload)
|
||||
if dry_run and device is None:
|
||||
return changes
|
||||
changes += self._sync_network(device, ap, tenant_id, dry_run, report)
|
||||
return changes
|
||||
|
||||
def _interface(self, device, ap, dry_run, report):
|
||||
interfaces = list(self.nb.dcim.interfaces.filter(device_id=device.id))
|
||||
if ap["mac"]:
|
||||
for interface in interfaces:
|
||||
if normalize_mac(getattr(interface, "mac_address", None)) == ap["mac"]:
|
||||
return interface, []
|
||||
named = next((item for item in interfaces if item.name == INTERFACE_NAME), None)
|
||||
if named or interfaces:
|
||||
return named or interfaces[0], []
|
||||
report["interfaces_created"] += 1
|
||||
if dry_run:
|
||||
return None, [f"Schnittstelle {INTERFACE_NAME} anlegen"]
|
||||
interface = self.nb.dcim.interfaces.create({"device": device.id, "name": INTERFACE_NAME, "type": "1000base-t"})
|
||||
return interface, [f"Schnittstelle {INTERFACE_NAME} anlegen"]
|
||||
|
||||
def _sync_network(self, device, ap, tenant_id, dry_run, report):
|
||||
if not ap["mac"] and not ap["ip"]:
|
||||
return []
|
||||
interface, changes = self._interface(device, ap, dry_run, report)
|
||||
if ap["mac"] and interface is not None and not dry_run:
|
||||
if assign_mac(self.nb, interface, ap["mac"], "dcim.interface"):
|
||||
changes.append(f"MAC {ap['mac']} zugeordnet")
|
||||
if not ap["ip"]:
|
||||
return changes
|
||||
prefix = next(iter(self.nb.ipam.prefixes.filter(contains=ap["ip"], vrf_id="null")), None)
|
||||
length = str(getattr(prefix, "prefix", "")).split("/")[-1] if prefix else "32"
|
||||
address = f"{ap['ip']}/{length}"
|
||||
existing = list(self.nb.ipam.ip_addresses.filter(address=ap["ip"], vrf_id="null"))
|
||||
if existing:
|
||||
ip = existing[0]
|
||||
assigned = getattr(ip, "assigned_object_id", None)
|
||||
if interface is not None and assigned == interface.id:
|
||||
pass
|
||||
elif assigned:
|
||||
changes.append(f"IP-Adresse {ap['ip']} ist bereits einem anderen Objekt zugeordnet – übersprungen")
|
||||
return changes
|
||||
else:
|
||||
changes.append(f"IP-Adresse {ap['ip']} zuordnen")
|
||||
if not dry_run and interface is not None:
|
||||
ip.update({"assigned_object_type": "dcim.interface", "assigned_object_id": interface.id,
|
||||
"tenant": related_id(ip, "tenant") or tenant_id})
|
||||
else:
|
||||
report["ips_created"] += 1
|
||||
changes.append(f"IP-Adresse {address} anlegen")
|
||||
if dry_run or interface is None:
|
||||
return changes
|
||||
ip = self.nb.ipam.ip_addresses.create({
|
||||
"address": address, "status": "active", "tenant": tenant_id,
|
||||
"assigned_object_type": "dcim.interface", "assigned_object_id": interface.id,
|
||||
})
|
||||
if not dry_run and related_id(device, "primary_ip4") != ip.id:
|
||||
device.update({"primary_ip4": ip.id})
|
||||
changes.append(f"Primäre IP {ap['ip']}")
|
||||
return changes
|
||||
@@ -23,6 +23,8 @@ DEFAULT_SETTINGS = {
|
||||
"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__)
|
||||
@@ -122,6 +124,9 @@ def empty_profile(name):
|
||||
"vlan_map": {},
|
||||
# Switch network decisions: "<network>" -> {"vrf_id", "vrf_name" (new VRF), "create": prefix}.
|
||||
"network_map": {},
|
||||
# Sophos AP import: tenant, role, rename option and site choices
|
||||
# ("site_map": Sophos site -> NetBox site ID, "ap_sites": AP key -> NetBox site ID).
|
||||
"access_points": {},
|
||||
# Windows client scan: targets and options, never a password.
|
||||
"clients": dict(DEFAULT_CLIENT_OPTIONS),
|
||||
}
|
||||
@@ -172,6 +177,7 @@ class ProfileStore:
|
||||
"host_map": dict(record.get("host_map", {})),
|
||||
"vlan_map": dict(record.get("vlan_map", {})),
|
||||
"network_map": dict(record.get("network_map", {})),
|
||||
"access_points": dict(record.get("access_points", {})),
|
||||
"clients": {**DEFAULT_CLIENT_OPTIONS, **{key: value for key, value in record.get("clients", {}).items()
|
||||
if key in DEFAULT_CLIENT_OPTIONS}},
|
||||
})
|
||||
@@ -247,6 +253,7 @@ class ProfileStore:
|
||||
"host_map": dict(profile.get("host_map", {})),
|
||||
"vlan_map": dict(profile.get("vlan_map", {})),
|
||||
"network_map": dict(profile.get("network_map", {})),
|
||||
"access_points": dict(profile.get("access_points", {})),
|
||||
"clients": dict(profile.get("clients", DEFAULT_CLIENT_OPTIONS)),
|
||||
})
|
||||
|
||||
|
||||
@@ -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": "…",
|
||||
}
|
||||
@@ -26,6 +26,8 @@ _PATHS = {
|
||||
"plus": '<path d="M5 12h14"/><path d="M12 5v14"/>',
|
||||
"pencil": '<path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/>',
|
||||
"trash": '<path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/>',
|
||||
"wifi": '<path d="M12 20h.01"/><path d="M2 8.82a15 15 0 0 1 20 0"/><path d="M5 12.86a10 10 0 0 1 14 0"/>'
|
||||
'<path d="M8.5 16.43a5 5 0 0 1 7 0"/>',
|
||||
"refresh": '<path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/>'
|
||||
'<path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/>',
|
||||
"play": '<polygon points="6 3 20 12 6 21 6 3"/>',
|
||||
|
||||
@@ -23,11 +23,13 @@ from netbox_sync.ui import widgets
|
||||
from netbox_sync.ui.actions import Actions
|
||||
from netbox_sync.ui.dialogs import ask_text
|
||||
from netbox_sync.ui.icons import icon
|
||||
from netbox_sync.ui.pages.access_points import AccessPointsPage
|
||||
from netbox_sync.ui.pages.clients import ClientsPage
|
||||
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
|
||||
@@ -44,7 +46,9 @@ NAVIGATION = (
|
||||
("vms", "Virtuelle Maschinen", "server"),
|
||||
("switches", "Switche", "network"),
|
||||
("clients", "Windows-Clients", "monitor"),
|
||||
("aps", "Access Points", "wifi"),
|
||||
("ipam", "VRFs && Netze", "globe"),
|
||||
("scanner", "Netzwerk-Scanner", "search"),
|
||||
("log", "Protokoll", "list"),
|
||||
)
|
||||
|
||||
@@ -104,7 +108,9 @@ 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), ("aps", AccessPointsPage),
|
||||
("ipam", IpamPage), ("scanner", ScannerPage),
|
||||
("log", LogPage),
|
||||
("settings", SettingsPage)):
|
||||
page = page_class(self)
|
||||
self.pages[key] = page
|
||||
@@ -122,7 +128,7 @@ class MainWindow(QMainWindow):
|
||||
self.state.save_failed.connect(lambda text: self.toast(f"Speichern fehlgeschlagen: {text}", "error", 8000))
|
||||
theme.changed.connect(self._theme_changed)
|
||||
|
||||
for index, (key, _title, _icon) in enumerate((*NAVIGATION, ("settings", "", ""))):
|
||||
for index, (key, _title, _icon) in enumerate((*NAVIGATION[:8], ("settings", "", ""))):
|
||||
QShortcut(QKeySequence(f"Ctrl+{index + 1}"), self, activated=lambda k=key: self.navigate(k))
|
||||
QShortcut(QKeySequence("F5"), self, activated=self._reload_current)
|
||||
QShortcut(QKeySequence("Ctrl+F"), self, activated=self._focus_search)
|
||||
@@ -273,6 +279,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)
|
||||
@@ -363,7 +371,7 @@ class MainWindow(QMainWindow):
|
||||
has_profile = self.state.profile is not None
|
||||
for key in ("duplicate", "rename", "delete"):
|
||||
self.profile_actions[key].setEnabled(has_profile)
|
||||
for key in ("connections", "vms", "switches", "clients", "ipam"):
|
||||
for key in ("connections", "vms", "switches", "clients", "aps", "ipam"):
|
||||
self.nav_buttons[key].setEnabled(has_profile)
|
||||
self.setWindowTitle(f"{self.state.active} – {APP_NAME}" if has_profile else APP_NAME)
|
||||
self._refresh_netbox_pill()
|
||||
|
||||
@@ -0,0 +1,420 @@
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import Qt, QTimer
|
||||
from PySide6.QtWidgets import (
|
||||
QFileDialog,
|
||||
QFormLayout,
|
||||
QHBoxLayout,
|
||||
QStackedWidget,
|
||||
QTableWidget,
|
||||
QTableWidgetItem,
|
||||
)
|
||||
|
||||
from netbox_sync.core.ap_sync import APImportError, APSyncEngine, ap_key, parse_csv
|
||||
from netbox_sync.core.netbox import related_id
|
||||
from netbox_sync.ui import widgets
|
||||
from netbox_sync.ui.client_dialogs import ClientPreviewDialog
|
||||
from netbox_sync.ui.dialogs import _Dialog
|
||||
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.widgets import (
|
||||
Card,
|
||||
EmptyState,
|
||||
SearchableComboBox,
|
||||
SearchField,
|
||||
Table,
|
||||
button,
|
||||
checkbox,
|
||||
form_dialog_buttons,
|
||||
label,
|
||||
)
|
||||
|
||||
STATE_TEXT = {"new": "neu", "known": "in NetBox", "check": "prüfen", "netbox_only": "nur in NetBox"}
|
||||
STATE_DOT = {"new": "accent", "known": "success", "check": "warning", "netbox_only": "text_faint"}
|
||||
ROLE_HINTS = ("access point", "accesspoint", "access-point", "wlan", "wifi", "ap")
|
||||
|
||||
|
||||
class SiteMappingDialog(_Dialog):
|
||||
"""Assign NetBox sites to Sophos sites and to APs without a Sophos site."""
|
||||
|
||||
def __init__(self, parent, hints, homeless, sites, site_map, ap_sites):
|
||||
super().__init__(parent, "Standorte zuordnen",
|
||||
"Neue Access Points werden am zugeordneten NetBox-Standort angelegt und erhalten dessen "
|
||||
"Mandanten. Zur Auswahl stehen die Standorte der Mandantengruppe.", width=760)
|
||||
self.resize(860, 620)
|
||||
items = [("– nicht zugeordnet –", 0)] + [
|
||||
(f"{site['name']}" + (f" ({site['tenant']})" if site["tenant"] else ""), site["id"]) for site in sites]
|
||||
self.table = QTableWidget(0, 3)
|
||||
self.table.setHorizontalHeaderLabels(["Sophos-Standort / Access Point", "APs", "NetBox-Standort"])
|
||||
self.rows = []
|
||||
for hint, count, suggestion in hints:
|
||||
self._row(hint, str(count), items, site_map.get(hint) or suggestion or 0, ("site", hint))
|
||||
for ap in homeless:
|
||||
self._row(f"{ap['name']} (ohne Sophos-Standort)", "1", items, ap_sites.get(ap_key(ap)) or 0,
|
||||
("ap", ap_key(ap)))
|
||||
self.table.verticalHeader().hide()
|
||||
self.table.verticalHeader().setDefaultSectionSize(42)
|
||||
self.table.setEditTriggers(QTableWidget.NoEditTriggers)
|
||||
self.table.setSelectionMode(QTableWidget.NoSelection)
|
||||
self.table.horizontalHeader().setStretchLastSection(True)
|
||||
for column, width in enumerate((330, 50, 360)):
|
||||
self.table.setColumnWidth(column, width)
|
||||
self.root.addWidget(self.table, 1)
|
||||
buttons, _ok = form_dialog_buttons(self, "Übernehmen")
|
||||
self.root.addWidget(buttons)
|
||||
self.site_map, self.ap_sites = dict(site_map), dict(ap_sites)
|
||||
|
||||
def _row(self, text, count, items, current, key):
|
||||
row = self.table.rowCount()
|
||||
self.table.insertRow(row)
|
||||
self.table.setItem(row, 0, QTableWidgetItem(text))
|
||||
self.table.setItem(row, 1, QTableWidgetItem(count))
|
||||
combo = SearchableComboBox("Standort suchen …")
|
||||
combo.set_items(items, current)
|
||||
self.table.setCellWidget(row, 2, combo)
|
||||
self.rows.append((key, combo))
|
||||
|
||||
def accept(self):
|
||||
for (kind, key), combo in self.rows:
|
||||
target = self.site_map if kind == "site" else self.ap_sites
|
||||
value = combo.valid_data()
|
||||
if value:
|
||||
target[key] = value
|
||||
else:
|
||||
target.pop(key, None)
|
||||
super().accept()
|
||||
|
||||
|
||||
class AccessPointsPage(Page):
|
||||
title = "Access Points"
|
||||
subtitle = ("Sophos-APs aus einem Export von Sophos Central laden, mit NetBox abgleichen (global über "
|
||||
"Seriennummer und MAC, im Mandanten über den Namen) und fehlende anlegen.")
|
||||
|
||||
def __init__(self, window):
|
||||
super().__init__(window)
|
||||
self.aps = []
|
||||
self.only_netbox = []
|
||||
self.engine = None
|
||||
self.tenants = []
|
||||
self.file_name = ""
|
||||
|
||||
source = Card("Sophos-Export", "In Sophos Central: Wireless › Access Points › Exportieren (CSV).")
|
||||
self.load_button = source.add_action(button("CSV laden …", "folder", on_click=self.load_file))
|
||||
self.sync_button = source.add_action(button("Nach NetBox übertragen …", "upload", "primary",
|
||||
on_click=self.sync))
|
||||
form = QFormLayout()
|
||||
form.setHorizontalSpacing(18)
|
||||
tenant_row = QHBoxLayout()
|
||||
self.tenant = SearchableComboBox("Mandant wählen …")
|
||||
self.tenant.setMinimumWidth(320)
|
||||
tenant_row.addWidget(self.tenant)
|
||||
self.tenant_hint = label("Standorte und vorhandene APs werden in seiner Mandantengruppe gesucht.", muted=True)
|
||||
tenant_row.addWidget(self.tenant_hint, 1)
|
||||
form.addRow("Mandant *", tenant_row)
|
||||
self.role = SearchableComboBox("Geräterolle wählen …")
|
||||
self.role.setMinimumWidth(320)
|
||||
form.addRow("Geräterolle", self.role)
|
||||
self.rename = checkbox("Namen vorhandener Geräte aus Sophos übernehmen", True)
|
||||
form.addRow("", self.rename)
|
||||
source.add(form)
|
||||
self.body.addWidget(source)
|
||||
|
||||
result = Card("Abgleich")
|
||||
self.sites_button = result.add_action(button("Standorte zuordnen …", "globe", on_click=self.map_sites))
|
||||
self.refresh_button = result.add_action(button("Neu abgleichen", "refresh", on_click=self.compare))
|
||||
filters = QHBoxLayout()
|
||||
self.search = SearchField("Name, S/N, MAC, IP, Standort …")
|
||||
self.only_open = checkbox("Nur neue und zu prüfende")
|
||||
filters.addWidget(self.search, 2)
|
||||
filters.addWidget(self.only_open)
|
||||
filters.addStretch(1)
|
||||
result.add(filters)
|
||||
columns = [
|
||||
Column("state", "Status", 110, value=lambda row: STATE_TEXT.get(row["state"], ""),
|
||||
dot=lambda row: "warning" if row.get("issues") and row["state"] == "new"
|
||||
else STATE_DOT.get(row["state"]), tooltip=lambda row: "\n".join(row.get("issues", []))),
|
||||
Column("name", "Name", 230),
|
||||
Column("model", "Modell", 80),
|
||||
Column("serial", "Seriennummer", 140),
|
||||
Column("mac", "MAC-Adresse", 135),
|
||||
Column("ip", "IP-Adresse", 110),
|
||||
Column("site_hint", "Sophos-Standort", 170),
|
||||
Column("netbox_site", "NetBox-Standort", 190,
|
||||
color=lambda row: "warning" if row["state"] == "new" and not row.get("site_id") else None),
|
||||
Column("netbox_device", "NetBox-Gerät", 170),
|
||||
Column("method", "Gefunden über", 110, color=lambda row: "text_muted"),
|
||||
Column("issues", "Hinweise", 260, value=lambda row: "; ".join(row.get("issues", [])),
|
||||
color=lambda row: "warning"),
|
||||
]
|
||||
self.model = RowTableModel(columns, row_id=lambda row: row["key"])
|
||||
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.stack = QStackedWidget()
|
||||
self.stack.addWidget(EmptyState("upload", "Noch kein Export geladen",
|
||||
"Die CSV-Datei aus Sophos Central laden. Danach wird automatisch mit NetBox "
|
||||
"abgeglichen – geschrieben wird erst nach der Vorschau.",
|
||||
"CSV laden …", self.load_file))
|
||||
self.stack.addWidget(self.table)
|
||||
result.add(self.stack, 1)
|
||||
self.summary = label("", muted=True)
|
||||
result.add(self.summary)
|
||||
self.body.addWidget(result, 1)
|
||||
|
||||
self.search.textChanged.connect(self.proxy.set_text)
|
||||
self.only_open.toggled.connect(lambda value: self.proxy.set_predicate(
|
||||
"open", (lambda row: row["state"] in ("new", "check")) if value else None))
|
||||
self.tenant.activated.connect(lambda _index: self._tenant_chosen())
|
||||
self.role.activated.connect(lambda _index: self._store(role_id=self.role.valid_data()))
|
||||
self.rename.toggled.connect(lambda value: self._store(rename=value))
|
||||
self.state.profile_switched.connect(self._profile_switched)
|
||||
self._profile_switched()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Profile settings
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _settings(self):
|
||||
return self.state.profile.setdefault("access_points", {}) if self.state.profile else {}
|
||||
|
||||
def _store(self, **values):
|
||||
if self.state.profile is None:
|
||||
return
|
||||
self._settings().update(values)
|
||||
self.state.touch()
|
||||
|
||||
def _profile_switched(self):
|
||||
self.aps, self.only_netbox, self.engine, self.tenants = [], [], None, []
|
||||
self.tenant.set_items([])
|
||||
self.role.set_items([])
|
||||
self.rename.blockSignals(True)
|
||||
self.rename.setChecked(self._settings().get("rename", True))
|
||||
self.rename.blockSignals(False)
|
||||
self._refresh()
|
||||
|
||||
def on_show(self):
|
||||
if not self.tenants and self._netbox_ready() and not self.tasks.busy:
|
||||
self._load_lists()
|
||||
|
||||
def set_busy(self, busy):
|
||||
for widget in (self.load_button, self.sites_button, self.refresh_button):
|
||||
widget.setEnabled(not busy)
|
||||
self._update_buttons()
|
||||
|
||||
def _netbox_ready(self):
|
||||
return bool(self.state.profile) and not self.state.offline and self.state.netbox_configured()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Loading
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def load_file(self):
|
||||
path, _filter = QFileDialog.getOpenFileName(self.window, "Sophos-Export laden", "",
|
||||
"CSV-Dateien (*.csv);;Alle Dateien (*)")
|
||||
if not path:
|
||||
return
|
||||
try:
|
||||
self.aps = parse_csv(Path(path).read_bytes())
|
||||
except (OSError, APImportError) as error:
|
||||
widgets.message(self.window, "Datei nicht lesbar", str(error), "warning")
|
||||
return
|
||||
self.file_name = Path(path).name
|
||||
self.only_netbox, self.engine = [], None
|
||||
logger("app").info("Sophos-Export %s: %s Access Points", self.file_name, len(self.aps))
|
||||
self._refresh()
|
||||
if self._netbox_ready():
|
||||
self._load_lists(then_compare=True)
|
||||
|
||||
def _load_lists(self, then_compare=False):
|
||||
connect = self.actions._connector()
|
||||
|
||||
def work(ctx):
|
||||
nb = connect(ctx)
|
||||
ctx.log("Lade Mandanten und Geräterollen …")
|
||||
tenants = sorted(((item.name, item.id) for item in nb.tenancy.tenants.all()), key=lambda x: x[0].casefold())
|
||||
roles = sorted(((item.name, item.id) for item in nb.dcim.device_roles.all()), key=lambda x: x[0].casefold())
|
||||
return tenants, roles
|
||||
|
||||
def done(result):
|
||||
self.tenants, roles = result
|
||||
settings = self._settings()
|
||||
self.tenant.set_items(self.tenants, settings.get("tenant_id"))
|
||||
role_id = settings.get("role_id") or next(
|
||||
(role_id for name, role_id in roles if name.casefold() in ROLE_HINTS
|
||||
or "access point" in name.casefold()), None)
|
||||
self.role.set_items(roles, role_id)
|
||||
if then_compare and self.tenant.valid_data():
|
||||
QTimer.singleShot(0, self.compare)
|
||||
|
||||
self.tasks.run(work, title="Mandanten laden", area="app", on_success=done,
|
||||
on_error=self.actions._netbox_failed)
|
||||
|
||||
def _tenant_chosen(self):
|
||||
self._store(tenant_id=self.tenant.valid_data())
|
||||
if self.aps and self.tenant.valid_data():
|
||||
self.compare()
|
||||
|
||||
def compare(self):
|
||||
tenant_id = self.tenant.valid_data()
|
||||
if not self.aps or not tenant_id or self.tasks.busy:
|
||||
if not tenant_id and self.aps:
|
||||
self.window.toast("Bitte zuerst den Mandanten wählen.", "info")
|
||||
return
|
||||
connect = self.actions._connector()
|
||||
aps = [dict(ap, issues=[issue for issue in ap["issues"] if not issue.startswith(("NetBox-Gerät gehört",
|
||||
"Seriennummer in NetBox"))])
|
||||
for ap in self.aps]
|
||||
|
||||
def work(ctx):
|
||||
engine = APSyncEngine(connect(ctx), ctx.log)
|
||||
ctx.log("Lade Standorte und vorhandene Access Points der Mandantengruppe …")
|
||||
engine.load_context(tenant_id)
|
||||
ctx.log(f"Suche {len(aps)} Access Points in NetBox (Seriennummer, MAC, Name) …")
|
||||
only_netbox = engine.match(aps)
|
||||
return engine, aps, only_netbox
|
||||
|
||||
def done(result):
|
||||
self.engine, self.aps, self.only_netbox = result
|
||||
found = sum(1 for ap in self.aps if ap.get("device"))
|
||||
logger("app").log(25, "Abgleich: %s von %s APs in NetBox, %s nur in NetBox", found, len(self.aps),
|
||||
len(self.only_netbox))
|
||||
self._refresh()
|
||||
|
||||
self.tasks.run(work, title="Access Points abgleichen", area="app", on_success=done,
|
||||
on_error=self.actions._netbox_failed)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Table
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _site_for(self, ap):
|
||||
settings = self._settings()
|
||||
chosen = (settings.get("ap_sites") or {}).get(ap_key(ap)) or (settings.get("site_map") or {}).get(
|
||||
ap["site_hint"])
|
||||
if chosen:
|
||||
return chosen
|
||||
return self.engine.suggest_site(ap["site_hint"]) if self.engine else None
|
||||
|
||||
def _site_name(self, site_id):
|
||||
sites = self.engine.ap_sites if self.engine else []
|
||||
return next((site["name"] for site in sites if site["id"] == site_id), "")
|
||||
|
||||
def _refresh(self):
|
||||
rows = []
|
||||
for ap in self.aps:
|
||||
device = ap.get("device")
|
||||
site_id = None if device else self._site_for(ap)
|
||||
if device:
|
||||
site = getattr(device, "site", None)
|
||||
site_name = getattr(site, "name", "") or self._site_name(getattr(site, "id", site))
|
||||
elif self.engine:
|
||||
site_name = self._site_name(site_id) if site_id else "– zuordnen –"
|
||||
else:
|
||||
site_name = ""
|
||||
state = "new" if not device else ("check" if ap["issues"] else "known")
|
||||
rows.append(dict(ap, key=ap_key(ap), state=state if self.engine else "", site_id=site_id,
|
||||
netbox_site=site_name, netbox_device=device.name if device else "",
|
||||
method=ap.get("method", "")))
|
||||
for device in self.only_netbox:
|
||||
rows.append({"key": f"netbox-{device.id}", "state": "netbox_only", "name": device.name,
|
||||
"model": getattr(getattr(device, "device_type", None), "model", "") or "",
|
||||
"serial": getattr(device, "serial", "") or "", "mac": "",
|
||||
"ip": str(getattr(getattr(device, "primary_ip4", None), "address", "") or "").split("/")[0],
|
||||
"site_hint": "", "netbox_site": getattr(getattr(device, "site", None), "name", "")
|
||||
or self._site_name(related_id(device, "site")),
|
||||
"netbox_device": device.name, "method": "",
|
||||
"issues": ["In NetBox, aber nicht im Sophos-Export"]})
|
||||
self.model.set_rows(rows)
|
||||
self.stack.setCurrentIndex(1 if rows else 0)
|
||||
counts = {key: sum(1 for row in rows if row["state"] == key) for key in STATE_TEXT}
|
||||
parts = [f"{len(self.aps)} Access Points" + (f" aus {self.file_name}" if self.file_name else "")]
|
||||
if self.engine:
|
||||
parts += [f"{counts['known']} in NetBox", f"{counts['new']} neu", f"{counts['check']} zu prüfen",
|
||||
f"{counts['netbox_only']} nur in NetBox"]
|
||||
missing_sites = sum(1 for row in rows if row["state"] == "new" and not row.get("site_id"))
|
||||
if missing_sites:
|
||||
parts.append(f"{missing_sites} ohne NetBox-Standort")
|
||||
elif self.aps:
|
||||
parts.append("Mandant wählen, um mit NetBox abzugleichen" if self._netbox_ready()
|
||||
else "kein NetBox-Abgleich (kein Zugang im Profil oder Offline-Modus)")
|
||||
self.summary.setText(" · ".join(parts) if self.aps or self.only_netbox else "")
|
||||
self._update_buttons()
|
||||
|
||||
def _update_buttons(self):
|
||||
busy = self.tasks.busy
|
||||
widgets.set_enabled(self.sync_button, bool(self.engine) and not busy,
|
||||
"Bitte Export laden und Mandanten wählen." if not self.engine else "Bitte warten …")
|
||||
widgets.set_enabled(self.sites_button, bool(self.engine) and not busy, "Erst mit NetBox abgleichen.")
|
||||
widgets.set_enabled(self.refresh_button, bool(self.aps) and not busy, "Erst einen Export laden.")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Sites and transfer
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _new_aps(self):
|
||||
return [ap for ap in self.aps if not ap.get("device")]
|
||||
|
||||
def map_sites(self):
|
||||
if not self.engine:
|
||||
return False
|
||||
new = self._new_aps()
|
||||
hints = {}
|
||||
for ap in new:
|
||||
if ap["site_hint"]:
|
||||
hints[ap["site_hint"]] = hints.get(ap["site_hint"], 0) + 1
|
||||
settings = self._settings()
|
||||
dialog = SiteMappingDialog(
|
||||
self.window, [(hint, count, self.engine.suggest_site(hint)) for hint, count in sorted(hints.items())],
|
||||
[ap for ap in new if not ap["site_hint"]], self.engine.ap_sites,
|
||||
settings.get("site_map") or {}, settings.get("ap_sites") or {})
|
||||
if not dialog.exec():
|
||||
return False
|
||||
self._store(site_map=dialog.site_map, ap_sites=dialog.ap_sites)
|
||||
self._refresh()
|
||||
return True
|
||||
|
||||
def sync(self):
|
||||
if not self.engine or self.tasks.busy:
|
||||
return
|
||||
new = self._new_aps()
|
||||
role_id = self.role.valid_data()
|
||||
if new and not role_id:
|
||||
widgets.message(self.window, "Geräterolle fehlt", "Für neue Access Points bitte eine Geräterolle wählen.",
|
||||
"info")
|
||||
return
|
||||
if any(not self._site_for(ap) for ap in new) and not self.map_sites():
|
||||
return
|
||||
sites = {ap_key(ap): self._site_for(ap) for ap in new}
|
||||
missing = [ap["name"] for ap in new if not sites.get(ap_key(ap))]
|
||||
if missing and not widgets.confirm(
|
||||
self.window, "Standorte fehlen", f"{len(missing)} neue Access Points haben keinen NetBox-Standort und "
|
||||
"werden übersprungen.", ok_text="Trotzdem fortfahren", details="\n".join(missing)):
|
||||
return
|
||||
engine, aps, rename = self.engine, list(self.aps), self.rename.isChecked()
|
||||
|
||||
def preview(ctx):
|
||||
ctx.log("Berechne Änderungen …")
|
||||
return engine.sync(aps, sites, role_id, rename, dry_run=True)
|
||||
|
||||
def show(report):
|
||||
def ask():
|
||||
if ClientPreviewDialog(self.window, report).exec():
|
||||
self.tasks.run(lambda ctx: engine.sync(aps, sites, role_id, rename, dry_run=False),
|
||||
title="Access Points übertragen", area="app", on_success=applied,
|
||||
on_error=self.actions._netbox_failed)
|
||||
QTimer.singleShot(0, ask)
|
||||
|
||||
def applied(report):
|
||||
for error in report["errors"]:
|
||||
logger("app").error("%s", error)
|
||||
text = (f"{report['devices_created']} Access Points angelegt, {report['devices_updated']} aktualisiert"
|
||||
+ (f", {len(report['errors'])} Fehler" if report["errors"] else ""))
|
||||
logger("app").log(25, "%s", text)
|
||||
self.window.toast(text, "warning" if report["errors"] else "success")
|
||||
QTimer.singleShot(0, self.compare)
|
||||
|
||||
self.tasks.run(preview, title="Änderungen berechnen", area="app", on_success=show,
|
||||
on_error=self.actions._netbox_failed)
|
||||
@@ -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))
|
||||
@@ -21,6 +21,8 @@ class Record(SimpleNamespace):
|
||||
|
||||
|
||||
def _matches(record, key, value):
|
||||
if isinstance(value, list): # pynetbox sends lists as repeated query parameters (OR)
|
||||
return any(_matches(record, key, item) for item in value)
|
||||
if key == "brief":
|
||||
return True
|
||||
if key.endswith("__ie"):
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fake_netbox import FakeNetBox, Record
|
||||
|
||||
from netbox_sync.core.ap_sync import APImportError, APSyncEngine, ap_key, parse_csv
|
||||
|
||||
CSV = (
|
||||
'"AP Name","MAC Address","Serial Number","Internal IP address","Model","Config Status",'
|
||||
'"Active Channel for 2.4 GHz","Current Site","Firmware","Uptime"\n'
|
||||
'"Kita Sonne EG ","7c:5a:1c:00:00:01","p52000000000001","10.10.230.101","APX320","UP_TO_DATE","6",'
|
||||
'"Kita Sonnenschein","v2.3.6","1"\n'
|
||||
'"Kita Sonne OG","7C:5A:1C:00:00:02","P52000000000002","10.10.230.102","APX320","UP_TO_DATE","1",'
|
||||
'"Kita Sonnenschein","v2.3.6","1"\n'
|
||||
'"Büro ohne Standort","c8:4f:86:00:00:03","P52000000000003","10.10.230.102","AP6 420","UPDATE_PENDING","",'
|
||||
'"","v1.10.3192",""\n'
|
||||
)
|
||||
|
||||
|
||||
def _netbox():
|
||||
nb = FakeNetBox()
|
||||
group = SimpleNamespace(id=3, name="Kunde")
|
||||
nb.tenancy.tenants.records += [Record(nb.tenancy.tenants, id=7, name="Kunde RZ", group=group),
|
||||
Record(nb.tenancy.tenants, id=8, name="Kunde Kita", group=group)]
|
||||
nb.dcim.sites.records += [
|
||||
Record(nb.dcim.sites, id=20, name="Kita Sonnenschein Jena", tenant=SimpleNamespace(id=8), tenant_group=group),
|
||||
Record(nb.dcim.sites, id=21, name="Geschäftsstelle", tenant=SimpleNamespace(id=7), tenant_group=group),
|
||||
]
|
||||
nb.dcim.device_roles.records.append(Record(nb.dcim.device_roles, id=30, name="Access Point"))
|
||||
sophos = Record(nb.dcim.manufacturers, id=40, name="Sophos", slug="sophos")
|
||||
nb.dcim.manufacturers.records.append(sophos)
|
||||
# Known by serial (other spelling), known only by name, and one missing in Sophos.
|
||||
nb.dcim.devices.records += [
|
||||
Record(nb.dcim.devices, id=101, name="AP alt", serial="P52000000000002", tenant=SimpleNamespace(id=8),
|
||||
tenant_group=group, manufacturer=sophos, site=SimpleNamespace(id=20), description="Firmware v2.3.5",
|
||||
primary_ip4=None),
|
||||
Record(nb.dcim.devices, id=102, name="Kita Sonne EG", serial="", tenant=SimpleNamespace(id=8),
|
||||
tenant_group=group, manufacturer=sophos, site=SimpleNamespace(id=20), description="",
|
||||
primary_ip4=None),
|
||||
Record(nb.dcim.devices, id=103, name="Abgebaut", serial="X1", tenant=SimpleNamespace(id=8),
|
||||
tenant_group=group, manufacturer=sophos, site=SimpleNamespace(id=20), description="",
|
||||
primary_ip4=None),
|
||||
]
|
||||
return nb
|
||||
|
||||
|
||||
def test_sophos_export_is_parsed_and_checked():
|
||||
aps = parse_csv(CSV.encode("utf-8"))
|
||||
assert [ap["name"] for ap in aps] == ["Kita Sonne EG", "Kita Sonne OG", "Büro ohne Standort"]
|
||||
assert aps[1]["mac"] == "7C:5A:1C:00:00:02" and aps[0]["serial"] == "P52000000000001"
|
||||
assert aps[2]["issues"][0] == "kein Standort in Sophos"
|
||||
assert any("10.10.230.102 doppelt" in issue for issue in aps[1]["issues"])
|
||||
assert parse_csv(CSV.replace(",", ";").encode("cp1252"))[2]["name"] == "Büro ohne Standort"
|
||||
with pytest.raises(APImportError):
|
||||
parse_csv(b"foo,bar\n1,2\n")
|
||||
|
||||
|
||||
def test_existing_aps_are_found_by_serial_and_name_and_missing_ones_reported():
|
||||
nb = _netbox()
|
||||
engine = APSyncEngine(nb)
|
||||
engine.load_context(7)
|
||||
assert [site["name"] for site in engine.ap_sites] == ["Geschäftsstelle", "Kita Sonnenschein Jena"]
|
||||
assert engine.suggest_site("Kita Sonnenschein") == 20 and engine.suggest_site("") is None
|
||||
aps = parse_csv(CSV)
|
||||
only_netbox = engine.match(aps)
|
||||
assert [(ap["device"].id if ap["device"] else None, ap["method"]) for ap in aps] == [
|
||||
(102, "Name"), (101, "Seriennummer"), (None, "")]
|
||||
assert [device.name for device in only_netbox] == ["Abgebaut"]
|
||||
|
||||
|
||||
def test_sync_creates_new_aps_with_site_tenant_and_updates_existing():
|
||||
nb = _netbox()
|
||||
engine = APSyncEngine(nb)
|
||||
engine.load_context(7)
|
||||
aps = parse_csv(CSV)
|
||||
engine.match(aps)
|
||||
sites = {ap_key(aps[2]): 21}
|
||||
|
||||
preview = engine.sync(aps, sites, role_id=30, dry_run=True)
|
||||
assert preview["errors"] == [] and preview["devices_created"] == 1 and preview["devices_updated"] == 2
|
||||
assert nb.dcim.devices.created == [] and nb.ipam.ip_addresses.created == []
|
||||
|
||||
report = engine.sync(aps, sites, role_id=30, dry_run=False)
|
||||
assert report["errors"] == []
|
||||
created = nb.dcim.devices.created[-1]
|
||||
assert created["name"] == "Büro ohne Standort" and created["site"] == 21 and created["tenant"] == 7
|
||||
assert created["serial"] == "P52000000000003" and created["description"] == "Firmware v1.10.3192"
|
||||
renamed = nb.dcim.devices.get(101)
|
||||
assert renamed.name == "Kita Sonne OG" and renamed.description == "Firmware v2.3.6"
|
||||
assert nb.dcim.devices.get(102).serial == "P52000000000001"
|
||||
assert [payload["tenant"] for payload in nb.ipam.ip_addresses.created] == [8, 8]
|
||||
# The duplicate IP of the third AP is not taken away from the second one.
|
||||
assert any("bereits einem anderen Objekt zugeordnet" in change for change in dict(report["items"])[
|
||||
"Büro ohne Standort"])
|
||||
|
||||
|
||||
def test_new_ap_without_site_is_an_error_not_a_guess():
|
||||
nb = _netbox()
|
||||
engine = APSyncEngine(nb)
|
||||
engine.load_context(7)
|
||||
aps = parse_csv(CSV)
|
||||
engine.match(aps)
|
||||
report = engine.sync(aps, {}, role_id=30, dry_run=True)
|
||||
assert report["errors"] == ["Büro ohne Standort: kein NetBox-Standort zugeordnet"]
|
||||
@@ -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"
|
||||
Reference in new issue
Block a user