Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b89a364bf0 | ||
|
|
97ee72e610 | ||
|
|
c85df7402d | ||
|
|
5427cc015e | ||
|
|
1aa1c15aa8 | ||
|
|
51f3fc70cd | ||
|
|
411c5446fe | ||
|
|
1bd2d42b5d | ||
|
|
2092f41624 | ||
|
|
e9e1783360 | ||
|
|
576f245b7d | ||
|
|
0e04dae354 | ||
|
|
63ed535a37 | ||
|
|
781ed7d17b | ||
|
|
05695a8471 | ||
|
|
1949f03bae | ||
|
|
dfe985bb9e | ||
|
|
d853f08445 | ||
|
|
f4c507de6c | ||
|
|
3c8bc7879c | ||
|
|
770edc4a03 | ||
|
|
eee60d26ad | ||
|
|
63fd7b987a | ||
|
|
899b4c58fc | ||
|
|
89fe37ea04 | ||
|
|
34b1391ff0 | ||
|
|
340f404f94 | ||
|
|
f1af9f8f86 | ||
|
|
2fb6ac38ec | ||
|
|
2dcd0b0855 | ||
|
|
159a933964 | ||
|
|
c81d9a7edc | ||
|
|
dc8921aaea | ||
|
|
1942d6ecdf | ||
|
|
b402591cdf | ||
|
|
ba50527ee5 | ||
|
|
8d2bbafc8d | ||
|
|
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
|
||||
@@ -49,7 +49,8 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
|
||||
### Switches (Aruba CX, ArubaOS-Switch/ProCurve, HPE Comware)
|
||||
|
||||
- Add several NetBox devices in one step — host taken from the primary IP,
|
||||
platform suggested from model/manufacturer
|
||||
platform suggested from model/manufacturer; members of a NetBox virtual
|
||||
chassis are added once, through the chassis master
|
||||
- Platform "detect automatically" via SSH
|
||||
- Parallel SSH queries; SSH host keys are stored on first contact and verified
|
||||
afterwards
|
||||
@@ -61,6 +62,12 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
|
||||
- VLAN membership per port (untagged and tagged, read from the running
|
||||
configuration) is written to the interface **label**, e.g. `10` or `1,20-22`;
|
||||
only VLAN-related lines of the configuration are kept in the raw data
|
||||
- LAG members (Aruba CX `lag N`, ArubaOS-Switch `trunk … trkN`, Comware
|
||||
`port link-aggregation group N`) get their LAG in the label, e.g.
|
||||
`10,20 (LAG 1)`, and are assigned to the LAG interface in NetBox (field
|
||||
*LAG*; only on the same device). Members without own VLAN configuration take
|
||||
the VLANs of their LAG. NetBox Utilities 0.25.0 or later ignores the LAG note
|
||||
when it evaluates VLAN labels
|
||||
- Automatic port mapping when NetBox names differ from the switch (e.g. `5` ↔
|
||||
`1/1/5`): equal name, then equal port number, then natural order
|
||||
- **Mapping review** before the preview: non-obvious port mappings and every
|
||||
@@ -82,9 +89,80 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
|
||||
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
|
||||
- Stacks are detected (Aruba CX VSF, ArubaOS-Switch stacking/VSF, HPE Comware
|
||||
IRF): every member is assigned to its own NetBox device (suggested from the
|
||||
NetBox virtual chassis positions, stored per switch) and gets its own ports;
|
||||
LAGs and VLAN interfaces stay on the switch's device
|
||||
- Optional: with the [NetBox Utilities](https://git.mrblake.cc/MrBlake/Netbox-Utilities)
|
||||
plugin (0.24.0 or later) a detected stack is also entered as its switch stack
|
||||
(the switch's device as stack switch, the other member devices as members);
|
||||
members entered by hand are kept. Without the plugin this step is skipped
|
||||
- Optional configuration backup ("Konfiguration als Anhang sichern"): with the
|
||||
[netbox-attachments](https://github.com/Kani999/netbox-attachments) plugin the
|
||||
running configuration is attached to the switch's device as a text file.
|
||||
Passwords, keys and SNMP communities are removed first; a new attachment is
|
||||
only added when the configuration changed (SHA-256 in the description).
|
||||
Older plugin versions (parent on the attachment) and newer ones (separate
|
||||
assignments) are supported; without the plugin the step is skipped with a note
|
||||
- Cables from LLDP/CDP, also with FQDN system names or via the management IP.
|
||||
Neighbors that report their MAC address as port ID (e.g. access points) are
|
||||
matched by MAC, and a device with a single physical port is cabled there
|
||||
- Existing cables are checked against LLDP/CDP: a different far end is reported
|
||||
as a note. Only with the optional "Bestehende Kabel anpassen" (confirmed with
|
||||
a warning, NetBox is the source of truth) the cable is moved to the reported
|
||||
neighbor; such changes are marked with ⚠ in the preview. Cables to patch
|
||||
panels (front/rear ports) and far ends that already have another cable are
|
||||
never changed
|
||||
- The switch configuration is only changed when "Enable LLDP if needed" is
|
||||
explicitly switched on
|
||||
- LANCOM switches with the mode-based LCOS SX 3.x CLI (e.g. GS-2326P+) are read
|
||||
over SSH: `system`, `port`, `vlan`, `ip` and `lldp` modes with their `show`
|
||||
commands. Untagged/tagged VLANs follow the egress rule (Access, Hybrid = PVID
|
||||
untagged, Trunk). There is no running-config; the collected outputs are
|
||||
attached as backup. "Enable LLDP if needed" switches ports whose LLDP mode is
|
||||
Disabled/Tx only to `enable` (not saved) and waits one LLDP interval
|
||||
- One-off import without SSH ("Backup importieren …"): configuration backups
|
||||
of D-Link DGS-1210 (`config.bin`) and Linksys LGS (`*.cfg` or the contained
|
||||
`SNCSR.conf`) switches are read offline. Hostname, location, management IP,
|
||||
port descriptions, admin state, untagged/tagged VLANs and VLAN names are
|
||||
taken over; the switch is matched to the NetBox device by its hostname and
|
||||
then synchronized like an SSH result (no LLDP neighbors, hence no cables)
|
||||
The D-Link `config.bin` is attached to the device unchanged (it contains the
|
||||
switch's secrets as stored by the switch); the Linksys configuration is
|
||||
attached as text with secrets removed
|
||||
|
||||
### 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
|
||||
- No tenant to pick up front: existing APs are found in all of NetBox by serial
|
||||
number, MAC address and name; Sophos APs in NetBox that are missing in the
|
||||
export are listed as "only in NetBox" for the tenants the export concerns
|
||||
- Sophos sites are mapped to NetBox sites (suggested by name, stored per
|
||||
profile); the site is optional – APs without one go to a default site, since
|
||||
NetBox requires a site for every device. The tenant is mandatory and chosen
|
||||
deliberately per Sophos site – it is never preselected. Sophos sites left without site and tenant are
|
||||
ignored (stored per profile) and not transferred
|
||||
- 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. 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)
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
#define AppName "NetBox Synchronizer"
|
||||
#ifndef AppVersion
|
||||
#define AppVersion "4.7.0"
|
||||
#define AppVersion "4.16.4"
|
||||
#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.16.4"
|
||||
APP_PUBLISHER = "Louis-Alexander Kerst"
|
||||
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
|
||||
|
||||
|
||||
@@ -0,0 +1,391 @@
|
||||
"""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.group_tenants = []
|
||||
self.netbox_aps = []
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Context
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def load_context(self, tenant_id=None):
|
||||
"""Sites and existing Sophos devices of the tenant's tenant group, or of all of NetBox without a tenant."""
|
||||
self.tenant_id = tenant_id
|
||||
if tenant_id is None:
|
||||
tenants = {item.id: item.name for item in self.nb.tenancy.tenants.all()}
|
||||
self.tenant_ids = set(tenants)
|
||||
self.group_tenants = sorted(({"id": key, "name": name} for key, name in tenants.items()),
|
||||
key=lambda row: row["name"].casefold())
|
||||
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.all()), key=lambda row: row["name"].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)) if manufacturer else []
|
||||
return self.ap_sites
|
||||
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.group_tenants = sorted(({"id": key, "name": tenants[key]} for key in self.tenant_ids if key in tenants),
|
||||
key=lambda row: row["name"].casefold())
|
||||
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, placements, role_id, rename=True, dry_run=True, default_site=None):
|
||||
"""``placements`` maps ``ap_key`` to ``{"site": ID or None, "tenant": ID}``.
|
||||
|
||||
The site is optional; NetBox needs one for every device, so new APs
|
||||
without a site go to ``default_site``. The tenant is mandatory.
|
||||
"""
|
||||
report = self.new_report()
|
||||
self._planned = set()
|
||||
for ap in aps:
|
||||
try:
|
||||
changes = self._sync_ap(ap, placements.get(ap_key(ap)) or {}, role_id, rename, dry_run, report,
|
||||
default_site)
|
||||
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, placement, role_id, rename, dry_run, report, default_site=None):
|
||||
device = ap.get("device")
|
||||
site_id = placement.get("site") or default_site
|
||||
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"] = placement.get("tenant") or 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 updates.get("tenant")
|
||||
else:
|
||||
if not site_id:
|
||||
raise APImportError("kein Standort – NetBox verlangt für Geräte einen Standort, bitte einen "
|
||||
"Standard-Standort wählen")
|
||||
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)
|
||||
# An explicitly chosen tenant wins, otherwise the one of the site.
|
||||
tenant_id = placement.get("tenant") or 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
|
||||
@@ -0,0 +1,342 @@
|
||||
"""One-off import of switch configuration backups (no SSH).
|
||||
|
||||
Some small switches cannot be read over SSH in a useful way, but their web UI
|
||||
exports a configuration backup. These parsers turn such a backup into the
|
||||
same snapshot that :func:`netbox_sync.core.switches.build_snapshot` produces,
|
||||
so the normal review and synchronization run unchanged.
|
||||
|
||||
Supported formats:
|
||||
|
||||
* D-Link DGS-1210 series (``config.bin``): a short header with the model name
|
||||
followed by a zlib-compressed dump of SNMP objects (``OID<TAB>type<TAB>value``).
|
||||
* Linksys LGS series (``*.cfg``): a firmware header followed by a tar archive
|
||||
whose ``current_config/SNCSR.conf`` holds an ISS-style CLI configuration.
|
||||
A plain text ``SNCSR.conf`` is accepted as well.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import io
|
||||
import ipaddress
|
||||
import re
|
||||
import tarfile
|
||||
import time
|
||||
import zlib
|
||||
|
||||
from netbox_sync.core.switches import _interface, _membership, mask_config
|
||||
|
||||
BACKUP_PLATFORMS = {
|
||||
"dlink_backup": "D-Link (Backup-Datei)",
|
||||
"linksys_backup": "Linksys LGS (Backup-Datei)",
|
||||
}
|
||||
|
||||
FILE_FILTER = "Switch-Backups (*.bin *.cfg *.conf *.txt);;Alle Dateien (*)"
|
||||
|
||||
|
||||
class BackupError(ValueError):
|
||||
"""The file is no supported switch backup."""
|
||||
|
||||
|
||||
def parse_backup(data, filename=""):
|
||||
"""Snapshot of a backup file plus ``name``, ``host`` and ``model`` from its configuration.
|
||||
|
||||
Returns ``(switch, snapshot)`` where ``switch`` is a profile entry without credentials.
|
||||
"""
|
||||
if isinstance(data, str):
|
||||
data = data.encode("utf-8")
|
||||
dump = _dlink_dump(data)
|
||||
if dump is not None:
|
||||
switch, snapshot = _dlink_snapshot(dump, data)
|
||||
# The original file is attached 1:1 so it can be restored on the switch.
|
||||
snapshot["config_file"] = {"name": filename or "config.bin", "data": base64.b64encode(data).decode("ascii")}
|
||||
return switch, snapshot
|
||||
text = _linksys_text(data)
|
||||
if text is not None:
|
||||
return _linksys_snapshot(text)
|
||||
raise BackupError(f"„{filename or 'Datei'}“ ist kein unterstütztes Backup (D-Link DGS-1210 oder Linksys LGS).")
|
||||
|
||||
|
||||
def _snapshot(platform, interfaces, vlan_names, config_backup=""):
|
||||
ips = [{"interface": item["name"], "address": address}
|
||||
for item in interfaces for address in item["ip_addresses"]]
|
||||
return {
|
||||
"platform": platform,
|
||||
"interfaces": interfaces,
|
||||
"ip_addresses": ips,
|
||||
"neighbors": [],
|
||||
"lldp_neighbors": [],
|
||||
"cdp_neighbors": [],
|
||||
"raw": {},
|
||||
"vlans_read": True,
|
||||
"config_backup": config_backup,
|
||||
"vlan_names": vlan_names,
|
||||
"stack": [],
|
||||
"lldp_disabled": False,
|
||||
"lldp_enabled_automatically": False,
|
||||
"discovered_at": time.time(),
|
||||
"source": "backup",
|
||||
}
|
||||
|
||||
|
||||
def _address(address, mask):
|
||||
try:
|
||||
value = ipaddress.ip_interface(f"{address}/{mask}")
|
||||
except ValueError:
|
||||
return None
|
||||
return None if value.ip.is_unspecified else str(value)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# D-Link DGS-1210
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
_DLINK_OID = re.compile(rb"^1\.3\.6\.1\.")
|
||||
|
||||
|
||||
def _dlink_dump(data):
|
||||
"""Decompressed SNMP dump of a D-Link backup, or ``None``."""
|
||||
if _DLINK_OID.match(data):
|
||||
return data
|
||||
if not data[:4] in (b"DGS-", b"DES-", b"DXS-"):
|
||||
return None
|
||||
for match in re.finditer(rb"\x78[\x01\x5e\x9c\xda]", data[:512]):
|
||||
try:
|
||||
dump = zlib.decompressobj().decompress(data[match.start():])
|
||||
except zlib.error:
|
||||
continue
|
||||
if _DLINK_OID.match(dump):
|
||||
return dump
|
||||
raise BackupError("D-Link-Backup erkannt, aber die Konfiguration lässt sich nicht entpacken.")
|
||||
|
||||
|
||||
def parse_snmp_dump(dump):
|
||||
"""``{OID: value}``; octet strings are ``bytes`` (they may contain line breaks), the rest ``str``."""
|
||||
values, position, size = {}, 0, len(dump)
|
||||
while position < size:
|
||||
if dump[position] in b"\x00\r\n":
|
||||
position += 1
|
||||
continue
|
||||
tab = dump.find(b"\t", position)
|
||||
if tab < 0:
|
||||
break
|
||||
oid = dump[position:tab].decode("ascii", "replace").strip()
|
||||
type_end = dump.find(b"\t", tab + 1)
|
||||
line_end = dump.find(b"\n", tab + 1)
|
||||
if line_end < 0:
|
||||
line_end = size
|
||||
if type_end < 0 or type_end > line_end:
|
||||
position = line_end + 1 # unknown line format
|
||||
continue
|
||||
kind = dump[tab + 1:type_end].strip()
|
||||
if kind == b"4":
|
||||
length_end = dump.find(b"\t", type_end + 1)
|
||||
try:
|
||||
length = int(dump[type_end + 1:length_end])
|
||||
except ValueError:
|
||||
position = line_end + 1
|
||||
continue
|
||||
start = length_end + 1
|
||||
values[oid] = dump[start:start + length]
|
||||
position = start + length + 1
|
||||
else:
|
||||
values[oid] = dump[type_end + 1:line_end].decode("ascii", "replace").strip()
|
||||
position = line_end + 1
|
||||
return values
|
||||
|
||||
|
||||
def _text(value):
|
||||
if isinstance(value, bytes):
|
||||
return value.decode("utf-8", "replace").strip("\x00").strip()
|
||||
return (value or "").strip()
|
||||
|
||||
|
||||
def _bitmap_ports(value):
|
||||
"""Ports set in an SNMP PortList (byte 0, bit 7 = port 1)."""
|
||||
ports = set()
|
||||
for index, byte in enumerate(value or b""):
|
||||
for bit in range(8):
|
||||
if byte & (0x80 >> bit):
|
||||
ports.add(index * 8 + bit + 1)
|
||||
return ports
|
||||
|
||||
|
||||
def _table(values, prefix):
|
||||
"""``{last index: value}`` of all OIDs ``<prefix>.<index>``."""
|
||||
result = {}
|
||||
for oid, value in values.items():
|
||||
if oid.startswith(prefix + ".") and oid[len(prefix) + 1:].isdigit():
|
||||
result[int(oid[len(prefix) + 1:])] = value
|
||||
return result
|
||||
|
||||
|
||||
def _dlink_snapshot(dump, data):
|
||||
values = parse_snmp_dump(dump)
|
||||
# The enterprise subtree of the model, e.g. 1.3.6.1.4.1.171.10.76.21.1 for DGS-1210-28P.
|
||||
base = next((match.group(1) for match in
|
||||
(re.match(r"^(1\.3\.6\.1\.4\.1\.171\.10(?:\.\d+)+?)\.7\.6\.1\.1\.\d+$", oid) for oid in values)
|
||||
if match), None)
|
||||
names, egress, untagged, pvids = {}, {}, {}, {}
|
||||
if base:
|
||||
names = _table(values, f"{base}.7.6.1.1")
|
||||
egress = _table(values, f"{base}.7.6.1.2")
|
||||
untagged = _table(values, f"{base}.7.6.1.4")
|
||||
pvids = _table(values, f"{base}.7.7.1.1")
|
||||
if not egress: # standard Q-BRIDGE-MIB
|
||||
names = _table(values, "1.3.6.1.2.1.17.7.1.4.3.1.1")
|
||||
egress = _table(values, "1.3.6.1.2.1.17.7.1.4.3.1.2")
|
||||
untagged = _table(values, "1.3.6.1.2.1.17.7.1.4.3.1.4")
|
||||
pvids = _table(values, "1.3.6.1.2.1.17.7.1.4.5.1.1")
|
||||
admin = _table(values, "1.3.6.1.2.1.2.2.1.7")
|
||||
descriptions = _table(values, f"{base}.1.16.1.2") if base else {}
|
||||
if not descriptions:
|
||||
descriptions = _table(values, "1.3.6.1.2.1.31.1.1.1.18")
|
||||
port_numbers = sorted(set(pvids) | set(admin) | set(descriptions))
|
||||
if not port_numbers:
|
||||
raise BackupError("Im D-Link-Backup wurden keine Ports gefunden.")
|
||||
|
||||
members = {port: {"untagged": set(), "tagged": set()} for port in port_numbers}
|
||||
for vid, bitmap in egress.items():
|
||||
untagged_ports = _bitmap_ports(untagged.get(vid))
|
||||
for port in _bitmap_ports(bitmap):
|
||||
if port in members:
|
||||
members[port]["untagged" if port in untagged_ports else "tagged"].add(vid)
|
||||
interfaces = []
|
||||
for port in port_numbers:
|
||||
entry = members[port]
|
||||
interfaces.append(_interface(
|
||||
str(port),
|
||||
enabled=str(admin.get(port, "1")) != "2",
|
||||
description=_text(descriptions.get(port)),
|
||||
vlans=_membership(entry["untagged"], entry["tagged"]) if entry["untagged"] or entry["tagged"] else None,
|
||||
lag=None,
|
||||
))
|
||||
if base:
|
||||
address = _address(_text(values.get(f"{base}.2.5.2.0")), _text(values.get(f"{base}.2.5.3.0")))
|
||||
if address:
|
||||
interfaces.append(_interface(_text(values.get(f"{base}.2.5.5.0")) or "System", connected=True,
|
||||
description="Management-Interface", virtual=True,
|
||||
ip_addresses=[address], vlans=None, lag=None))
|
||||
vlan_names = {vid: _text(name) for vid, name in names.items() if _text(name)}
|
||||
model = data[:16].split(b"\x00", 1)[0].decode("ascii", "replace") if not _DLINK_OID.match(data) else ""
|
||||
name = _text(values.get("1.3.6.1.2.1.1.5.0")) or (_text(values.get(f"{base}.2.7.0")) if base else "")
|
||||
host = next((item["ip_addresses"][0].split("/")[0] for item in interfaces if item["ip_addresses"]), "")
|
||||
switch = {"name": name, "host": host, "model": model, "platform": "dlink_backup",
|
||||
"location": _text(values.get("1.3.6.1.2.1.1.6.0"))}
|
||||
return switch, _snapshot("dlink_backup", interfaces, vlan_names)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Linksys LGS (ISS CLI configuration)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
_LINKSYS_MEMBER = "current_config/SNCSR.conf"
|
||||
|
||||
|
||||
def _linksys_text(data):
|
||||
"""``SNCSR.conf`` of a Linksys backup, or ``None``."""
|
||||
offset = data.find(_LINKSYS_MEMBER.encode())
|
||||
if offset >= 0:
|
||||
try:
|
||||
with tarfile.open(fileobj=io.BytesIO(data[offset:]), mode="r:") as archive:
|
||||
stream = archive.extractfile(_LINKSYS_MEMBER)
|
||||
if stream is not None:
|
||||
return stream.read().decode("utf-8", "replace")
|
||||
except (tarfile.TarError, KeyError) as error:
|
||||
raise BackupError(f"Linksys-Backup erkannt, aber nicht lesbar: {error}") from error
|
||||
head = data[:200_000].decode("utf-8", "replace")
|
||||
if re.search(r"(?m)^interface gigabitethernet \d+/\d+\s*$", head) and re.search(r"(?m)^vlan \d+\s*$", head):
|
||||
return data.decode("utf-8", "replace")
|
||||
return None
|
||||
|
||||
|
||||
_GI_PORT = re.compile(r"(?:gigabitethernet|gi)\s*(\d+)/(\d+)(?:-(\d+))?", re.I)
|
||||
|
||||
|
||||
def _linksys_ports(text):
|
||||
"""Port numbers in ``gigabitethernet 0/1``, ``gi 0/1-4`` or comma lists."""
|
||||
ports = []
|
||||
for match in _GI_PORT.finditer(text):
|
||||
start, end = int(match.group(2)), int(match.group(3) or match.group(2))
|
||||
ports += range(start, end + 1)
|
||||
return ports
|
||||
|
||||
|
||||
def _linksys_blocks(text):
|
||||
"""``(header, lines)`` for every top-level block; ISS repeats blocks per feature."""
|
||||
header, body = None, []
|
||||
for raw in text.replace("\r", "").splitlines():
|
||||
line = raw.strip()
|
||||
if line == "!":
|
||||
if header:
|
||||
yield header, body
|
||||
header, body = None, []
|
||||
elif header is None and re.match(r"^(?:interface|vlan)\s+", line, re.I):
|
||||
header, body = line, []
|
||||
elif header is not None:
|
||||
body.append(line)
|
||||
if header:
|
||||
yield header, body
|
||||
|
||||
|
||||
def _linksys_snapshot(text):
|
||||
ports, vlan_names, vlan_members, lags = {}, {}, {}, {}
|
||||
ips = {}
|
||||
for header, body in _linksys_blocks(text):
|
||||
port = re.match(r"(?i)^interface gigabitethernet (\d+)/(\d+)$", header)
|
||||
vlan_interface = re.match(r"(?i)^interface vlan (\d+)$", header)
|
||||
vlan = re.match(r"(?i)^vlan (\d+)$", header)
|
||||
if port:
|
||||
entry = ports.setdefault(int(port.group(2)), {"enabled": True, "description": ""})
|
||||
for line in body:
|
||||
if line == "shutdown":
|
||||
entry["enabled"] = False
|
||||
elif line == "no shutdown":
|
||||
entry["enabled"] = True
|
||||
description = re.match(r'^description\s+"?(.*?)"?$', line)
|
||||
if description:
|
||||
entry["description"] = description.group(1)
|
||||
group = re.match(r"^channel-group (\d+)\b", line)
|
||||
if group:
|
||||
lags[int(port.group(2))] = f"Po{group.group(1)}"
|
||||
elif vlan_interface:
|
||||
for line in body:
|
||||
address = re.match(r"^ip address (\S+) (\S+)$", line)
|
||||
if address:
|
||||
value = _address(address.group(1), address.group(2))
|
||||
if value:
|
||||
ips.setdefault(int(vlan_interface.group(1)), []).append(value)
|
||||
elif vlan:
|
||||
vid = int(vlan.group(1))
|
||||
members = vlan_members.setdefault(vid, {"untagged": set(), "tagged": set()})
|
||||
for line in body:
|
||||
name = re.match(r'^(?:ports\s+)?name\s+"?(.+?)"?$', line)
|
||||
if name:
|
||||
vlan_names[vid] = name.group(1)
|
||||
added = re.match(r"(?i)^ports add (.+?)(?:\s+untagged\s+(.+))?$", line)
|
||||
if added:
|
||||
untagged = set(_linksys_ports(added.group(2) or ""))
|
||||
for number in _linksys_ports(added.group(1)):
|
||||
members["untagged" if number in untagged else "tagged"].add(number)
|
||||
if not ports:
|
||||
raise BackupError("In der Linksys-Konfiguration wurden keine Ports gefunden.")
|
||||
|
||||
interfaces = []
|
||||
for number in sorted(ports):
|
||||
untagged = {vid for vid, item in vlan_members.items() if number in item["untagged"]}
|
||||
tagged = {vid for vid, item in vlan_members.items() if number in item["tagged"]}
|
||||
interfaces.append(_interface(
|
||||
f"GE{number}",
|
||||
enabled=ports[number]["enabled"],
|
||||
description=ports[number]["description"],
|
||||
vlans=_membership(untagged, tagged) if untagged or tagged else None,
|
||||
lag=lags.get(number),
|
||||
))
|
||||
for vid in sorted(ips):
|
||||
interfaces.append(_interface(f"vlan{vid}", connected=True, description="Management-Interface",
|
||||
virtual=True, ip_addresses=ips[vid], vlans=None, lag=None))
|
||||
system = {key: (re.search(rf'(?m)^system {key} "?(.*?)"?\s*$', text) or [None, ""])[1]
|
||||
for key in ("name", "location")}
|
||||
model = (re.search(r'(?m)^set switch-name "?(.*?)"?\s*$', text) or [None, ""])[1]
|
||||
host = next((item["ip_addresses"][0].split("/")[0] for item in interfaces if item["ip_addresses"]), "")
|
||||
switch = {"name": system["name"], "host": host, "model": model, "platform": "linksys_backup",
|
||||
"location": system["location"]}
|
||||
return switch, _snapshot("linksys_backup", interfaces, vlan_names, mask_config(text))
|
||||
@@ -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,319 @@
|
||||
"""LANCOM switches with the LCOS SX 3.x mode-based CLI (e.g. GS-2326P+, GS-2310P+).
|
||||
|
||||
There is no ``show running-config``: every area is a mode (``port``, ``vlan``,
|
||||
``lldp``, ``system``, ``ip``) with its own ``show`` command, left with ``exit``.
|
||||
The outputs are converted into the snapshot of :mod:`netbox_sync.core.switches`.
|
||||
"""
|
||||
|
||||
import ipaddress
|
||||
import re
|
||||
import time
|
||||
|
||||
from netbox_sync.core.switches import (
|
||||
CLI_ERROR,
|
||||
CLI_PROMPT,
|
||||
_compress_vlans,
|
||||
_interface,
|
||||
_membership,
|
||||
clean_output,
|
||||
parse_vlan_list,
|
||||
)
|
||||
|
||||
PLATFORM = "lancom_sx3"
|
||||
|
||||
# (mode, command, output key)
|
||||
COMMANDS = (
|
||||
("system", "show", "system"),
|
||||
("port", "show status", "status"),
|
||||
("port", "show configuration", "port_config"),
|
||||
("vlan", "show vlan", "vlans"),
|
||||
("vlan", "show port-config", "vlan_ports"),
|
||||
("ip", "show", "ip"),
|
||||
("lldp", "show config", "lldp_config"),
|
||||
# "{ports}" becomes the port list from "show status", e.g. "1-26".
|
||||
("lldp", "show info {ports}", "neighbors"),
|
||||
)
|
||||
|
||||
|
||||
# The CLI pages long outputs ("-- more --, next page: Space, ..., q to quit") and cannot be told not to.
|
||||
PAGER = re.compile(r"(?im)^[^\n]*(?:q to quit|-+\s*more\s*-+)[^\n]*\Z")
|
||||
|
||||
|
||||
def _run_cli_command(channel, command, timeout=20):
|
||||
"""Run a command; this CLI executes it only on "\r" ("\n" is just echoed).
|
||||
|
||||
Paging prompts are answered with Space and removed from the output.
|
||||
"""
|
||||
channel.send(command + "\r")
|
||||
chunks, started = [], time.monotonic()
|
||||
while time.monotonic() - started < timeout:
|
||||
if channel.recv_ready():
|
||||
chunks.append(channel.recv(65535).decode("utf-8", errors="replace"))
|
||||
text = clean_output("".join(chunks))
|
||||
if PAGER.search(text):
|
||||
chunks = [PAGER.sub("", text)]
|
||||
channel.send(" ")
|
||||
started = time.monotonic() # every page gets the full timeout
|
||||
continue
|
||||
if CLI_PROMPT.search(text):
|
||||
return text
|
||||
time.sleep(0.05)
|
||||
text = clean_output("".join(chunks))
|
||||
tail = " | ".join(line.strip() for line in text.splitlines()[-3:] if line.strip())
|
||||
raise TimeoutError(f"CLI-Befehl nicht vollständig abgeschlossen: {command}. Der Switch hat die CLI-Ausgabe nicht "
|
||||
f"mit einem vollständigen Prompt abgeschlossen. Letzte Ausgabe: {tail[-300:] or '–'}")
|
||||
|
||||
|
||||
def probe(channel):
|
||||
"""``True`` when the "system" mode shows a LANCOM model; leaves the mode again."""
|
||||
_run_cli_command(channel, "system")
|
||||
system = _run_cli_command(channel, "show", timeout=30)
|
||||
_run_cli_command(channel, "exit")
|
||||
return is_lancom(system)
|
||||
|
||||
|
||||
def is_lancom(text):
|
||||
return bool(re.search(r"(?i)Model Name\s*:\s*LANCOM", text or ""))
|
||||
|
||||
|
||||
# Neighbors usually send LLDP every 30 seconds; after enabling reception we wait for one round.
|
||||
LLDP_WAIT_SECONDS = 35
|
||||
|
||||
|
||||
def run_commands(channel, log=lambda *_args: None, name="", enable_lldp=False, wait=LLDP_WAIT_SECONDS):
|
||||
"""Run :data:`COMMANDS` in their modes; a missing command only leaves its output empty.
|
||||
|
||||
With ``enable_lldp`` ports that do not receive LLDP are switched to ``enable``
|
||||
(running configuration only, nothing is saved).
|
||||
"""
|
||||
outputs, mode = {"lldp_enabled_automatically": False}, None
|
||||
for wanted, command, key in COMMANDS:
|
||||
if mode != wanted:
|
||||
if mode:
|
||||
_run_cli_command(channel, "exit")
|
||||
_run_cli_command(channel, wanted)
|
||||
mode = wanted
|
||||
if "{ports}" in command:
|
||||
numbers = sorted(parse_status(outputs.get("status", "")))
|
||||
if not numbers:
|
||||
outputs[key] = ""
|
||||
continue
|
||||
command = command.format(ports=_compress_vlans(numbers))
|
||||
output = _run_cli_command(channel, command, timeout=60)
|
||||
if CLI_ERROR.search(output):
|
||||
log(f"{name}: „{wanted} → {command}“ wird nicht unterstützt")
|
||||
output = ""
|
||||
outputs[key] = output
|
||||
if key == "lldp_config" and enable_lldp:
|
||||
ports = not_receiving(output)
|
||||
if ports:
|
||||
result = _run_cli_command(channel, f"mode {_compress_vlans(ports)} enable")
|
||||
if CLI_ERROR.search(result) or re.search(r"(?i)permission|denied|privilege", result):
|
||||
raise RuntimeError(f"LLDP konnte nicht aktiviert werden: {clean_output(result).strip()[:200]}")
|
||||
outputs["lldp_enabled_automatically"] = True
|
||||
log(f"{name}: LLDP auf Port(s) {_compress_vlans(ports)} aktiviert – warte {wait} s auf Nachbarn …")
|
||||
time.sleep(wait)
|
||||
outputs[key] = _run_cli_command(channel, "show config", timeout=60)
|
||||
if mode:
|
||||
_run_cli_command(channel, "exit")
|
||||
return outputs
|
||||
|
||||
|
||||
def _field(text, label):
|
||||
match = re.search(rf"(?im)^{re.escape(label)}\s*:\s*(.*?)\s*$", text or "")
|
||||
return match.group(1) if match else ""
|
||||
|
||||
|
||||
def _speed(text):
|
||||
match = re.match(r"(?i)^(\d+(?:\.\d+)?)(G|M)?$", text or "")
|
||||
if not match:
|
||||
return None
|
||||
return int(float(match.group(1)) * (1000 if (match.group(2) or "").upper() == "G" else 1))
|
||||
|
||||
|
||||
def parse_status(output):
|
||||
"""``show status``: ``2/UTP Enabled Up Enabled 1G Full ...``."""
|
||||
ports = {}
|
||||
for line in clean_output(output).splitlines():
|
||||
match = re.match(r"^\s*(\d+)/(\w+)\s+(Enabled|Disabled)\s+(Up|Down)\s+\S+\s+(\S+)", line, re.I)
|
||||
if match:
|
||||
up = match.group(4).lower() == "up"
|
||||
ports[int(match.group(1))] = {
|
||||
"enabled": match.group(3).lower() == "enabled", "connected": up,
|
||||
"speed_mbps": _speed(match.group(5)) if up else None,
|
||||
# Copper ports of these switches are Gigabit; the combo ports report SFP while a module is active.
|
||||
"media": "SFP" if match.group(2).upper() == "SFP" else "1000T",
|
||||
}
|
||||
return ports
|
||||
|
||||
|
||||
def parse_port_config(output):
|
||||
"""``show configuration``: a port line followed by its description line."""
|
||||
ports, current = {}, None
|
||||
for line in clean_output(output).splitlines():
|
||||
match = re.match(r"^\s*(\d+)\s+(Enabled|Disabled)\s", line, re.I)
|
||||
if match:
|
||||
current = int(match.group(1))
|
||||
ports[current] = {"enabled": match.group(2).lower() == "enabled", "description": ""}
|
||||
elif current is not None and line.strip() and not set(line.strip()) <= {"-"}:
|
||||
ports[current]["description"] = line.strip()
|
||||
current = None
|
||||
elif current is not None and set(line.strip()) <= {"-"} and line.strip():
|
||||
current = None
|
||||
return ports
|
||||
|
||||
|
||||
def parse_vlans(output):
|
||||
"""``show vlan``: ``({vid: name}, {vid: {ports}})``."""
|
||||
names, members, current = {}, {}, None
|
||||
for line in clean_output(output).splitlines():
|
||||
match = re.match(r"^\s*(\d+)\s+(.*?)\s+(Static|Combined|GVRP|MSTP|MVR|NAS|VCL|Voice)\b\s*(.*)$", line, re.I)
|
||||
if match:
|
||||
current = int(match.group(1))
|
||||
if match.group(2).strip():
|
||||
names[current] = match.group(2).strip()
|
||||
members[current] = parse_vlan_list(match.group(4))
|
||||
elif current is not None and re.match(r"^\s+[\d,\-\s]+$", line):
|
||||
members[current] |= parse_vlan_list(line) # wrapped port list
|
||||
else:
|
||||
current = None
|
||||
return names, members
|
||||
|
||||
|
||||
def parse_vlan_ports(output):
|
||||
"""``show port-config``: ``{port: (pvid, egress rule)}``."""
|
||||
ports = {}
|
||||
for line in clean_output(output).splitlines():
|
||||
match = re.match(r"^\s*(\d+)\s+(\d+)\s+\S+\s+\S+\s+(Access|Hybrid|Trunk)\b", line, re.I)
|
||||
if match:
|
||||
ports[int(match.group(1))] = (int(match.group(2)), match.group(3).lower())
|
||||
return ports
|
||||
|
||||
|
||||
def port_membership(vids, pvid, rule):
|
||||
"""Access: untagged; Trunk: all tagged; Hybrid: the PVID untagged, the rest tagged."""
|
||||
if not vids:
|
||||
return None
|
||||
if rule == "access":
|
||||
return _membership(vids)
|
||||
if rule == "trunk":
|
||||
return _membership((), vids)
|
||||
return _membership({pvid} & vids, vids - {pvid})
|
||||
|
||||
|
||||
def parse_ip(output):
|
||||
"""``ip → show``: management address with its VLAN, using the "Current" column."""
|
||||
def current(label):
|
||||
values = _field(output, label).split()
|
||||
return values[-1] if values else ""
|
||||
try:
|
||||
address = ipaddress.ip_interface(f"{current('IP Address')}/{current('IP Mask')}")
|
||||
except ValueError:
|
||||
return None, None
|
||||
vlan = current("VLAN ID")
|
||||
return (None if address.ip.is_unspecified else str(address)), (int(vlan) if vlan.isdigit() else None)
|
||||
|
||||
|
||||
def _lldp_modes(output):
|
||||
"""``lldp → show config``: ``{port: mode}``."""
|
||||
return {int(port): mode.lower() for port, mode in re.findall(
|
||||
r"(?im)^\s*(\d+)\s+(Enabled|Disabled|Rx[ _-]?only|Tx[ _-]?only)\b", clean_output(output or ""))}
|
||||
|
||||
|
||||
def not_receiving(output):
|
||||
"""Ports that drop received LLDP (mode Disabled or Tx only)."""
|
||||
return sorted(port for port, mode in _lldp_modes(output).items() if mode == "disabled" or mode.startswith("tx"))
|
||||
|
||||
|
||||
def lldp_receiving(output):
|
||||
"""``False`` when no port receives LLDP; ``True`` when unknown (no warning)."""
|
||||
modes = _lldp_modes(output)
|
||||
return not modes or len(not_receiving(output)) < len(modes)
|
||||
|
||||
|
||||
def parse_neighbors(output):
|
||||
"""``lldp → show info``: one block per neighbor, ``Label : value`` lines."""
|
||||
neighbors = []
|
||||
blocks = re.split(r"(?im)^(?=\s*Local Port\s*:)", clean_output(output or ""))
|
||||
for block in blocks:
|
||||
local = _field(block, "Local Port")
|
||||
if not local:
|
||||
continue
|
||||
port = re.search(r"(\d+)", local) # "Port 2" → "2", the name of the switch port
|
||||
neighbors.append({
|
||||
"local_port": port.group(1) if port else local,
|
||||
"system_name": _field(block, "System Name"),
|
||||
"remote_port": _field(block, "Port ID") or _field(block, "Port Description"),
|
||||
"port_description": _field(block, "Port Description"),
|
||||
"management_ip": (re.search(r"\b\d{1,3}(?:\.\d{1,3}){3}\b", _field(block, "Management Address"))
|
||||
or [""])[0],
|
||||
"chassis_id": _field(block, "Chassis ID"),
|
||||
"protocol": "LLDP",
|
||||
})
|
||||
return neighbors
|
||||
|
||||
|
||||
def build_snapshot(outputs):
|
||||
status = parse_status(outputs.get("status", ""))
|
||||
config = parse_port_config(outputs.get("port_config", ""))
|
||||
names, members = parse_vlans(outputs.get("vlans", ""))
|
||||
vlan_ports = parse_vlan_ports(outputs.get("vlan_ports", ""))
|
||||
vlans_read = bool(members and vlan_ports)
|
||||
interfaces = []
|
||||
for number in sorted(set(status) | set(config)):
|
||||
vids = {vid for vid, ports in members.items() if number in ports}
|
||||
pvid, rule = vlan_ports.get(number, (1, "hybrid"))
|
||||
values = dict(status.get(number, {}))
|
||||
values["enabled"] = config.get(number, {}).get("enabled", values.get("enabled", True))
|
||||
interfaces.append(_interface(str(number), description=config.get(number, {}).get("description", ""),
|
||||
vlans=port_membership(vids, pvid, rule) if vlans_read else None,
|
||||
lag=None, **values))
|
||||
address, vlan = parse_ip(outputs.get("ip", ""))
|
||||
ip_addresses = []
|
||||
if address:
|
||||
name = f"vlan{vlan}" if vlan else "System"
|
||||
interfaces.append(_interface(name, connected=True, description="Management-Interface", virtual=True,
|
||||
ip_addresses=[address], vlans=None, lag=None))
|
||||
ip_addresses.append({"interface": name, "address": address})
|
||||
neighbors = parse_neighbors(outputs.get("neighbors", ""))
|
||||
by_name = {item["name"]: item for item in interfaces}
|
||||
for neighbor in neighbors:
|
||||
if neighbor["local_port"] in by_name:
|
||||
by_name[neighbor["local_port"]]["neighbor"] = neighbor
|
||||
system = outputs.get("system", "")
|
||||
mac = _field(system, "Host MAC Address")
|
||||
raw = {key: value for key, value in outputs.items() if key != "platform" and isinstance(value, str)}
|
||||
return {
|
||||
"platform": PLATFORM,
|
||||
"interfaces": interfaces,
|
||||
"ip_addresses": ip_addresses,
|
||||
"neighbors": neighbors,
|
||||
"lldp_neighbors": neighbors,
|
||||
"cdp_neighbors": [],
|
||||
"raw": raw,
|
||||
"vlans_read": vlans_read,
|
||||
# No configuration file over the CLI; the readable state serves as backup.
|
||||
"config_backup": "\n\n".join(f"### {mode} → {command}\n{clean_output(outputs.get(key, '')).strip()}"
|
||||
for mode, command, key in COMMANDS if outputs.get(key)),
|
||||
"vlan_names": names,
|
||||
"stack": [],
|
||||
"lldp_disabled": not lldp_receiving(outputs.get("lldp_config", "")),
|
||||
"lldp_enabled_automatically": bool(outputs.get("lldp_enabled_automatically")),
|
||||
"discovered_at": time.time(),
|
||||
"system": {"name": _field(system, "Device Name"), "model": _field(system, "Model Name"),
|
||||
"location": _field(system, "Location"), "mac": mac,
|
||||
"serial": _field(system, "Serial Number"), "firmware": _field(system, "Firmware Version")},
|
||||
}
|
||||
|
||||
|
||||
def reparse(snapshot):
|
||||
"""Rebuild a stored snapshot from its raw outputs with the current parsers.
|
||||
|
||||
Exchange files keep all LANCOM outputs, so parser fixes also apply to older exports.
|
||||
"""
|
||||
raw = snapshot.get("raw") or {}
|
||||
if snapshot.get("platform") != PLATFORM or not raw.get("status"):
|
||||
return snapshot
|
||||
rebuilt = build_snapshot(dict(raw, lldp_enabled_automatically=snapshot.get("lldp_enabled_automatically")))
|
||||
rebuilt["discovered_at"] = snapshot.get("discovered_at", rebuilt["discovered_at"])
|
||||
return rebuilt
|
||||
@@ -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": "…",
|
||||
}
|
||||
+480
-33
@@ -1,5 +1,8 @@
|
||||
"""SSH discovery and NetBox synchronization for HPE and Aruba switches."""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import io
|
||||
import ipaddress
|
||||
import re
|
||||
import threading
|
||||
@@ -8,13 +11,14 @@ from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
from netbox_sync.core.netbox import assign_mac, related_id
|
||||
from netbox_sync.core.netbox import assign_mac, normalize_mac, related_id
|
||||
|
||||
PLATFORMS = {
|
||||
"auto": "Automatisch erkennen",
|
||||
"aruba_cx": "Aruba CX (AOS-CX)",
|
||||
"aruba_aos": "ArubaOS-Switch / ProCurve",
|
||||
"hpe_comware": "HPE Comware",
|
||||
"lancom_sx3": "LANCOM LCOS SX 3.x (GS-23xx)",
|
||||
}
|
||||
|
||||
COMMANDS = {
|
||||
@@ -171,8 +175,9 @@ def _read_available(channel, timeout=20, initialize_session=False):
|
||||
return output
|
||||
|
||||
|
||||
def _run_cli_command(channel, command, timeout=20):
|
||||
channel.send(command + "\n")
|
||||
def _run_cli_command(channel, command, timeout=20, newline="\n"):
|
||||
# LANCOM LCOS SX 3.x only executes a command on "\r" (like PuTTY's Enter); "\n" is just echoed.
|
||||
channel.send(command + newline)
|
||||
try:
|
||||
return _read_available(channel, timeout=timeout)
|
||||
except TimeoutError as error:
|
||||
@@ -257,25 +262,80 @@ def detect_platform(channel, banner):
|
||||
"""Identify the switch OS from prompt and ``show version`` output."""
|
||||
if COMWARE_PROMPT.search(banner):
|
||||
return "hpe_comware"
|
||||
_run_cli_command(channel, "no page")
|
||||
try:
|
||||
_run_cli_command(channel, "no page")
|
||||
except TimeoutError:
|
||||
# The command was only echoed: a CLI that needs "\r" as Enter (LANCOM LCOS SX 3.x).
|
||||
from netbox_sync.core import lancom
|
||||
channel.send("\r")
|
||||
_read_available(channel, timeout=20)
|
||||
if lancom.probe(channel):
|
||||
return lancom.PLATFORM
|
||||
raise
|
||||
version = _run_cli_command(channel, "show version", timeout=30)
|
||||
if re.search(r"(?i)ArubaOS-CX|AOS-CX|\b[A-Z]{2}\.10\.\d+", version):
|
||||
return "aruba_cx"
|
||||
if re.search(r"(?i)Image stamp|ProCurve|\b[A-Z]{1,2}\.1[456]\.\d+", version):
|
||||
return "aruba_aos"
|
||||
if CLI_ERROR.search(version):
|
||||
# LANCOM LCOS SX 3.x has no "show version"; its system information is in the "system" mode.
|
||||
from netbox_sync.core import lancom
|
||||
if lancom.probe(channel):
|
||||
return lancom.PLATFORM
|
||||
display = _run_cli_command(channel, "display version", timeout=30)
|
||||
if re.search(r"(?i)Comware", display):
|
||||
return "hpe_comware"
|
||||
raise RuntimeError("Plattform konnte nicht automatisch erkannt werden – bitte im Switch-Dialog manuell wählen.")
|
||||
|
||||
|
||||
class _SessionRecorder:
|
||||
"""Channel wrapper that records everything sent and received for the raw data view."""
|
||||
|
||||
def __init__(self, channel, session):
|
||||
self._channel = channel
|
||||
self._session = session
|
||||
|
||||
def send(self, data):
|
||||
self._session.append(f"»» {data.strip()}\n" if data.strip() else "»» <Enter>\n")
|
||||
return self._channel.send(data)
|
||||
|
||||
def recv(self, size):
|
||||
data = self._channel.recv(size)
|
||||
self._session.append(data.decode("utf-8", errors="replace"))
|
||||
return data
|
||||
|
||||
def __getattr__(self, name):
|
||||
return getattr(self._channel, name)
|
||||
|
||||
|
||||
def session_text(session):
|
||||
"""The recorded CLI session without passwords, keys and communities."""
|
||||
return mask_config("".join(session))
|
||||
|
||||
|
||||
def run_switch_commands(config, enable_lldp=False, known_hosts=None, log=_noop):
|
||||
"""CLI outputs of a switch; ``outputs["session"]`` is the full recorded session.
|
||||
|
||||
On errors the session up to the failure is attached to the exception as
|
||||
``error.transcript`` so it can be shown as raw data.
|
||||
"""
|
||||
session = []
|
||||
try:
|
||||
outputs = _run_switch_commands(config, enable_lldp, known_hosts, log, session)
|
||||
except Exception as error:
|
||||
error.transcript = session_text(session)
|
||||
raise
|
||||
outputs["session"] = session_text(session)
|
||||
return outputs
|
||||
|
||||
|
||||
def _run_switch_commands(config, enable_lldp, known_hosts, log, session):
|
||||
platform = config.get("platform", "auto")
|
||||
if platform not in PLATFORMS:
|
||||
raise ValueError(f"Nicht unterstützte Switch-Plattform: {platform}")
|
||||
client = _open_client(config, known_hosts, log)
|
||||
try:
|
||||
channel = client.invoke_shell(width=240, height=1000)
|
||||
channel = _SessionRecorder(client.invoke_shell(width=240, height=1000), session)
|
||||
try:
|
||||
banner = _read_available(channel, timeout=45, initialize_session=True)
|
||||
except TimeoutError as error:
|
||||
@@ -283,6 +343,10 @@ def run_switch_commands(config, enable_lldp=False, known_hosts=None, log=_noop):
|
||||
if platform == "auto":
|
||||
platform = detect_platform(channel, banner)
|
||||
log(f"{config.get('name', config['host'])}: Plattform erkannt – {PLATFORMS[platform]}")
|
||||
if platform == "lancom_sx3":
|
||||
from netbox_sync.core import lancom
|
||||
return dict(lancom.run_commands(channel, log, config.get("name", config["host"]), enable_lldp),
|
||||
platform=platform)
|
||||
pager_command, interface_command, neighbor_command = COMMANDS[platform]
|
||||
_run_cli_command(channel, pager_command)
|
||||
|
||||
@@ -608,8 +672,8 @@ def _parse_neighbor_table(output):
|
||||
# VLAN membership from the running configuration
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
_PORT_RANGE = re.compile(r"^(\D*(?:\d+/)*)(\d+)-(?:\1)?(\d+)$")
|
||||
_VLAN_CONFIG_LINE = re.compile(r"(?i)^\s*(?:interface\s|vlan\s|#|exit|\s*(?:no\s+)?routing\b)|vlan|tagged|link-type|link-mode")
|
||||
_PORT_RANGE = re.compile(r"^(\D*(?:\d+/)*[A-Za-z]?)(\d+)-(?:\1)?(\d+)$")
|
||||
_VLAN_CONFIG_LINE = re.compile(r"(?i)^\s*(?:interface\s|vlan\s|#|exit|\s*(?:no\s+)?routing\b)|vlan|tagged|link-type|link-mode|^\s*lag \d|^trunk\s|link-aggregation")
|
||||
|
||||
|
||||
def parse_vlan_list(text):
|
||||
@@ -776,16 +840,104 @@ def vlan_label(vlans, limit=64):
|
||||
return text
|
||||
|
||||
|
||||
def port_label(vlans, lag=None, limit=64):
|
||||
"""NetBox label of a port: its VLANs plus its LAG, e.g. ``10,20 (LAG 1)``."""
|
||||
number = re.search(r"(\d+)$", lag or "")
|
||||
suffix = f"(LAG {number.group(1)})" if number else ""
|
||||
text = vlan_label(vlans, limit - len(suffix) - 1 if suffix else limit)
|
||||
return f"{text} {suffix}".strip()
|
||||
|
||||
|
||||
def parse_lags(config, platform):
|
||||
"""LAG of every member port as ``{interface_key(port): LAG name}``."""
|
||||
lags = {}
|
||||
if platform == "aruba_aos":
|
||||
# "trunk 49-50 trk1 lacp" is a global line.
|
||||
for match in re.finditer(r"(?im)^trunk\s+(\S+)\s+trk(\d+)\b", clean_output(config or "")):
|
||||
for port in _expand_ports(match.group(1)):
|
||||
lags[interface_key(port)] = f"Trk{match.group(2)}"
|
||||
return lags
|
||||
member = {"aruba_cx": (re.compile(r"(?i)^lag (\d+)$"), "lag{}"),
|
||||
"hpe_comware": (re.compile(r"(?i)^port link-aggregation group (\d+)$"), "Bridge-Aggregation{}")}
|
||||
if platform not in member:
|
||||
return lags
|
||||
pattern, name = member[platform]
|
||||
for match, body in _config_blocks(config or "", re.compile(r"^interface\s+(\S+)\s*$", re.I)):
|
||||
group = next((found.group(1) for found in map(pattern.match, body) if found), None)
|
||||
if group:
|
||||
lags[interface_key(match.group(1))] = name.format(group)
|
||||
return lags
|
||||
|
||||
|
||||
# Values after these words are removed from configuration backups.
|
||||
_SECRET = re.compile(r"(?i)\b(password|secret|key|community|ciphertext|plaintext|psk|passphrase)\b(\s+).*$")
|
||||
|
||||
|
||||
def mask_config(config):
|
||||
"""Running configuration without passwords, keys and SNMP communities."""
|
||||
return "\n".join(_SECRET.sub(r"\1\2<entfernt>", line) for line in clean_output(config).splitlines()).strip()
|
||||
|
||||
|
||||
def _vlan_config_excerpt(config):
|
||||
"""Keep only VLAN-related lines – the full configuration may contain secrets."""
|
||||
return "\n".join(line for line in clean_output(config).splitlines() if _VLAN_CONFIG_LINE.search(line))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Stacks (Aruba CX VSF, ArubaOS-Switch stacking/VSF, HPE Comware IRF)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
_STACK_PORT = {
|
||||
"aruba_cx": re.compile(r"^(\d+)/\d+/\d+$"),
|
||||
"aruba_aos": re.compile(r"^(\d+)/[A-Z]?\d+$"),
|
||||
"hpe_comware": re.compile(r"^[A-Za-z][A-Za-z\-]*(\d+)/\d+/\d+$"),
|
||||
}
|
||||
|
||||
|
||||
def stack_member(name, platform):
|
||||
"""Stack member of a port name (``2/1/5`` → 2) or ``None`` for LAGs, VLANs …"""
|
||||
pattern = _STACK_PORT.get(platform)
|
||||
match = pattern.match(name or "") if pattern else None
|
||||
return int(match.group(1)) if match else None
|
||||
|
||||
|
||||
def parse_stack(config, platform, interfaces=()):
|
||||
"""Stack members as ``[{"member", "model", "mac"}]``; empty for a single switch."""
|
||||
members = {}
|
||||
text = clean_output(config or "")
|
||||
if platform == "aruba_cx" or platform == "aruba_aos":
|
||||
for match, body in _config_blocks(text, re.compile(r"^vsf member (\d+)\s*$", re.I)):
|
||||
model = next((re.match(r"(?i)type\s+(\S+)", line).group(1) for line in body
|
||||
if re.match(r"(?i)type\s+\S+", line)), "")
|
||||
members[int(match.group(1))] = {"model": model.strip('"'), "mac": ""}
|
||||
# ArubaOS-Switch: "member 2 type "JL256A" mac-address 9020c2-123456" below "stacking"/"vsf".
|
||||
for match in re.finditer(r'(?im)^\s+member (\d+) type "?([^"\s]+)"?(?:\s+mac-address (\S+))?', text):
|
||||
members.setdefault(int(match.group(1)), {"model": match.group(2), "mac": match.group(3) or ""})
|
||||
elif platform == "hpe_comware":
|
||||
for match in re.finditer(r"(?im)^\s*irf member (\d+)\b", text):
|
||||
members.setdefault(int(match.group(1)), {"model": "", "mac": ""})
|
||||
for interface in interfaces:
|
||||
member = stack_member(interface["name"], platform) if not interface.get("virtual") else None
|
||||
if member is not None:
|
||||
members.setdefault(member, {"model": "", "mac": ""})
|
||||
if len(members) < 2:
|
||||
return []
|
||||
return [dict(members[member], member=member) for member in sorted(members)]
|
||||
|
||||
|
||||
def build_snapshot(outputs, platform):
|
||||
if platform == "lancom_sx3":
|
||||
from netbox_sync.core import lancom
|
||||
return lancom.build_snapshot(outputs)
|
||||
interfaces = parse_interfaces(outputs["interfaces"], platform)
|
||||
vlans = parse_vlans(outputs.get("config", ""), platform)
|
||||
lags = parse_lags(outputs.get("config", ""), platform)
|
||||
for interface in interfaces:
|
||||
interface["vlans"] = vlans.get(interface_key(interface["name"]))
|
||||
interface["lag"] = lags.get(interface_key(interface["name"]))
|
||||
if interface["lag"] and not interface["vlans"]:
|
||||
# Aruba CX/Comware: the VLANs are configured on the LAG and apply to its member ports.
|
||||
interface["vlans"] = vlans.get(interface_key(interface["lag"]))
|
||||
interface_ips = parse_interface_ips(outputs.get("ipv4_interfaces", ""), outputs.get("ipv6_interfaces", ""), platform)
|
||||
lldp_neighbors = parse_neighbors(outputs["neighbors"])
|
||||
cdp_neighbors = parse_cdp_neighbors(outputs.get("cdp_neighbors", ""))
|
||||
@@ -821,7 +973,9 @@ 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")),
|
||||
"config_backup": mask_config(outputs["config"]) if outputs.get("config") else "",
|
||||
"vlan_names": parse_vlan_names(outputs.get("config", "")),
|
||||
"stack": parse_stack(outputs.get("config", ""), platform, interfaces),
|
||||
"lldp_disabled": outputs.get("lldp_disabled", False),
|
||||
"lldp_enabled_automatically": outputs.get("lldp_enabled_automatically", False),
|
||||
"discovered_at": time.time(),
|
||||
@@ -842,6 +996,8 @@ def suggest_platform(*texts):
|
||||
text = " ".join(str(value or "") for value in texts).casefold()
|
||||
if not text.strip():
|
||||
return "auto"
|
||||
if re.search(r"lancom|\bgs-23\d\d", text):
|
||||
return "lancom_sx3"
|
||||
if re.search(r"comware|h3c|\b(?:19[0-9]0|51[234]0|55[01]0|57[01]0|59[0-9]0|75\d\d|10500|12500|12900)\b", text):
|
||||
return "hpe_comware"
|
||||
if re.search(r"aos-?cx|arubaos-?cx|\bcx\b|\b(?:4100i|6000|6100|6200[fm]?|6300[fm]?|6400|8100|8320|8325|8360|8400|9300|10000)\b", text):
|
||||
@@ -1181,6 +1337,61 @@ def _switch_vlan_matches(nb, config, snapshot, tenant_id, site_id):
|
||||
return vlans, match_vlans(snapshot_vlan_ids(snapshot), names, vlans, tenant_id, site_id, config.get("vlan_map"))
|
||||
|
||||
|
||||
def stack_devices(nb, config, snapshot, device):
|
||||
"""``{member: NetBox device or None}`` for a stack, ``{}`` for a single switch.
|
||||
|
||||
Order: the choice stored in the profile (0 = skip the member), the member's
|
||||
position in the NetBox virtual chassis of the switch, else the first member
|
||||
is the switch's own device.
|
||||
"""
|
||||
stack = snapshot.get("stack") or []
|
||||
if not stack:
|
||||
return {}
|
||||
chosen = config.get("stack_devices") or {}
|
||||
by_position = {}
|
||||
chassis = related_id(device, "virtual_chassis")
|
||||
if chassis:
|
||||
for member_device in nb.dcim.devices.filter(virtual_chassis_id=chassis):
|
||||
position = getattr(member_device, "vc_position", None)
|
||||
if position is not None:
|
||||
by_position[int(position)] = member_device
|
||||
first = stack[0]["member"]
|
||||
result = {}
|
||||
for entry in stack:
|
||||
member = entry["member"]
|
||||
if str(member) in chosen:
|
||||
device_id = int(chosen[str(member)] or 0)
|
||||
result[member] = None if not device_id else (device if device_id == device.id
|
||||
else nb.dcim.devices.get(device_id))
|
||||
else:
|
||||
result[member] = by_position.get(member) or (device if member == first else None)
|
||||
return result
|
||||
|
||||
|
||||
def _interface_owners(snapshot, members, device):
|
||||
"""NetBox device per discovered interface; ``None`` = member without device."""
|
||||
platform = snapshot.get("platform")
|
||||
owners = {}
|
||||
for interface in snapshot["interfaces"]:
|
||||
member = None if interface.get("virtual") or not members else stack_member(interface["name"], platform)
|
||||
# LAGs, VLAN interfaces and loopbacks belong to the stack as a whole.
|
||||
owners[interface["name"]] = members[member] if member in members else device
|
||||
return owners
|
||||
|
||||
|
||||
def _match_by_owner(nb, snapshot, owners, manual):
|
||||
groups = {}
|
||||
for interface in snapshot["interfaces"]:
|
||||
owner = owners[interface["name"]]
|
||||
if owner is not None:
|
||||
groups.setdefault(owner.id, (owner, []))[1].append(interface)
|
||||
matches, records = {}, {}
|
||||
for owner_id, (_owner, interfaces) in groups.items():
|
||||
records[owner_id] = list(nb.dcim.interfaces.filter(device_id=owner_id))
|
||||
matches.update(match_interfaces(interfaces, records[owner_id], manual))
|
||||
return matches, records
|
||||
|
||||
|
||||
def plan_switch_sync(nb, config, snapshot):
|
||||
"""Proposals for the review dialog: interface mapping, neighbor devices,
|
||||
networks (VRF and missing prefixes) and missing VLANs."""
|
||||
@@ -1189,8 +1400,10 @@ def plan_switch_sync(nb, config, snapshot):
|
||||
tenant_id, error = _require_tenant(device)
|
||||
if error:
|
||||
return {"error": error}
|
||||
records = list(nb.dcim.interfaces.filter(device_id=device.id))
|
||||
matches = match_interfaces(snapshot["interfaces"], records, config.get("interface_map"))
|
||||
members = stack_devices(nb, config, snapshot, device)
|
||||
owners = _interface_owners(snapshot, members, device)
|
||||
matches, owner_records = _match_by_owner(nb, snapshot, owners, config.get("interface_map"))
|
||||
records = owner_records.get(device.id) or list(nb.dcim.interfaces.filter(device_id=device.id))
|
||||
scope, devices = candidate_devices(nb, device)
|
||||
known = {row["id"] for row in devices}
|
||||
lookup = _RemoteLookup(nb)
|
||||
@@ -1208,6 +1421,11 @@ def plan_switch_sync(nb, config, snapshot):
|
||||
devices.append({"id": remote.id, "name": remote.name})
|
||||
known.add(remote.id)
|
||||
neighbors.append(dict(neighbor, device_id=device_id, method=method))
|
||||
# Stack members may be chosen from the same list (including the switch itself).
|
||||
for member_device in ([device, *filter(None, members.values())] if members else []):
|
||||
if member_device.id not in known:
|
||||
devices.append({"id": member_device.id, "name": member_device.name})
|
||||
known.add(member_device.id)
|
||||
devices.sort(key=lambda row: row["name"].casefold())
|
||||
|
||||
vrf_records = candidate_vrfs(nb, tenant_id)
|
||||
@@ -1251,12 +1469,20 @@ def plan_switch_sync(nb, config, snapshot):
|
||||
"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(without_vlans(item.get("vlans"), ignored_vlans(vlan_map)))}
|
||||
for item in snapshot["interfaces"]
|
||||
"physical": _physical_interface(item), "owner_id": owners[item["name"]].id,
|
||||
"vlan_label": port_label(without_vlans(item.get("vlans"), ignored_vlans(vlan_map)), item.get("lag"))}
|
||||
for item in snapshot["interfaces"] if owners[item["name"]] is not None
|
||||
for record, method in [matches[item["name"]]]
|
||||
],
|
||||
"netbox_interfaces": sorted((record.name for record in records), key=_natural_key),
|
||||
# NetBox interface names per device, for stacks with one device per member.
|
||||
"owner_interfaces": {str(owner_id): sorted((record.name for record in owner_records[owner_id]),
|
||||
key=_natural_key) for owner_id in owner_records},
|
||||
"stack": [dict(entry, device_id=members[entry["member"]].id if members.get(entry["member"]) else None,
|
||||
ports=sum(1 for item in snapshot["interfaces"]
|
||||
if stack_member(item["name"], snapshot.get("platform")) == entry["member"]))
|
||||
for entry in snapshot.get("stack") or []],
|
||||
"skipped_ports": sum(1 for owner in owners.values() if owner is None),
|
||||
"neighbors": neighbors,
|
||||
"device_scope": scope,
|
||||
"devices": devices,
|
||||
@@ -1315,7 +1541,17 @@ class _RemoteLookup:
|
||||
if _physical_record(record) and _port_number(record.name) == number]
|
||||
if len(found) == 1:
|
||||
return found[0]
|
||||
return None
|
||||
# Access points and phones often report their MAC address as port ID.
|
||||
mac = normalize_mac(neighbor.get("remote_port"))
|
||||
if mac:
|
||||
found = [record for record in records.values()
|
||||
if normalize_mac(getattr(record, "mac_address", None)) == mac]
|
||||
if len(found) == 1:
|
||||
return found[0]
|
||||
# An end device with a single port (e.g. an AP from the Sophos import) can only be cabled there.
|
||||
physical = [record for record in records.values()
|
||||
if _physical_record(record) and not getattr(record, "mgmt_only", False)]
|
||||
return physical[0] if len(physical) == 1 else None
|
||||
|
||||
|
||||
_NEW = "new" # placeholder ID of objects a dry run would create
|
||||
@@ -1402,8 +1638,12 @@ def _sync_prefixes(nb, config, snapshot, tenant_id, vrf_ids, dry_run, report):
|
||||
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."""
|
||||
def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report, sites=None):
|
||||
"""``{VLAN ID: NetBox ID}``; missing VLANs are only created when approved.
|
||||
|
||||
``sites`` receives ``{VLAN ID: (site ID or None, name)}`` for the site check of the ports.
|
||||
"""
|
||||
sites = {} if sites is None else sites
|
||||
_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
|
||||
@@ -1411,6 +1651,7 @@ def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report):
|
||||
for vid, (record, method, name) in matches.items():
|
||||
if record is not None:
|
||||
present[vid] = record.id
|
||||
sites[vid] = (related_id(record, "site"), getattr(record, "name", "") or str(vid))
|
||||
continue
|
||||
if method != "new" or vid not in approved:
|
||||
continue
|
||||
@@ -1423,6 +1664,7 @@ def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report):
|
||||
if site_id:
|
||||
payload["site"] = site_id
|
||||
present[vid] = _NEW if dry_run else nb.ipam.vlans.create(payload).id
|
||||
sites[vid] = (site_id, name)
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"VLAN {vid}: {error}")
|
||||
return present
|
||||
@@ -1464,13 +1706,194 @@ 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,
|
||||
"cables_created": 0, "cables_updated": 0, "cables_skipped": 0,
|
||||
"vrfs_created": 0, "prefixes_created": 0, "vlans_created": 0,
|
||||
"changes": [], "errors": [],
|
||||
"changes": [], "errors": [], "notes": [],
|
||||
}
|
||||
|
||||
|
||||
def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=False, log=_noop):
|
||||
def _sync_switch_stack(nb, device, members, dry_run, report):
|
||||
"""Fill in the switch stack of the optional NetBox Utilities plugin.
|
||||
|
||||
The switch's device is the stack switch, the other member devices are
|
||||
added to it; members entered by hand stay. Without the plugin nothing happens.
|
||||
"""
|
||||
others = {member.id: member for member in members.values() if member is not None and member.id != device.id}
|
||||
if not others:
|
||||
return
|
||||
try:
|
||||
endpoint = nb.plugins.utilities.switch_stacks
|
||||
stacks = list(endpoint.filter(device_id=device.id))
|
||||
except AttributeError:
|
||||
return
|
||||
except Exception as error: # noqa: BLE001
|
||||
if getattr(getattr(error, "req", None), "status_code", None) != 404:
|
||||
report["errors"].append(f"Switch-Stack (NetBox Utilities): {error}")
|
||||
return
|
||||
stack = stacks[0] if stacks else None
|
||||
current = [getattr(item, "id", item) for item in (getattr(stack, "members", None) or [])]
|
||||
missing = [member_id for member_id in others if member_id not in current]
|
||||
if not missing:
|
||||
return
|
||||
names = ", ".join(others[member_id].name for member_id in missing)
|
||||
report["changes"].append(f"Switch-Stack {device.name}: Mitglieder {names} eintragen (NetBox Utilities)"
|
||||
if stack else f"Switch-Stack {device.name} neu mit Mitgliedern {names} (NetBox Utilities)")
|
||||
if dry_run:
|
||||
return
|
||||
try:
|
||||
if stack:
|
||||
stack.update({"members": current + missing})
|
||||
else:
|
||||
endpoint.create({"device": device.id, "members": missing})
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"Switch-Stack (NetBox Utilities): {error}")
|
||||
|
||||
|
||||
def _vlans_for_site(vlan_ids, vlan_sites, site_id, owner, reported, report):
|
||||
"""VLANs a port of ``owner`` may use: NetBox only allows global VLANs or VLANs of the device's site.
|
||||
|
||||
Other VLANs stay in the label; each is reported once per device.
|
||||
"""
|
||||
allowed = {}
|
||||
for vid, netbox_id in vlan_ids.items():
|
||||
vlan_site, name = vlan_sites.get(vid, (None, str(vid)))
|
||||
if vlan_site in (None, site_id):
|
||||
allowed[vid] = netbox_id
|
||||
elif (owner.id, vid) not in reported:
|
||||
reported.add((owner.id, vid))
|
||||
report["notes"].append(f"VLAN {vid} „{name}“ gehört zu einem anderen Standort als {owner.name} – "
|
||||
f"nur im Label vermerkt, nicht am Port zugewiesen (VLAN global machen, "
|
||||
f"um es zuzuweisen)")
|
||||
return allowed
|
||||
|
||||
|
||||
def _sync_lag_members(snapshot, owners, records, dry_run, report):
|
||||
"""Assign member ports to their LAG interface (NetBox field ``lag``)."""
|
||||
names = {interface_key(item["name"]): item["name"] for item in snapshot["interfaces"]}
|
||||
for interface in snapshot["interfaces"]:
|
||||
key, lag_key = interface_key(interface["name"]), interface_key(interface.get("lag") or "")
|
||||
if not interface.get("lag") or key not in records or lag_key not in records:
|
||||
continue
|
||||
record, lag_record = records[key], records[lag_key]
|
||||
owner, lag_owner = owners[interface["name"]], owners[names[lag_key]]
|
||||
if owner.id != lag_owner.id:
|
||||
# NetBox only allows a LAG of the same device (or virtual chassis).
|
||||
report["notes"].append(f"Interface {interface['name']}: LAG {names[lag_key]} liegt auf {lag_owner.name} "
|
||||
f"– nur im Label vermerkt")
|
||||
continue
|
||||
if record and lag_record and related_id(record, "lag") == lag_record.id:
|
||||
continue
|
||||
report["changes"].append(f"Interface {record.name if record else interface['name']}: LAG {names[lag_key]}")
|
||||
if not dry_run and record and lag_record:
|
||||
try:
|
||||
record.update({"lag": lag_record.id})
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"Interface {interface['name']}: LAG {names[lag_key]}: {error}")
|
||||
|
||||
|
||||
def _backup_config(nb, device, snapshot, dry_run, report):
|
||||
"""Attach the running configuration to the device (optional netbox-attachments plugin).
|
||||
|
||||
A new attachment is only added when the configuration of this device changed
|
||||
since the last backup; the hash in the description identifies it.
|
||||
"""
|
||||
original = snapshot.get("config_file")
|
||||
if original:
|
||||
# Backup file from the switch's web UI (e.g. D-Link config.bin), attached unchanged.
|
||||
content = base64.b64decode(original["data"])
|
||||
extension = Path(original.get("name") or "config.bin").suffix or ".bin"
|
||||
content_type = "application/octet-stream"
|
||||
else:
|
||||
config = snapshot.get("config_backup")
|
||||
if not config:
|
||||
report["notes"].append("Konfigurations-Backup: keine Konfiguration ausgelesen")
|
||||
return
|
||||
content, extension, content_type = config.encode("utf-8"), ".txt", "text/plain"
|
||||
digest = hashlib.sha256(f"{device.id}\n".encode("utf-8") + content).hexdigest()[:16]
|
||||
try:
|
||||
app = nb.plugins.netbox_attachments
|
||||
known = [item for item in app.netbox_attachments.filter(q=digest)
|
||||
if digest in (getattr(item, "description", "") or "")]
|
||||
except AttributeError:
|
||||
return
|
||||
except Exception as error: # noqa: BLE001
|
||||
if getattr(getattr(error, "req", None), "status_code", None) == 404:
|
||||
report["notes"].append("Konfigurations-Backup übersprungen: Plugin netbox-attachments ist nicht installiert")
|
||||
else:
|
||||
report["errors"].append(f"Konfigurations-Backup: {error}")
|
||||
return
|
||||
if known:
|
||||
return
|
||||
stamp = time.strftime("%Y-%m-%d %H-%M", time.localtime(snapshot.get("discovered_at") or time.time()))
|
||||
name = f"Running-Config {device.name} {stamp}"
|
||||
report["changes"].append(f"Konfigurations-Backup: Anhang „{name}“")
|
||||
if dry_run:
|
||||
return
|
||||
filename = re.sub(r"[^\w.-]+", "_", f"{device.name}_{stamp}") + extension
|
||||
try:
|
||||
attachment = app.netbox_attachments.create({
|
||||
"name": name, "description": f"Running-Config, SHA-256 {digest}",
|
||||
# Older plugin versions keep the parent on the attachment itself.
|
||||
"object_type": "dcim.device", "object_id": device.id,
|
||||
"file": (filename, io.BytesIO(content), content_type),
|
||||
})
|
||||
if hasattr(attachment, "assignments"):
|
||||
# Newer plugin versions assign attachments to objects separately.
|
||||
app.netbox_attachment_assignments.create({"attachment": attachment.id, "object_type": "dcim.device",
|
||||
"object_id": device.id})
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"Konfigurations-Backup: {error}")
|
||||
|
||||
|
||||
def _term(value, key):
|
||||
return value.get(key) if isinstance(value, dict) else getattr(value, key, None)
|
||||
|
||||
|
||||
def _termination_text(termination):
|
||||
item = _term(termination, "object") or {}
|
||||
owner = _term(_term(item, "device") or {}, "name")
|
||||
return f"{owner} {_term(item, 'name')}" if owner else str(_term(item, "name") or _term(termination, "object_id"))
|
||||
|
||||
|
||||
def _check_cable(nb, local, remote, label, update_cables, dry_run, report):
|
||||
"""Compare an existing cable of a switch port with its LLDP/CDP neighbor.
|
||||
|
||||
NetBox is the source of truth: a different far end is only reported unless
|
||||
``update_cables`` is set. Cables to patch panels (front/rear ports) or with
|
||||
several terminations are never touched.
|
||||
"""
|
||||
cable = nb.dcim.cables.get(related_id(local, "cable"))
|
||||
if cable is None:
|
||||
report["cables_skipped"] += 1
|
||||
return
|
||||
sides = [list(_term(cable, "a_terminations") or []), list(_term(cable, "b_terminations") or [])]
|
||||
local_side = next((side for side in sides if any(_term(item, "object_id") == local.id for item in side)), None)
|
||||
far = sides[1] if local_side is sides[0] else sides[0]
|
||||
if local_side is None or len(far) != 1 or _term(far[0], "object_type") != "dcim.interface":
|
||||
report["cables_skipped"] += 1
|
||||
return
|
||||
if _term(far[0], "object_id") == remote.id:
|
||||
report["cables_skipped"] += 1
|
||||
return
|
||||
old = _termination_text(far[0])
|
||||
remote_cable = related_id(remote, "cable")
|
||||
if not update_cables or (remote_cable and remote_cable != cable.id):
|
||||
reason = ("Gegenstelle hat bereits ein anderes Kabel" if update_cables
|
||||
else "„Bestehende Kabel anpassen“ ist aus")
|
||||
report["notes"].append(f"Kabel {label}: in NetBox mit {old} verbunden – nicht angepasst ({reason})")
|
||||
return
|
||||
report["cables_updated"] += 1
|
||||
report["changes"].append(f"⚠ Kabel {label}: ersetzt bisherige Gegenstelle {old}")
|
||||
if not dry_run:
|
||||
cable.update({
|
||||
"a_terminations": [{"object_type": "dcim.interface", "object_id": local.id}],
|
||||
"b_terminations": [{"object_type": "dcim.interface", "object_id": remote.id}],
|
||||
})
|
||||
remote.cable = cable
|
||||
|
||||
|
||||
def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=False, log=_noop,
|
||||
backup_config=False, update_cables=False):
|
||||
"""Write a discovery snapshot to NetBox.
|
||||
|
||||
With ``dry_run`` nothing is written; the returned report lists what would
|
||||
@@ -1487,17 +1910,31 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
device_id = device.id
|
||||
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)
|
||||
vlan_sites = {}
|
||||
vlan_ids = _sync_vlans(nb, config, snapshot, tenant_id, related_id(device, "site"), dry_run, report, vlan_sites)
|
||||
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 = {}
|
||||
members = stack_devices(nb, config, snapshot, device)
|
||||
owners = _interface_owners(snapshot, members, device)
|
||||
matches, _owner_records = _match_by_owner(nb, snapshot, owners, config.get("interface_map"))
|
||||
own_devices = {device_id} | {member.id for member in members.values() if member is not None}
|
||||
for member, member_device in members.items():
|
||||
if member_device is None:
|
||||
skipped = sum(1 for name, owner in owners.items() if owner is None
|
||||
and stack_member(name, snapshot.get("platform")) == member)
|
||||
report["notes"].append(f"Stack-Mitglied {member}: kein NetBox-Gerät gewählt – {skipped} Ports übersprungen")
|
||||
_sync_switch_stack(nb, device, members, dry_run, report)
|
||||
records, foreign = {}, set()
|
||||
|
||||
for interface in snapshot["interfaces"]:
|
||||
key = interface_key(interface["name"])
|
||||
owner = owners[interface["name"]]
|
||||
if owner is None:
|
||||
continue
|
||||
record, method = matches[interface["name"]]
|
||||
where = f" auf {owner.name}" if owner.id != device_id else ""
|
||||
port = dict(interface, vlans=without_vlans(interface.get("vlans"), ignored))
|
||||
label = vlan_label(port["vlans"])
|
||||
label = port_label(port["vlans"], interface.get("lag"))
|
||||
owner_vlans = _vlans_for_site(vlan_ids, vlan_sites, related_id(owner, "site"), owner, foreign, report)
|
||||
try:
|
||||
if record:
|
||||
changes = {}
|
||||
@@ -1507,7 +1944,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))
|
||||
changes.update(_vlan_assignment(port, owner_vlans, record))
|
||||
if changes:
|
||||
report["interfaces_updated"] += 1
|
||||
texts = []
|
||||
@@ -1518,25 +1955,25 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
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)}")
|
||||
report["changes"].append(f"Interface {target}{where}: {', '.join(texts)}")
|
||||
if not dry_run:
|
||||
record.update(changes)
|
||||
else:
|
||||
report["interfaces_unchanged"] += 1
|
||||
else:
|
||||
payload = {
|
||||
"device": device_id,
|
||||
"device": owner.id,
|
||||
"name": interface["name"],
|
||||
"type": netbox_interface_type(interface),
|
||||
"enabled": bool(interface.get("enabled", True)),
|
||||
}
|
||||
if label:
|
||||
payload["label"] = label
|
||||
payload.update(_vlan_assignment(port, vlan_ids))
|
||||
payload.update(_vlan_assignment(port, owner_vlans))
|
||||
if interface.get("description"):
|
||||
payload["description"] = interface["description"][:200]
|
||||
report["interfaces_created"] += 1
|
||||
report["changes"].append(f"Interface {interface['name']} neu ({payload['type']})"
|
||||
report["changes"].append(f"Interface {interface['name']}{where} neu ({payload['type']})"
|
||||
+ (f", Label „{label}“" if label else ""))
|
||||
if not dry_run:
|
||||
record = nb.dcim.interfaces.create(payload)
|
||||
@@ -1546,6 +1983,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"Interface {interface['name']}: {error}")
|
||||
|
||||
_sync_lag_members(snapshot, owners, records, dry_run, report)
|
||||
|
||||
for interface in snapshot["interfaces"]:
|
||||
key = interface_key(interface["name"])
|
||||
if key not in records:
|
||||
@@ -1598,9 +2037,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
if key not in records:
|
||||
continue
|
||||
local = records[key]
|
||||
if local is not None and getattr(local, "cable", None):
|
||||
report["cables_skipped"] += 1
|
||||
continue
|
||||
existing = getattr(local, "cable", None) if local is not None else None
|
||||
if neighbor["local_port"] in manual_devices:
|
||||
# 0 means "no device" was chosen in the review dialog.
|
||||
chosen = int(manual_devices[neighbor["local_port"]] or 0)
|
||||
@@ -1610,9 +2047,15 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
if not remote_device:
|
||||
report["cables_skipped"] += 1
|
||||
continue
|
||||
if remote_device.id == device_id:
|
||||
if remote_device.id in own_devices:
|
||||
continue
|
||||
remote = lookup.interface(remote_device, neighbor)
|
||||
if existing:
|
||||
if remote:
|
||||
_check_cable(nb, local, remote, f"{device.name} {label}", update_cables, dry_run, report)
|
||||
else:
|
||||
report["cables_skipped"] += 1
|
||||
continue
|
||||
if not remote or getattr(remote, "cable", None):
|
||||
report["cables_skipped"] += 1
|
||||
continue
|
||||
@@ -1628,12 +2071,16 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
remote.cable = True # avoid a second cable from the reverse direction
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"Nachbar {label}: {error}")
|
||||
if backup_config:
|
||||
_backup_config(nb, device, snapshot, dry_run, report)
|
||||
return report
|
||||
|
||||
|
||||
def describe_snapshot(snapshot):
|
||||
stack = snapshot.get("stack") or []
|
||||
return (
|
||||
f"{len(snapshot['interfaces'])} Schnittstellen, {len(snapshot.get('ip_addresses', []))} IP-Adressen, "
|
||||
(f"Stack mit {len(stack)} Mitgliedern, " if stack else "")
|
||||
+ f"{len(snapshot['interfaces'])} Schnittstellen, {len(snapshot.get('ip_addresses', []))} IP-Adressen, "
|
||||
f"{len(snapshot.get('lldp_neighbors', []))} LLDP- und {len(snapshot.get('cdp_neighbors', []))} CDP-Nachbarn"
|
||||
)
|
||||
|
||||
+102
-13
@@ -1,6 +1,7 @@
|
||||
"""Long-running operations started from the UI. Everything here runs in background tasks."""
|
||||
|
||||
import threading
|
||||
from pathlib import Path
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
@@ -8,11 +9,11 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from PySide6.QtCore import QTimer
|
||||
from PySide6.QtWidgets import QFileDialog
|
||||
|
||||
from netbox_sync.core import exchange, netbox
|
||||
from netbox_sync.core import backups, exchange, lancom, netbox
|
||||
from netbox_sync.core.client_sync import ClientSyncEngine
|
||||
from netbox_sync.core.clients import ClientScanError, expand_targets, new_row, query_ad, scan_clients
|
||||
from netbox_sync.core.config import known_hosts_path
|
||||
from netbox_sync.core.netbox import NetBoxError, related_name
|
||||
from netbox_sync.core.netbox import NetBoxError, related_id, related_name
|
||||
from netbox_sync.core.switches import (
|
||||
PLATFORMS,
|
||||
describe_snapshot,
|
||||
@@ -42,8 +43,13 @@ def _device_row(device):
|
||||
tenant = related_name(device, "tenant")
|
||||
role = related_name(device, "role") or related_name(device, "device_role")
|
||||
name = str(device.name)
|
||||
chassis = getattr(device, "virtual_chassis", None)
|
||||
return {
|
||||
"id": device.id,
|
||||
"chassis": related_id(device, "virtual_chassis"),
|
||||
"chassis_master": related_id(chassis, "master") if chassis is not None else None,
|
||||
"vc_position": getattr(device, "vc_position", None),
|
||||
"stack_of": "",
|
||||
"name": name,
|
||||
"site": site,
|
||||
"tenant": tenant,
|
||||
@@ -56,6 +62,23 @@ def _device_row(device):
|
||||
}
|
||||
|
||||
|
||||
def _merge_stacks(rows):
|
||||
"""Stack members are read through one SSH session: point them at the chassis master and its address."""
|
||||
chassis = {}
|
||||
for row in rows:
|
||||
if row["chassis"]:
|
||||
chassis.setdefault(row["chassis"], []).append(row)
|
||||
for members in chassis.values():
|
||||
master = next((row for row in members if row["id"] == row["chassis_master"]), None)
|
||||
master = master or min(members, key=lambda row: (not row["host"], row["vc_position"] or 0, row["name"]))
|
||||
host = master["host"] or next((row["host"] for row in members if row["host"]), "")
|
||||
master["host"] = host
|
||||
for row in members:
|
||||
if row is not master:
|
||||
row.update(host=host, stack_of=master["name"], stack_master=master["id"])
|
||||
return rows
|
||||
|
||||
|
||||
class Actions:
|
||||
def __init__(self, window):
|
||||
self.window = window
|
||||
@@ -297,6 +320,7 @@ class Actions:
|
||||
return
|
||||
snapshots, added = exchange.merge_switches(self.state.switches, data["switches"], lambda: uuid.uuid4().hex)
|
||||
for switch_id, snapshot in snapshots.items():
|
||||
snapshot = lancom.reparse(snapshot)
|
||||
self.state.switch_snapshots[switch_id] = snapshot
|
||||
self.state.switch_status[switch_id] = ("ok", "aus Datei · " + describe_snapshot(snapshot))
|
||||
if added:
|
||||
@@ -306,6 +330,50 @@ class Actions:
|
||||
logger("switch").log(25, "%s", text)
|
||||
self.window.toast(text)
|
||||
|
||||
def import_switch_backups(self):
|
||||
"""One-off import of D-Link/Linksys configuration backups instead of SSH."""
|
||||
if self.state.profile is None:
|
||||
return
|
||||
paths, _filter = QFileDialog.getOpenFileNames(self.window, "Switch-Backup importieren", "",
|
||||
backups.FILE_FILTER)
|
||||
if not paths:
|
||||
return
|
||||
devices = {row["name"].casefold(): row for row in self.state.netbox_devices or []}
|
||||
items, failures = [], []
|
||||
for path in paths:
|
||||
name = Path(path).name
|
||||
try:
|
||||
switch, snapshot = backups.parse_backup(Path(path).read_bytes(), name)
|
||||
except (OSError, backups.BackupError) as error:
|
||||
failures.append(f"{name}: {error}")
|
||||
continue
|
||||
switch["name"] = switch["name"] or Path(path).stem
|
||||
device = devices.get(switch["name"].casefold())
|
||||
items.append({"switch": {"name": device["name"] if device else switch["name"],
|
||||
"device_id": device["id"] if device else None,
|
||||
"platform": switch["platform"], "host": switch["host"], "port": 22},
|
||||
"snapshot": snapshot, "file": name})
|
||||
if items:
|
||||
snapshots, added = exchange.merge_switches(self.state.switches, items, lambda: uuid.uuid4().hex)
|
||||
by_id = {switch["id"]: switch for switch in self.state.switches}
|
||||
for switch_id, snapshot in snapshots.items():
|
||||
self.state.switch_snapshots[switch_id] = snapshot
|
||||
self.state.switch_status[switch_id] = ("ok", "aus Backup · " + describe_snapshot(snapshot))
|
||||
stored = by_id.get(switch_id)
|
||||
if stored and stored.get("platform", "auto") == "auto":
|
||||
stored["platform"] = snapshot["platform"]
|
||||
self.state.touch()
|
||||
if added:
|
||||
self.state.touch()
|
||||
self.state.switches_changed.emit()
|
||||
names = ", ".join(item["switch"]["name"] for item in items)
|
||||
logger("switch").log(25, "Backup importiert: %s", names)
|
||||
self.window.toast(f"{len(items)} Switch-Backup(s) geladen" + (f", {added} neu im Profil" if added else "")
|
||||
+ " – jetzt „Nach NetBox übertragen“ wählen")
|
||||
if failures:
|
||||
widgets.message(self.window, "Nicht alle Backups gelesen",
|
||||
f"{len(items)} von {len(paths)} Datei(en) importiert.", "warning", "\n".join(failures))
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Switches
|
||||
# ------------------------------------------------------------------
|
||||
@@ -319,7 +387,7 @@ class Actions:
|
||||
nb = connect(ctx)
|
||||
ctx.log("Lade NetBox-Geräte …")
|
||||
devices = list(nb.dcim.devices.all())
|
||||
rows = [_device_row(device) for device in devices if getattr(device, "name", None)]
|
||||
rows = _merge_stacks([_device_row(device) for device in devices if getattr(device, "name", None)])
|
||||
skipped = len(devices) - len(rows)
|
||||
ctx.log(f"{len(rows)} Geräte geladen" + (f" ({skipped} ohne Namen übersprungen)" if skipped else ""),
|
||||
"success")
|
||||
@@ -336,7 +404,8 @@ class Actions:
|
||||
on_error=self._netbox_failed)
|
||||
|
||||
def discover_switches(self, switches):
|
||||
switches = [dict(switch) for switch in switches if switch.get("enabled", True)]
|
||||
switches = [dict(switch) for switch in switches if switch.get("enabled", True)
|
||||
and switch.get("platform") not in backups.BACKUP_PLATFORMS]
|
||||
if not switches:
|
||||
widgets.message(self.window, "Keine aktiven Switche", "Die ausgewählten Switche sind deaktiviert.", "info")
|
||||
return
|
||||
@@ -345,7 +414,7 @@ class Actions:
|
||||
known_hosts = known_hosts_path()
|
||||
|
||||
def work(ctx):
|
||||
snapshots, failures = {}, {}
|
||||
snapshots, failures, transcripts = {}, {}, {}
|
||||
ctx.progress(0, len(switches), "Verbinde …")
|
||||
with ThreadPoolExecutor(max_workers=min(parallel, len(switches))) as pool:
|
||||
futures = {}
|
||||
@@ -367,16 +436,28 @@ class Actions:
|
||||
ctx.log(f"{switch['name']}: keine Schnittstellen erkannt – bitte SSH-Rohdaten prüfen",
|
||||
"warning")
|
||||
except Exception as error: # noqa: BLE001
|
||||
failures[switch["id"]] = str(error)
|
||||
ctx.log(f"{switch['name']}: {error}", "error")
|
||||
problem = str(error)
|
||||
if "getaddrinfo" in problem:
|
||||
problem = (f"Host „{switch['host']}“ ist nicht auflösbar (keine Primär-IP in NetBox?). "
|
||||
"Stack-Mitglieder werden über den Stack-Master ausgelesen und können aus "
|
||||
"dem Profil entfernt werden.")
|
||||
failures[switch["id"]] = problem
|
||||
if getattr(error, "transcript", ""):
|
||||
transcripts[switch["id"]] = error.transcript
|
||||
ctx.log(f"{switch['name']}: {problem}", "error")
|
||||
ctx.progress(done, len(switches), switch["name"])
|
||||
if ctx.cancelled:
|
||||
for pending in futures:
|
||||
pending.cancel()
|
||||
return snapshots, failures
|
||||
return snapshots, failures, transcripts
|
||||
|
||||
def success(result):
|
||||
snapshots, failures = result
|
||||
snapshots, failures, transcripts = result
|
||||
for switch_id in snapshots:
|
||||
self.state.switch_failed_raw.pop(switch_id, None)
|
||||
for switch_id in failures:
|
||||
self.state.switch_failed_raw.pop(switch_id, None)
|
||||
self.state.switch_failed_raw.update(transcripts)
|
||||
by_id = {switch["id"]: switch for switch in self.state.switches}
|
||||
platform_updates = 0
|
||||
for switch_id, snapshot in snapshots.items():
|
||||
@@ -405,6 +486,8 @@ class Actions:
|
||||
if not self.require_netbox_config():
|
||||
return
|
||||
by_id = {switch["id"]: switch for switch in self.state.switches}
|
||||
backup = self.state.settings.get("backup_config")
|
||||
update_cables = create_cables and bool(self.state.settings.get("update_cables"))
|
||||
# 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", {})
|
||||
@@ -433,6 +516,7 @@ 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 member["device_id"] for member in item.get("stack", []))
|
||||
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)
|
||||
@@ -470,7 +554,8 @@ class Actions:
|
||||
for index, (switch, snapshot) in enumerate(items):
|
||||
ctx.progress(index, len(items), switch["name"])
|
||||
ctx.log(f"{switch['name']}: berechne Änderungen …")
|
||||
reports.append((switch, sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=True)))
|
||||
reports.append((switch, sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=True,
|
||||
backup_config=backup, update_cables=update_cables)))
|
||||
return nb, reports
|
||||
|
||||
def show_preview(result):
|
||||
@@ -481,22 +566,26 @@ class Actions:
|
||||
# follow-up task is not rejected as "still busy".
|
||||
dialog = SyncPreviewDialog(self.window, reports, create_cables)
|
||||
if dialog.exec():
|
||||
self._apply_switch_sync(nb, items, create_cables, log)
|
||||
self._apply_switch_sync(nb, items, create_cables, log, update_cables)
|
||||
QTimer.singleShot(0, ask)
|
||||
|
||||
self.tasks.run(plan, title="Zuordnung ermitteln", area="switch", on_success=review,
|
||||
on_error=self._netbox_failed)
|
||||
|
||||
def _apply_switch_sync(self, nb, items, create_cables, log):
|
||||
def _apply_switch_sync(self, nb, items, create_cables, log, update_cables=False):
|
||||
def work(ctx):
|
||||
reports = []
|
||||
for index, (switch, snapshot) in enumerate(items):
|
||||
ctx.check_cancelled()
|
||||
ctx.progress(index, len(items), switch["name"])
|
||||
ctx.log(f"{switch['name']}: übertrage nach NetBox …")
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=False)
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=False,
|
||||
backup_config=self.state.settings.get("backup_config"),
|
||||
update_cables=update_cables)
|
||||
for error in report["errors"]:
|
||||
ctx.log(f"{switch['name']}: {error}", "error")
|
||||
for note in report.get("notes", []):
|
||||
ctx.log(f"{switch['name']}: {note}", "warning")
|
||||
reports.append((switch, report))
|
||||
return reports
|
||||
|
||||
|
||||
+124
-26
@@ -1,5 +1,6 @@
|
||||
"""Modal dialogs for editing connections and reviewing changes."""
|
||||
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from PySide6.QtCore import QThreadPool, Qt
|
||||
@@ -368,7 +369,9 @@ class AddSwitchesDialog(_Dialog):
|
||||
width=980)
|
||||
self.resize(1080, 720)
|
||||
self.result = []
|
||||
self.rows = [dict(device, added=device["id"] in existing_device_ids) for device in devices]
|
||||
self.rows = [dict(device, added=device.get("stack_master", device["id"]) in existing_device_ids)
|
||||
for device in devices]
|
||||
self.by_id = {row["id"]: row for row in self.rows}
|
||||
|
||||
filters = QHBoxLayout()
|
||||
filters.setSpacing(8)
|
||||
@@ -402,8 +405,8 @@ class AddSwitchesDialog(_Dialog):
|
||||
Column("host", "SSH-Host", 130),
|
||||
Column("platform", "Plattform", 160, value=lambda row: PLATFORMS[row["platform"]],
|
||||
color=lambda row: "text_faint" if row["platform"] == "auto" else None),
|
||||
Column("added", "", 110, value=lambda row: "bereits im Profil" if row["added"] else "",
|
||||
color=lambda row: "text_faint"),
|
||||
Column("added", "", 170, value=lambda row: "bereits im Profil" if row["added"] else (
|
||||
f"Stack von {row['stack_of']}" if row.get("stack_of") else ""), color=lambda row: "text_faint"),
|
||||
]
|
||||
self.model = RowTableModel(columns, checkable=True, row_id=lambda row: row["id"])
|
||||
self.model.set_rows(self.rows)
|
||||
@@ -491,6 +494,16 @@ class AddSwitchesDialog(_Dialog):
|
||||
self.show_error("Bitte Benutzer und Passwort für den SSH-Zugang angeben.")
|
||||
return
|
||||
platform = self.platform.currentData()
|
||||
# a stack is read once through its master; every member is mapped in the review
|
||||
masters = {}
|
||||
for row in chosen:
|
||||
master = self.by_id.get(row.get("stack_master"), row)
|
||||
if not master["added"]:
|
||||
masters.setdefault(master["id"], master)
|
||||
chosen = list(masters.values())
|
||||
if not chosen:
|
||||
self.show_error("Die ausgewählten Stack-Mitglieder sind über ihren Stack bereits im Profil.")
|
||||
return
|
||||
self.result = [{
|
||||
"id": uuid.uuid4().hex,
|
||||
"name": row["name"],
|
||||
@@ -533,9 +546,14 @@ class SyncPreviewDialog(_Dialog):
|
||||
items.append((f"{totals[key]} {text}", "info"))
|
||||
if create_cables:
|
||||
items.append((f"{totals.get('cables_created', 0)} Kabel", "info"))
|
||||
if totals.get("cables_updated"):
|
||||
items.append((f"{totals['cables_updated']} Kabel angepasst", "error"))
|
||||
errors = sum(len(report["errors"]) for _switch, report in reports)
|
||||
if errors:
|
||||
items.append((f"{errors} Probleme", "error"))
|
||||
notes = sum(len(report.get("notes", [])) for _switch, report in reports)
|
||||
if notes:
|
||||
items.append((f"{notes} Hinweis(e)", "warning"))
|
||||
for text, kind in items:
|
||||
summary.addWidget(Badge(text, kind))
|
||||
summary.addStretch(1)
|
||||
@@ -551,7 +569,9 @@ class SyncPreviewDialog(_Dialog):
|
||||
changes = report["changes"]
|
||||
total_changes += len(changes)
|
||||
unchanged = report["interfaces_unchanged"]
|
||||
top = QTreeWidgetItem([f"{switch['name']} — {len(changes)} Änderung(en), {unchanged} Interface(s) unverändert"])
|
||||
hints = len(report.get("notes", []))
|
||||
top = QTreeWidgetItem([f"{switch['name']} — {len(changes)} Änderung(en), {unchanged} Interface(s) unverändert"
|
||||
+ (f", {hints} Hinweis(e)" if hints else "")])
|
||||
top.setIcon(0, icon("network", theme.color("accent")))
|
||||
font = top.font(0)
|
||||
font.setBold(True)
|
||||
@@ -560,10 +580,27 @@ class SyncPreviewDialog(_Dialog):
|
||||
child = QTreeWidgetItem([error])
|
||||
child.setIcon(0, icon("warning", theme.color("danger")))
|
||||
top.addChild(child)
|
||||
for note in report.get("notes", []):
|
||||
child = QTreeWidgetItem([note])
|
||||
child.setIcon(0, icon("info", theme.color("warning")))
|
||||
top.addChild(child)
|
||||
members = {}
|
||||
for change in changes[:2000]:
|
||||
top.addChild(QTreeWidgetItem([change]))
|
||||
# stack member ports read "Interface X (Y) auf <member>: …" – group them under the member
|
||||
found = re.match(r"(Interface .+?) auf ([^:]+): (.*)$", change)
|
||||
if not found:
|
||||
top.addChild(QTreeWidgetItem([change]))
|
||||
continue
|
||||
if found.group(2) not in members:
|
||||
members[found.group(2)] = QTreeWidgetItem([found.group(2)])
|
||||
members[found.group(2)].setIcon(0, icon("network", theme.color("text_muted")))
|
||||
members[found.group(2)].addChild(QTreeWidgetItem([f"{found.group(1)}: {found.group(3)}"]))
|
||||
for member in members.values():
|
||||
member.setText(0, f"{member.text(0)} — {member.childCount()} Änderung(en)")
|
||||
top.addChild(member)
|
||||
member.setExpanded(True)
|
||||
tree.addTopLevelItem(top)
|
||||
top.setExpanded(len(reports) == 1 or bool(report["errors"]))
|
||||
top.setExpanded(len(reports) == 1 or bool(report["errors"]) or bool(hints))
|
||||
self.root.addWidget(tree, 1)
|
||||
if total_changes == 0:
|
||||
self.root.addWidget(Banner("NetBox ist bereits auf dem aktuellen Stand – es gibt nichts zu übertragen.", "success"))
|
||||
@@ -598,6 +635,37 @@ class SwitchMappingDialog(_Dialog):
|
||||
self._new_vrf_names = []
|
||||
tabs = QTabWidget()
|
||||
|
||||
# Stack ---------------------------------------------------------------
|
||||
self.stack_rows = []
|
||||
stacks = [(switch, plan) for switch, plan in plans if plan.get("stack")]
|
||||
if stacks:
|
||||
stack_page = QWidget()
|
||||
stack_layout = QVBoxLayout(stack_page)
|
||||
stack_layout.setContentsMargins(0, 12, 0, 0)
|
||||
stack_layout.addWidget(label(
|
||||
"Der Switch ist ein Stack. Jedes Mitglied wird einem eigenen NetBox-Gerät zugeordnet, die Ports "
|
||||
"kommen an das Gerät ihres Mitglieds (2/1/5 an das Gerät von Mitglied 2). LAGs und VLAN-Interfaces "
|
||||
"bleiben am Gerät des Switch-Eintrags. Vorschlag: Positionen im Virtual Chassis von NetBox.",
|
||||
muted=True, wrap=True))
|
||||
self.stack_table = QTableWidget(0, 5)
|
||||
self.stack_table.setHorizontalHeaderLabels(["Switch", "Mitglied", "Modell", "Ports", "NetBox-Gerät"])
|
||||
for switch, plan in stacks:
|
||||
items = [("– Ports überspringen –", 0)] + [(device["name"], device["id"]) for device in plan["devices"]]
|
||||
for entry in plan["stack"]:
|
||||
row = self.stack_table.rowCount()
|
||||
self.stack_table.insertRow(row)
|
||||
texts = (switch["name"], str(entry["member"]), entry["model"], str(entry["ports"]))
|
||||
for column, text in enumerate(texts):
|
||||
self.stack_table.setItem(row, column, QTableWidgetItem(text))
|
||||
combo = SearchableComboBox("Gerät suchen …")
|
||||
combo.set_items(items, entry["device_id"] or 0)
|
||||
self.stack_table.setCellWidget(row, 4, combo)
|
||||
self.stack_rows.append((switch, entry, combo))
|
||||
self._prepare_table(self.stack_table, (160, 80, 120, 70, 320))
|
||||
stack_layout.addWidget(self.stack_table, 1)
|
||||
open_members = sum(1 for _switch, entry, _combo in self.stack_rows if not entry["device_id"])
|
||||
tabs.addTab(stack_page, f"Stack ({open_members} ohne Gerät)" if open_members else "Stack")
|
||||
|
||||
# Interfaces --------------------------------------------------------
|
||||
interface_page = QWidget()
|
||||
interface_layout = QVBoxLayout(interface_page)
|
||||
@@ -610,10 +678,12 @@ class SwitchMappingDialog(_Dialog):
|
||||
self.interface_rows = []
|
||||
for switch, plan in plans:
|
||||
vlans = {item["name"]: item["vlan_label"] for item in plan["interfaces"]}
|
||||
choices = [("+ neu anlegen", self.NEW)] + [(name, name) for name in plan["netbox_interfaces"]]
|
||||
for item in plan["interfaces"]:
|
||||
if not item["physical"] and item["method"] in ("name", "new"):
|
||||
continue
|
||||
# In a stack every member has its own NetBox device and interfaces.
|
||||
names = plan.get("owner_interfaces", {}).get(str(item.get("owner_id")), plan["netbox_interfaces"])
|
||||
choices = [("+ neu anlegen", self.NEW)] + [(name, name) for name in names]
|
||||
row = self.interface_table.rowCount()
|
||||
self.interface_table.insertRow(row)
|
||||
combo = QComboBox()
|
||||
@@ -897,17 +967,30 @@ class SwitchMappingDialog(_Dialog):
|
||||
result = {switch["id"]: {"interface_map": dict(switch.get("interface_map") or {}),
|
||||
"neighbor_devices": dict(switch.get("neighbor_devices") or {})}
|
||||
for switch, _plan in self.plans}
|
||||
# Members moved to another device: their port choices refer to the old
|
||||
# device and are dropped, so the ports are matched again automatically.
|
||||
moved = set()
|
||||
for switch, entry, combo in self.stack_rows:
|
||||
chosen = int(combo.valid_data() or 0)
|
||||
result[switch["id"]].setdefault("stack_devices", {})[str(entry["member"])] = chosen
|
||||
if chosen != (entry["device_id"] or 0) and entry["device_id"]:
|
||||
moved.add((switch["id"], entry["device_id"]))
|
||||
used = {}
|
||||
for _row, switch, item, combo in self.interface_rows:
|
||||
if (switch["id"], item.get("owner_id")) in moved:
|
||||
result[switch["id"]]["interface_map"].pop(item["name"], None)
|
||||
continue
|
||||
chosen = combo.currentData()
|
||||
target = "" if chosen == self.NEW else chosen
|
||||
mapping = result[switch["id"]]["interface_map"]
|
||||
if target and (switch["id"], target) in used:
|
||||
# Stack members have their own devices, so equal names are only a clash on the same device.
|
||||
key = (switch["id"], item.get("owner_id"), target)
|
||||
if target and key in used:
|
||||
self.show_error(f"{switch['name']}: „{target}“ ist mehreren Schnittstellen zugeordnet "
|
||||
f"({used[(switch['id'], target)]}, {item['name']}).")
|
||||
f"({used[key]}, {item['name']}).")
|
||||
return
|
||||
if target:
|
||||
used[(switch["id"], target)] = item["name"]
|
||||
used[key] = item["name"]
|
||||
# Plain name matches stay automatic; everything else is remembered.
|
||||
if item["method"] == "name" and target == item["netbox_name"]:
|
||||
mapping.pop(item["name"], None)
|
||||
@@ -955,17 +1038,22 @@ class RawDataDialog(_Dialog):
|
||||
SECTIONS = {
|
||||
"interfaces": "Schnittstellen", "ipv4_interfaces": "IPv4", "ipv6_interfaces": "IPv6",
|
||||
"neighbors": "LLDP", "cdp_neighbors": "CDP", "vlan_config": "VLAN-Konfiguration", "lldp_status": "LLDP-Status",
|
||||
# LANCOM LCOS SX 3.x
|
||||
"system": "System", "status": "Port-Status", "port_config": "Port-Konfiguration", "vlans": "VLANs",
|
||||
"vlan_ports": "VLAN-Ports", "ip": "IP", "lldp_config": "LLDP-Konfiguration",
|
||||
"session": "Sitzung",
|
||||
}
|
||||
|
||||
def __init__(self, parent, items, selected_id=None):
|
||||
super().__init__(parent, "SSH-Rohdaten", "Unveränderte Ausgaben der Switch-CLI – hilfreich bei der Fehlersuche.",
|
||||
width=900)
|
||||
super().__init__(parent, "SSH-Rohdaten", "Unveränderte Ausgaben der Switch-CLI – hilfreich bei der Fehlersuche. "
|
||||
"„Sitzung“ zeigt den kompletten Ablauf, bei Fehlern bis zum Abbruch.", width=900)
|
||||
self.resize(1040, 700)
|
||||
self.items = items
|
||||
top = QHBoxLayout()
|
||||
self.switch_combo = QComboBox()
|
||||
for switch, _snapshot in items:
|
||||
self.switch_combo.addItem(f"{switch['name']} ({switch['host']})", switch["id"])
|
||||
for switch, snapshot in items:
|
||||
suffix = " – abgebrochen" if snapshot.get("failed") else ""
|
||||
self.switch_combo.addItem(f"{switch['name']} ({switch['host']}){suffix}", switch["id"])
|
||||
if selected_id:
|
||||
self.switch_combo.setCurrentIndex(max(0, self.switch_combo.findData(selected_id)))
|
||||
top.addWidget(self.switch_combo, 1)
|
||||
@@ -973,14 +1061,6 @@ class RawDataDialog(_Dialog):
|
||||
top.addWidget(button("Alles speichern …", "download", on_click=self.save_all))
|
||||
self.root.addLayout(top)
|
||||
self.tabs = QTabWidget()
|
||||
self.editors = {}
|
||||
for key, title in self.SECTIONS.items():
|
||||
editor = QPlainTextEdit()
|
||||
editor.setObjectName("LogView")
|
||||
editor.setReadOnly(True)
|
||||
editor.setLineWrapMode(QPlainTextEdit.NoWrap)
|
||||
self.tabs.addTab(editor, title)
|
||||
self.editors[key] = editor
|
||||
self.root.addWidget(self.tabs, 1)
|
||||
close = button("Schließen", variant="primary", on_click=self.accept)
|
||||
self.root.addWidget(close, 0, Qt.AlignRight)
|
||||
@@ -990,15 +1070,32 @@ class RawDataDialog(_Dialog):
|
||||
def _current(self):
|
||||
return self.items[max(0, self.switch_combo.currentIndex())]
|
||||
|
||||
@classmethod
|
||||
def _sections(cls, raw):
|
||||
"""Known outputs in a fixed order, unknown ones after them, the session last."""
|
||||
keys = [key for key in cls.SECTIONS if key != "session" and key in raw]
|
||||
keys += sorted(key for key in raw if key not in cls.SECTIONS and isinstance(raw[key], str))
|
||||
keys += ["session"] if "session" in raw else []
|
||||
return [(key, cls.SECTIONS.get(key, key)) for key in keys] or [("", "Rohdaten")]
|
||||
|
||||
def show_switch(self, *_args):
|
||||
_switch, snapshot = self._current()
|
||||
raw = snapshot.get("raw", {})
|
||||
for key, editor in self.editors.items():
|
||||
self.tabs.clear()
|
||||
for key, title in self._sections(raw):
|
||||
editor = QPlainTextEdit()
|
||||
editor.setObjectName("LogView")
|
||||
editor.setReadOnly(True)
|
||||
editor.setLineWrapMode(QPlainTextEdit.NoWrap)
|
||||
editor.setPlainText(str(raw.get(key) or "(keine Ausgabe)"))
|
||||
self.tabs.addTab(editor, title)
|
||||
if snapshot.get("failed"):
|
||||
self.tabs.setCurrentIndex(self.tabs.count() - 1)
|
||||
|
||||
def copy_current(self):
|
||||
editor = self.tabs.currentWidget()
|
||||
QGuiApplication.clipboard().setText(editor.toPlainText())
|
||||
if editor is not None:
|
||||
QGuiApplication.clipboard().setText(editor.toPlainText())
|
||||
|
||||
def save_all(self):
|
||||
path, _filter = QFileDialog.getSaveFileName(self, "SSH-Rohdaten speichern", "ssh-rohdaten.txt", "Text (*.txt)")
|
||||
@@ -1006,9 +1103,10 @@ class RawDataDialog(_Dialog):
|
||||
return
|
||||
sections = []
|
||||
for switch, snapshot in self.items:
|
||||
sections.append(f"{'=' * 20} {switch['name']} ({switch['host']}) {'=' * 20}")
|
||||
suffix = " (abgebrochen)" if snapshot.get("failed") else ""
|
||||
sections.append(f"{'=' * 20} {switch['name']} ({switch['host']}){suffix} {'=' * 20}")
|
||||
raw = snapshot.get("raw", {})
|
||||
for key, title in self.SECTIONS.items():
|
||||
for key, title in self._sections(raw):
|
||||
sections.extend((f"\n--- {title.upper()} ---", str(raw.get(key) or "(keine Ausgabe)")))
|
||||
with open(path, "w", encoding="utf-8") as stream:
|
||||
stream.write("\n".join(sections))
|
||||
@@ -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,469 @@
|
||||
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",
|
||||
"ignored": "ignoriert"}
|
||||
STATE_DOT = {"new": "accent", "known": "success", "check": "warning", "netbox_only": "text_faint",
|
||||
"ignored": "text_faint"}
|
||||
ROLE_HINTS = ("access point", "accesspoint", "access-point", "wlan", "wifi", "ap")
|
||||
|
||||
|
||||
def placement_value(value):
|
||||
"""Stored choice as ``{"site": ID or None, "tenant": ID or None}`` (4.9.0 stored only a site ID)."""
|
||||
if isinstance(value, dict):
|
||||
return {"site": value.get("site") or None, "tenant": value.get("tenant") or None}
|
||||
return {"site": value or None, "tenant": None}
|
||||
|
||||
|
||||
class SiteMappingDialog(_Dialog):
|
||||
"""Assign an optional NetBox site and the mandatory tenant to Sophos sites
|
||||
and to APs without a Sophos site."""
|
||||
|
||||
def __init__(self, parent, rows, sites, tenants):
|
||||
super().__init__(parent, "Standorte & Mandanten zuordnen",
|
||||
"Der Standort ist optional – APs ohne Zuordnung kommen an den Standard-Standort, weil NetBox "
|
||||
"für jedes Gerät einen Standort verlangt. Der Mandant ist Pflicht und wird bewusst gewählt. Zeilen ohne "
|
||||
"Standort und ohne Mandant werden ignoriert.",
|
||||
width=860)
|
||||
self.resize(980, 620)
|
||||
site_items = [("– kein Standort (Standard-Standort) –", 0)] + [
|
||||
(site["name"] + (f" ({site['tenant']})" if site["tenant"] else ""), site["id"]) for site in sites]
|
||||
tenant_items = [(tenant["name"], tenant["id"]) for tenant in tenants]
|
||||
self.table = QTableWidget(0, 4)
|
||||
self.table.setHorizontalHeaderLabels(["Sophos-Standort / Access Point", "APs", "NetBox-Standort (optional)",
|
||||
"Mandant *"])
|
||||
self.rows = []
|
||||
for text, count, key, current in rows:
|
||||
row = self.table.rowCount()
|
||||
self.table.insertRow(row)
|
||||
self.table.setItem(row, 0, QTableWidgetItem(text))
|
||||
self.table.setItem(row, 1, QTableWidgetItem(str(count)))
|
||||
site = SearchableComboBox("Standort suchen …")
|
||||
site.set_items(site_items, current["site"] or 0)
|
||||
tenant = SearchableComboBox("Mandant wählen …")
|
||||
# only a stored choice is shown – never a suggestion
|
||||
tenant.set_items(tenant_items, current["tenant"])
|
||||
self.table.setCellWidget(row, 2, site)
|
||||
self.table.setCellWidget(row, 3, tenant)
|
||||
self.rows.append((key, site, tenant))
|
||||
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((300, 50, 330, 240)):
|
||||
self.table.setColumnWidth(column, width)
|
||||
self.root.addWidget(self.table, 1)
|
||||
self.root.addWidget(self.error_banner)
|
||||
buttons, _ok = form_dialog_buttons(self, "Übernehmen")
|
||||
self.root.addWidget(buttons)
|
||||
self.result = {}
|
||||
|
||||
def accept(self):
|
||||
result = {}
|
||||
for key, site, tenant in self.rows:
|
||||
if tenant.valid_data() is None and site.valid_data():
|
||||
self.show_error(f"Bitte für „{key[1]}“ einen Mandanten wählen.")
|
||||
return
|
||||
result[key] = {"site": site.valid_data() or None, "tenant": tenant.valid_data()}
|
||||
self.result = result
|
||||
super().accept()
|
||||
|
||||
|
||||
class AccessPointsPage(Page):
|
||||
title = "Access Points"
|
||||
subtitle = ("Sophos-APs aus einem Export von Sophos Central laden, mit NetBox abgleichen (global über "
|
||||
"Seriennummer, MAC und Name) und fehlende anlegen.")
|
||||
|
||||
def __init__(self, window):
|
||||
super().__init__(window)
|
||||
self.aps = []
|
||||
self.only_netbox = []
|
||||
self.engine = None
|
||||
self.roles = []
|
||||
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)
|
||||
self.role = SearchableComboBox("Geräterolle wählen …")
|
||||
self.role.setMinimumWidth(320)
|
||||
form.addRow("Geräterolle", self.role)
|
||||
site_row = QHBoxLayout()
|
||||
self.default_site = SearchableComboBox("Standort wählen …")
|
||||
self.default_site.setMinimumWidth(320)
|
||||
site_row.addWidget(self.default_site)
|
||||
site_row.addWidget(label("Für neue APs ohne zugeordneten Standort – NetBox verlangt für jedes Gerät einen.",
|
||||
muted=True), 1)
|
||||
form.addRow("Standard-Standort", site_row)
|
||||
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 && Mandanten …", "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 ("text_muted" if str(row.get("netbox_site", "")).startswith("Standard:") else None)),
|
||||
Column("tenant", "Mandant", 150),
|
||||
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.role.activated.connect(lambda _index: self._store(role_id=self.role.valid_data()))
|
||||
self.default_site.activated.connect(lambda _index: (self._store(default_site=self.default_site.valid_data()),
|
||||
self._refresh()))
|
||||
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.roles = [], [], None, []
|
||||
self.role.set_items([])
|
||||
self.default_site.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.roles 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 Geräterollen …")
|
||||
return sorted(((item.name, item.id) for item in nb.dcim.device_roles.all()), key=lambda x: x[0].casefold())
|
||||
|
||||
def done(roles):
|
||||
self.roles = roles
|
||||
settings = self._settings()
|
||||
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:
|
||||
QTimer.singleShot(0, self.compare)
|
||||
|
||||
self.tasks.run(work, title="Geräterollen laden", area="app", on_success=done,
|
||||
on_error=self.actions._netbox_failed)
|
||||
|
||||
def compare(self):
|
||||
if not self.aps or self.tasks.busy:
|
||||
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, Mandanten und vorhandene Sophos-Geräte …")
|
||||
engine.load_context()
|
||||
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
|
||||
self.default_site.set_items([(site["name"] + (f" ({site['tenant']})" if site["tenant"] else ""),
|
||||
site["id"]) for site in self.engine.ap_sites],
|
||||
self._settings().get("default_site"))
|
||||
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 _placement(self, ap):
|
||||
"""Site (optional) and tenant for a new AP: stored choice, else the suggestion."""
|
||||
settings = self._settings()
|
||||
stored = (settings.get("ap_sites") or {}).get(ap_key(ap)) or (settings.get("site_map") or {}).get(
|
||||
ap["site_hint"])
|
||||
if stored:
|
||||
value = placement_value(stored)
|
||||
# neither site nor tenant: the user chose to leave these APs out
|
||||
return dict(value, stored=True, ignored=not value["site"] and not value["tenant"])
|
||||
site = self.engine.suggest_site(ap["site_hint"]) if self.engine else None
|
||||
return {"site": site, "tenant": None, "stored": False, "ignored": False}
|
||||
|
||||
def _tenant_for(self, placement):
|
||||
return placement.get("tenant")
|
||||
|
||||
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 _tenant_name(self, tenant_id):
|
||||
tenants = self.engine.group_tenants if self.engine else []
|
||||
return next((tenant["name"] for tenant in tenants if tenant["id"] == tenant_id), "")
|
||||
|
||||
def _refresh(self):
|
||||
rows = []
|
||||
default_site = self.default_site.valid_data()
|
||||
for ap in self.aps:
|
||||
device = ap.get("device")
|
||||
site_id = tenant_name = None
|
||||
if device:
|
||||
site = getattr(device, "site", None)
|
||||
site_name = getattr(site, "name", "") or self._site_name(getattr(site, "id", site))
|
||||
tenant_name = getattr(getattr(device, "tenant", None), "name", "") or self._tenant_name(
|
||||
related_id(device, "tenant"))
|
||||
elif self.engine and self._placement(ap)["ignored"]:
|
||||
site_name = ""
|
||||
elif self.engine:
|
||||
placement = self._placement(ap)
|
||||
site_id = placement["site"] or default_site
|
||||
site_name = (self._site_name(placement["site"]) if placement["site"] else
|
||||
f"Standard: {self._site_name(default_site)}" if default_site else "– Standard-Standort fehlt –")
|
||||
tenant_name = self._tenant_name(self._tenant_for(placement))
|
||||
else:
|
||||
site_name = ""
|
||||
state = ("ignored" if self.engine and self._placement(ap)["ignored"] else "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, tenant=tenant_name or "",
|
||||
netbox_device=device.name if device else "", method=ap.get("method", "")))
|
||||
# NetBox APs missing in the export – only for tenants this export is about
|
||||
tenants = {related_id(ap["device"], "tenant") for ap in self.aps if ap.get("device")}
|
||||
tenants |= {self._tenant_for(self._placement(ap)) for ap in self.aps if not ap.get("device")}
|
||||
tenants.discard(None)
|
||||
for device in (device for device in self.only_netbox if related_id(device, "tenant") in tenants):
|
||||
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")),
|
||||
"tenant": self._tenant_name(related_id(device, "tenant")),
|
||||
"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"]
|
||||
if counts["ignored"]:
|
||||
parts.append(f"{counts['ignored']} ignoriert")
|
||||
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 Standort – Standard-Standort wählen")
|
||||
elif self.aps:
|
||||
parts.append("Abgleich mit NetBox läuft …" 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 einen Export laden." 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()
|
||||
groups = {}
|
||||
for ap in new:
|
||||
if ap["site_hint"]:
|
||||
groups.setdefault(ap["site_hint"], []).append(ap)
|
||||
rows = [(hint, len(members), ("site", hint), self._placement(members[0]))
|
||||
for hint, members in sorted(groups.items(), key=lambda pair: pair[0].casefold())]
|
||||
rows += [(f"{ap['name']} (ohne Sophos-Standort)", 1, ("ap", ap_key(ap)), self._placement(ap))
|
||||
for ap in new if not ap["site_hint"]]
|
||||
if not rows:
|
||||
self.window.toast("Alle Access Points sind bereits in NetBox.", "info")
|
||||
return False
|
||||
dialog = SiteMappingDialog(self.window, rows, self.engine.ap_sites, self.engine.group_tenants)
|
||||
if not dialog.exec():
|
||||
return False
|
||||
settings = self._settings()
|
||||
site_map, ap_sites = dict(settings.get("site_map") or {}), dict(settings.get("ap_sites") or {})
|
||||
for (kind, key), value in dialog.result.items():
|
||||
(site_map if kind == "site" else ap_sites)[key] = value
|
||||
self._store(site_map=site_map, ap_sites=ap_sites)
|
||||
self._refresh()
|
||||
return True
|
||||
|
||||
def sync(self):
|
||||
if not self.engine or self.tasks.busy:
|
||||
return
|
||||
new = [ap for ap in self._new_aps() if not self._placement(ap)["ignored"]]
|
||||
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._placement(ap)["stored"] for ap in new):
|
||||
if not self.map_sites():
|
||||
return
|
||||
new = [ap for ap in new if not self._placement(ap)["ignored"]]
|
||||
default_site = self.default_site.valid_data()
|
||||
placements = {}
|
||||
for ap in new:
|
||||
placement = self._placement(ap)
|
||||
placements[ap_key(ap)] = {"site": placement["site"], "tenant": self._tenant_for(placement)}
|
||||
homeless = [ap["name"] for ap in new if not placements[ap_key(ap)]["site"]]
|
||||
if homeless and not default_site:
|
||||
widgets.message(self.window, "Standard-Standort fehlt",
|
||||
f"{len(homeless)} neue Access Points haben keinen Standort. NetBox verlangt für jedes "
|
||||
"Gerät einen Standort – bitte oben einen Standard-Standort wählen.", "info",
|
||||
"\n".join(homeless))
|
||||
return
|
||||
engine, rename = self.engine, self.rename.isChecked()
|
||||
aps = [ap for ap in self.aps if ap.get("device") or ap_key(ap) in placements]
|
||||
|
||||
def run(dry_run):
|
||||
return lambda ctx: engine.sync(aps, placements, role_id, rename, dry_run=dry_run, default_site=default_site)
|
||||
|
||||
def show(report):
|
||||
def ask():
|
||||
if ClientPreviewDialog(self.window, report).exec():
|
||||
self.tasks.run(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(run(True), 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))
|
||||
@@ -4,7 +4,8 @@ import uuid
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWidgets import QComboBox, QHBoxLayout, QMenu, QSplitter, QStackedWidget
|
||||
|
||||
from netbox_sync.core.switches import PLATFORMS, ignored_vlans, vlan_label, without_vlans
|
||||
from netbox_sync.core.backups import BACKUP_PLATFORMS
|
||||
from netbox_sync.core.switches import PLATFORMS, ignored_vlans, port_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
|
||||
@@ -23,7 +24,8 @@ def _speed(value):
|
||||
class SwitchesPage(Page):
|
||||
title = "Switche"
|
||||
subtitle = ("Bestehende NetBox-Geräte per SSH auslesen und Schnittstellen, IP-Adressen und LLDP/CDP-Verkabelung "
|
||||
"dokumentieren. Unterstützt Aruba CX, ArubaOS-Switch/ProCurve und HPE Comware.")
|
||||
"dokumentieren. Unterstützt Aruba CX, ArubaOS-Switch/ProCurve, HPE Comware und LANCOM LCOS SX 3.x – D-Link und Linksys "
|
||||
"per Backup-Datei.")
|
||||
|
||||
def __init__(self, window):
|
||||
super().__init__(window)
|
||||
@@ -36,7 +38,7 @@ class SwitchesPage(Page):
|
||||
self.discover_button = list_card.add_action(button("Auslesen", "play", "primary", on_click=self.discover))
|
||||
columns = [
|
||||
Column("name", "NetBox-Gerät", 200),
|
||||
Column("platform", "Plattform", 180, value=lambda row: PLATFORMS.get(row.get("platform"), row.get("platform"))),
|
||||
Column("platform", "Plattform", 180, value=lambda row: PLATFORMS.get(row.get("platform")) or BACKUP_PLATFORMS.get(row.get("platform"), row.get("platform"))),
|
||||
Column("host", "SSH-Host", 150, value=lambda row: f"{row.get('host', '')}:{row.get('port', 22)}"),
|
||||
Column("enabled", "Aktiv", 70, value=lambda row: "ja" if row.get("enabled", True) else "nein",
|
||||
color=lambda row: None if row.get("enabled", True) else "text_faint"),
|
||||
@@ -81,6 +83,11 @@ class SwitchesPage(Page):
|
||||
self.file_button = result_card.add_action(button("Aus Datei laden …", "folder", on_click=self.load_file,
|
||||
tooltip="Ausleseergebnisse aus einer im Offline-Modus "
|
||||
"erstellten Exportdatei (JSON) laden."))
|
||||
self.backup_button = result_card.add_action(button(
|
||||
"Backup importieren …", "folder", on_click=self.actions.import_switch_backups,
|
||||
tooltip="Einmal-Import ohne SSH: Konfigurations-Backup eines D-Link- (DGS-1210, config.bin) oder "
|
||||
"Linksys-Switches (LGS, *.cfg) laden. Der Switch wird über seinen Hostnamen dem NetBox-Gerät "
|
||||
"zugeordnet."))
|
||||
self.raw_button = result_card.add_action(button("SSH-Rohdaten", "terminal", on_click=self.show_raw))
|
||||
self.sync_button = result_card.add_action(button("Nach NetBox übertragen …", "upload", "primary",
|
||||
on_click=self.sync))
|
||||
@@ -93,13 +100,30 @@ class SwitchesPage(Page):
|
||||
self.cables_option = checkbox("Kabel aus LLDP/CDP anlegen",
|
||||
tooltip="Legt Kabel zwischen Schnittstellen an, deren Gegenstelle in NetBox "
|
||||
"eindeutig gefunden wird. Bestehende Kabel werden nie verändert.")
|
||||
self.update_cables_option = checkbox(
|
||||
"Bestehende Kabel anpassen",
|
||||
tooltip="Achtung: NetBox ist die Source of Truth. Weicht ein vorhandenes Kabel vom LLDP/CDP-Nachbarn ab, "
|
||||
"wird es auf die vom Switch gemeldete Gegenstelle umgehängt. Kabel zu Patchpanels werden nie "
|
||||
"verändert. Ohne diese Option werden Abweichungen nur gemeldet.")
|
||||
self.backup_option = checkbox("Konfiguration als Anhang sichern",
|
||||
tooltip="Hängt die laufende Konfiguration als Textdatei an das NetBox-Gerät "
|
||||
"(Plugin netbox-attachments). Passwörter, Schlüssel und Communities "
|
||||
"werden entfernt; ein neuer Anhang entsteht nur bei Änderungen.")
|
||||
# Two rows: filters for the table, then the options of the NetBox transfer.
|
||||
filters.setSpacing(12)
|
||||
filters.addWidget(self.search, 2)
|
||||
filters.addWidget(self.switch_filter, 1)
|
||||
filters.addWidget(self.only_up)
|
||||
filters.addWidget(self.only_neighbors)
|
||||
filters.addStretch(1)
|
||||
filters.addWidget(self.cables_option)
|
||||
result_card.add(filters)
|
||||
options = QHBoxLayout()
|
||||
options.setSpacing(16)
|
||||
options.addWidget(label("Übertragen:", muted=True))
|
||||
options.addWidget(self.cables_option)
|
||||
options.addWidget(self.update_cables_option)
|
||||
options.addWidget(self.backup_option)
|
||||
options.addStretch(1)
|
||||
result_card.add(options)
|
||||
result_columns = [
|
||||
Column("switch", "Switch", 140),
|
||||
Column("name", "Schnittstelle", 150),
|
||||
@@ -108,8 +132,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(without_vlans(
|
||||
row.get("vlans"), ignored_vlans((self.state.profile or {}).get("vlan_map"))))),
|
||||
Column("vlans", "VLANs", 110, value=lambda row: port_label(without_vlans(
|
||||
row.get("vlans"), ignored_vlans((self.state.profile or {}).get("vlan_map"))), row.get("lag"))),
|
||||
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", "")),
|
||||
@@ -144,6 +168,9 @@ class SwitchesPage(Page):
|
||||
self.switch_table.selectionModel().selectionChanged.connect(self._update_buttons)
|
||||
self.lldp_option.toggled.connect(lambda value: self.state.update_settings(enable_lldp=value))
|
||||
self.cables_option.toggled.connect(lambda value: self.state.update_settings(create_cables=value))
|
||||
self.backup_option.toggled.connect(lambda value: self.state.update_settings(backup_config=value))
|
||||
self.update_cables_option.toggled.connect(self._toggle_update_cables)
|
||||
self.cables_option.toggled.connect(self.update_cables_option.setEnabled)
|
||||
self.state.switches_changed.connect(self.refresh)
|
||||
self.state.profile_switched.connect(self.refresh)
|
||||
self.state.profile_edited.connect(self.refresh_switches)
|
||||
@@ -155,10 +182,25 @@ class SwitchesPage(Page):
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _load_settings(self):
|
||||
for widget, key in ((self.lldp_option, "enable_lldp"), (self.cables_option, "create_cables")):
|
||||
for widget, key in ((self.lldp_option, "enable_lldp"), (self.cables_option, "create_cables"),
|
||||
(self.backup_option, "backup_config"), (self.update_cables_option, "update_cables")):
|
||||
widget.blockSignals(True)
|
||||
widget.setChecked(bool(self.state.settings.get(key)))
|
||||
widget.blockSignals(False)
|
||||
self.update_cables_option.setEnabled(self.cables_option.isChecked())
|
||||
|
||||
def _toggle_update_cables(self, value):
|
||||
if value and not widgets.confirm(
|
||||
self.window, "Bestehende Kabel anpassen?",
|
||||
"NetBox ist die Source of Truth. Mit dieser Option werden vorhandene Kabel, deren Gegenstelle nicht "
|
||||
"zum LLDP/CDP-Nachbarn des Switches passt, umgehängt – die bisherige Verbindung geht in NetBox "
|
||||
"verloren. Kabel zu Patchpanels bleiben unverändert. Jede Anpassung steht vorher in der Vorschau.",
|
||||
ok_text="Einschalten", destructive=True):
|
||||
self.update_cables_option.blockSignals(True)
|
||||
self.update_cables_option.setChecked(False)
|
||||
self.update_cables_option.blockSignals(False)
|
||||
return
|
||||
self.state.update_settings(update_cables=value)
|
||||
|
||||
def _status_text(self, row):
|
||||
status = self.state.switch_status.get(row["id"])
|
||||
@@ -248,11 +290,13 @@ class SwitchesPage(Page):
|
||||
self.sync_button.setText(f"{len(with_data)} nach NetBox übertragen …" if with_data
|
||||
else "Nach NetBox übertragen …")
|
||||
self.cables_option.setVisible(not offline)
|
||||
widgets.set_enabled(self.raw_button, bool(self.state.switch_snapshots), "Noch nichts ausgelesen.")
|
||||
widgets.set_enabled(self.raw_button, bool(self.state.switch_snapshots or self.state.switch_failed_raw),
|
||||
"Noch nichts ausgelesen.")
|
||||
widgets.set_enabled(self.edit_button, len(self._selected()) == 1, "Bitte genau einen Switch markieren.")
|
||||
widgets.set_enabled(self.remove_button, bool(targets), "Bitte Switche anhaken oder markieren.")
|
||||
self.add_button.setEnabled(not busy)
|
||||
self.file_button.setEnabled(not busy)
|
||||
self.backup_button.setEnabled(not busy)
|
||||
|
||||
def set_busy(self, busy):
|
||||
self._update_buttons()
|
||||
@@ -306,6 +350,7 @@ class SwitchesPage(Page):
|
||||
if dialog.result.get("device_id") != current.get("device_id"):
|
||||
self.state.switch_snapshots.pop(current["id"], None)
|
||||
self.state.switch_status.pop(current["id"], None)
|
||||
self.state.switch_failed_raw.pop(current["id"], None)
|
||||
self.state.touch()
|
||||
self.refresh()
|
||||
|
||||
@@ -323,6 +368,7 @@ class SwitchesPage(Page):
|
||||
for switch_id in ids:
|
||||
self.state.switch_snapshots.pop(switch_id, None)
|
||||
self.state.switch_status.pop(switch_id, None)
|
||||
self.state.switch_failed_raw.pop(switch_id, None)
|
||||
self.state.touch()
|
||||
self.refresh()
|
||||
|
||||
@@ -352,7 +398,11 @@ class SwitchesPage(Page):
|
||||
|
||||
def show_raw(self):
|
||||
by_id = {switch["id"]: switch for switch in self.state.switches}
|
||||
items = [(by_id[key], snapshot) for key, snapshot in self.state.switch_snapshots.items() if key in by_id]
|
||||
raw = dict(self.state.switch_snapshots)
|
||||
# A failed discovery is newer than an older result: show its session up to the error.
|
||||
for key, transcript in self.state.switch_failed_raw.items():
|
||||
raw[key] = {"raw": {"session": transcript}, "failed": True}
|
||||
items = [(by_id[key], snapshot) for key, snapshot in raw.items() if key in by_id]
|
||||
if not items:
|
||||
return
|
||||
selected = self._selected()
|
||||
@@ -365,7 +415,8 @@ class SwitchesPage(Page):
|
||||
menu = QMenu(self)
|
||||
menu.addAction(icon("play", muted), "Auslesen", self.discover)
|
||||
menu.addAction(icon("pencil", muted), "Bearbeiten …", self.edit_switch)
|
||||
if any(switch["id"] in self.state.switch_snapshots for switch in self._selected()):
|
||||
if any(switch["id"] in self.state.switch_snapshots or switch["id"] in self.state.switch_failed_raw
|
||||
for switch in self._selected()):
|
||||
menu.addAction(icon("terminal", muted), "SSH-Rohdaten …", self.show_raw)
|
||||
menu.addSeparator()
|
||||
menu.addAction(icon("trash", theme.color("danger")), "Entfernen", self.remove_switches)
|
||||
|
||||
@@ -48,6 +48,8 @@ class AppState(QObject):
|
||||
self.netbox_devices = None
|
||||
self.switch_snapshots = {}
|
||||
self.switch_status = {}
|
||||
# CLI session of failed discoveries (switch id → masked text) for the raw data view.
|
||||
self.switch_failed_raw = {}
|
||||
self.clients = []
|
||||
self.clients_loaded_at = None
|
||||
self.client_engine = None
|
||||
|
||||
@@ -255,6 +255,28 @@ class EmptyState(QWidget):
|
||||
layout.addSpacing(6)
|
||||
layout.addLayout(buttons)
|
||||
layout.addStretch(2)
|
||||
layout.setContentsMargins(24, 16, 24, 16)
|
||||
|
||||
def _heights(self, width):
|
||||
width = max(width, 320) - 48
|
||||
core = 32 + self.title_label.heightForWidth(width) + 10
|
||||
if self.action is not None:
|
||||
core += 16 + self.action.sizeHint().height()
|
||||
return core, self.text_label.heightForWidth(min(width, 520)) + 10, 56 + 10
|
||||
|
||||
def minimumSizeHint(self):
|
||||
# Title and button always fit; icon and text are dropped when space is short.
|
||||
core, _text, _icon = self._heights(self.width())
|
||||
return QSize(260, core)
|
||||
|
||||
def resizeEvent(self, event):
|
||||
super().resizeEvent(event)
|
||||
# Word-wrapped labels report almost no minimum height, so a small card
|
||||
# would squeeze icon, title, text and button on top of each other.
|
||||
core, text, icon_height = self._heights(event.size().width())
|
||||
available = event.size().height()
|
||||
self.text_label.setVisible(available >= core + text)
|
||||
self.icon_label.setVisible(available >= core + text + icon_height)
|
||||
|
||||
def set_text(self, title=None, text=None):
|
||||
if title is not None:
|
||||
|
||||
+1
-1
@@ -2,5 +2,5 @@ PySide6-Essentials>=6.7
|
||||
pynetbox>=7.4
|
||||
pyvmomi>=8.0
|
||||
requests>=2.31
|
||||
paramiko>=3.4
|
||||
paramiko>=3.4,<4 # 4.x+ dropped ssh-rsa (SHA-1) and ssh-dss host keys used by older switches (e.g. LANCOM GS-23xx)
|
||||
pywin32>=306; sys_platform == "win32"
|
||||
@@ -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,130 @@
|
||||
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]): {"site": 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"][0].startswith("Büro ohne Standort: kein Standort")
|
||||
|
||||
|
||||
def test_site_is_optional_with_default_site_and_tenant_can_be_chosen():
|
||||
nb = _netbox()
|
||||
engine = APSyncEngine(nb)
|
||||
engine.load_context(7)
|
||||
assert [tenant["name"] for tenant in engine.group_tenants] == ["Kunde Kita", "Kunde RZ"]
|
||||
aps = parse_csv(CSV)
|
||||
engine.match(aps)
|
||||
# No site for the new AP: it goes to the default site, with an own tenant.
|
||||
engine.sync(aps, {ap_key(aps[2]): {"site": None, "tenant": 8}}, role_id=30, dry_run=False, default_site=21)
|
||||
created = nb.dcim.devices.created[-1]
|
||||
assert (created["site"], created["tenant"]) == (21, 8)
|
||||
|
||||
|
||||
def test_without_tenant_the_whole_netbox_is_searched_and_tenant_comes_from_the_choice():
|
||||
nb = _netbox()
|
||||
engine = APSyncEngine(nb)
|
||||
engine.load_context()
|
||||
assert [tenant["name"] for tenant in engine.group_tenants] == ["Kunde Kita", "Kunde RZ"]
|
||||
assert len(engine.ap_sites) == 2 and len(engine.netbox_aps) == 3
|
||||
aps = parse_csv(CSV)
|
||||
engine.match(aps)
|
||||
assert [ap["device"].id if ap["device"] else None for ap in aps] == [102, 101, None]
|
||||
report = engine.sync(aps, {ap_key(aps[2]): {"site": 21, "tenant": 7}}, role_id=30, dry_run=False)
|
||||
assert report["errors"] == [] and nb.dcim.devices.created[-1]["tenant"] == 7
|
||||
@@ -0,0 +1,151 @@
|
||||
import io
|
||||
import tarfile
|
||||
import zlib
|
||||
|
||||
import pytest
|
||||
|
||||
from netbox_sync.core.backups import BackupError, parse_backup, parse_snmp_dump
|
||||
|
||||
BASE = "1.3.6.1.4.1.171.10.76.21.1"
|
||||
|
||||
|
||||
def _octets(oid, value):
|
||||
value = value if isinstance(value, bytes) else value.encode()
|
||||
return f"{oid}\t 4\t{len(value):4d}\t".encode() + value + b"\n"
|
||||
|
||||
|
||||
def _scalar(oid, kind, value):
|
||||
return f"{oid}\t{kind:>2}\t{value}\n".encode()
|
||||
|
||||
|
||||
def dlink_backup():
|
||||
dump = b"".join([
|
||||
_octets("1.3.6.1.2.1.1.5.0", "SW-01"),
|
||||
_octets("1.3.6.1.2.1.1.6.0", "Keller"),
|
||||
_octets(f"{BASE}.1.16.1.2.1", "Uplink"),
|
||||
_octets(f"{BASE}.1.16.1.2.2", ""),
|
||||
_octets(f"{BASE}.1.16.1.2.3", ""),
|
||||
_octets(f"{BASE}.7.6.1.1.10", "LAN"),
|
||||
_octets(f"{BASE}.7.6.1.1.20", "VOICE"),
|
||||
# Bitmaps may contain a line break (0x0a) – the parser must honour the length.
|
||||
_octets(f"{BASE}.7.6.1.2.10", b"\xe0\x00\x00\x00"),
|
||||
_octets(f"{BASE}.7.6.1.4.10", b"\x60\x00\x00\x00"),
|
||||
_octets(f"{BASE}.7.6.1.2.20", b"\x80\x0a\x00\x00"),
|
||||
_octets(f"{BASE}.7.6.1.4.20", b"\x00\x00\x00\x00"),
|
||||
_scalar(f"{BASE}.7.7.1.1.1", 66, 10),
|
||||
_scalar(f"{BASE}.7.7.1.1.2", 66, 10),
|
||||
_scalar(f"{BASE}.7.7.1.1.3", 66, 10),
|
||||
_scalar("1.3.6.1.2.1.2.2.1.7.1", 2, 1),
|
||||
_scalar("1.3.6.1.2.1.2.2.1.7.2", 2, 1),
|
||||
_scalar("1.3.6.1.2.1.2.2.1.7.3", 2, 2),
|
||||
_scalar(f"{BASE}.2.5.2.0", 64, "10.0.0.5"),
|
||||
_scalar(f"{BASE}.2.5.3.0", 64, "255.255.255.0"),
|
||||
_octets(f"{BASE}.2.5.5.0", "System"),
|
||||
])
|
||||
header = b"DGS-1210-28P".ljust(32, b"\x00") + b"\x00" * 16
|
||||
return header + zlib.compress(dump)
|
||||
|
||||
|
||||
LINKSYS_CONF = """
|
||||
system name "SW-02"
|
||||
system location "Büro"
|
||||
interface gigabitethernet 0/1
|
||||
shutdown
|
||||
description "AP"
|
||||
!
|
||||
interface gigabitethernet 0/2
|
||||
shutdown
|
||||
description ""
|
||||
!
|
||||
interface gigabitethernet 0/3
|
||||
description ""
|
||||
!
|
||||
interface gigabitethernet 0/1
|
||||
no shutdown
|
||||
!
|
||||
vlan 1
|
||||
ports name default
|
||||
!
|
||||
vlan 10
|
||||
ports add gigabitethernet 0/1 untagged gigabitethernet 0/1
|
||||
ports add gigabitethernet 0/2
|
||||
!
|
||||
vlan 20
|
||||
ports add gigabitethernet 0/2
|
||||
!
|
||||
interface vlan 1
|
||||
ip address 10.0.0.6 255.255.255.0
|
||||
!
|
||||
snmp community name SECRET security noAuthUser
|
||||
set switch-name LGS328MPC
|
||||
"""
|
||||
|
||||
|
||||
def linksys_backup():
|
||||
buffer = io.BytesIO()
|
||||
with tarfile.open(fileobj=buffer, mode="w") as archive:
|
||||
data = LINKSYS_CONF.encode()
|
||||
info = tarfile.TarInfo("current_config/SNCSR.conf")
|
||||
info.size = len(data)
|
||||
archive.addfile(info, io.BytesIO(data))
|
||||
return b"`A \x00 IMG-3.01.252 header".ljust(64, b"\x00") + buffer.getvalue()
|
||||
|
||||
|
||||
def test_snmp_dump_keeps_binary_octets():
|
||||
values = parse_snmp_dump(_octets("1.2", b"a\nb") + _scalar("1.3", 2, 7))
|
||||
assert values == {"1.2": b"a\nb", "1.3": "7"}
|
||||
|
||||
|
||||
def test_dlink_backup():
|
||||
switch, snapshot = parse_backup(dlink_backup(), "config.bin")
|
||||
assert switch["name"] == "SW-01" and switch["host"] == "10.0.0.5" and switch["model"] == "DGS-1210-28P"
|
||||
ports = {item["name"]: item for item in snapshot["interfaces"]}
|
||||
assert ports["1"]["description"] == "Uplink"
|
||||
assert ports["1"]["vlans"] == {"untagged": [], "tagged": [10, 20], "tagged_all": False}
|
||||
assert ports["2"]["vlans"]["untagged"] == [10]
|
||||
assert ports["3"]["enabled"] is False
|
||||
assert ports["System"]["ip_addresses"] == ["10.0.0.5/24"] and ports["System"]["virtual"]
|
||||
assert snapshot["vlan_names"] == {10: "LAN", 20: "VOICE"}
|
||||
|
||||
|
||||
def test_linksys_backup():
|
||||
switch, snapshot = parse_backup(linksys_backup(), "x.cfg")
|
||||
assert switch == {"name": "SW-02", "host": "10.0.0.6", "model": "LGS328MPC", "platform": "linksys_backup",
|
||||
"location": "Büro"}
|
||||
ports = {item["name"]: item for item in snapshot["interfaces"]}
|
||||
assert ports["GE1"]["enabled"] is True and ports["GE1"]["description"] == "AP"
|
||||
assert ports["GE1"]["vlans"]["untagged"] == [10]
|
||||
assert ports["GE2"]["enabled"] is False
|
||||
assert ports["GE2"]["vlans"] == {"untagged": [], "tagged": [10, 20], "tagged_all": False}
|
||||
assert ports["GE3"]["vlans"] is None
|
||||
assert ports["vlan1"]["ip_addresses"] == ["10.0.0.6/24"]
|
||||
assert "SECRET" not in snapshot["config_backup"]
|
||||
|
||||
|
||||
def test_linksys_plain_text():
|
||||
switch, _snapshot = parse_backup(LINKSYS_CONF, "SNCSR.conf")
|
||||
assert switch["name"] == "SW-02"
|
||||
|
||||
|
||||
def test_unknown_file():
|
||||
with pytest.raises(BackupError):
|
||||
parse_backup(b"hello world", "x.bin")
|
||||
|
||||
|
||||
def test_dlink_original_file_is_attached():
|
||||
import base64
|
||||
from types import SimpleNamespace
|
||||
|
||||
from netbox_sync.core.switches import _backup_config
|
||||
|
||||
data = dlink_backup()
|
||||
_switch, snapshot = parse_backup(data, "config.bin")
|
||||
created = []
|
||||
attachments = SimpleNamespace(filter=lambda **_kw: [], create=lambda payload: created.append(payload)
|
||||
or SimpleNamespace())
|
||||
nb = SimpleNamespace(plugins=SimpleNamespace(netbox_attachments=SimpleNamespace(netbox_attachments=attachments)))
|
||||
report = {"notes": [], "errors": [], "changes": []}
|
||||
_backup_config(nb, SimpleNamespace(id=1, name="SW-01"), snapshot, False, report)
|
||||
filename, stream, content_type = created[0]["file"]
|
||||
assert filename.endswith(".bin") and content_type == "application/octet-stream"
|
||||
assert stream.read() == data == base64.b64decode(snapshot["config_file"]["data"])
|
||||
@@ -0,0 +1,297 @@
|
||||
from netbox_sync.core import lancom
|
||||
from netbox_sync.core.switches import build_snapshot, netbox_interface_type, suggest_platform
|
||||
|
||||
SYSTEM = """
|
||||
Model Name : LANCOM GS-2326P+
|
||||
Location : Keller
|
||||
Device Name : SW-08
|
||||
Firmware Version : v3.34.0205RU4
|
||||
Serial Number : 4006846720000000
|
||||
Host MAC Address : 00-a0-57-00-00-01
|
||||
SW-08(system)#"""
|
||||
|
||||
STATUS = """
|
||||
Port/Media State Link Auto Nego Speed Duplex Rx Pause Tx Pause
|
||||
---------- -------- -------------- --------- ------------ -------- --------
|
||||
1/UTP Enabled Down Enabled Down Disabled Disabled
|
||||
2/UTP Enabled Up Enabled 1G Full Disabled Disabled
|
||||
3/UTP Disabled Down Enabled Down Disabled Disabled
|
||||
4/UTP Enabled Up Enabled 100 Full Disabled Disabled
|
||||
25/SFP Enabled Up Enabled 1G Full Disabled Disabled
|
||||
SW-08(port)#"""
|
||||
|
||||
PORT_CONFIG = """
|
||||
Port State Speed Duplex Flow Control Max. Frame Excessive Power
|
||||
Description
|
||||
--------------------------------------------------------------------------------
|
||||
1 Enabled Auto Disabled 9600 Discard Disabled
|
||||
Uplink
|
||||
--------------------------------------------------------------------------------
|
||||
2 Enabled Auto Disabled 9600 Discard Disabled
|
||||
AP005
|
||||
--------------------------------------------------------------------------------
|
||||
3 Disabled Auto Disabled 9600 Discard Disabled
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
4 Enabled Auto Disabled 9600 Discard Disabled
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
25 Enabled SFP_Auto_AMS Disabled 9600 Discard Disabled
|
||||
|
||||
SW-08(port)#"""
|
||||
|
||||
VLANS = """
|
||||
VID VLAN Name User Ports
|
||||
---- -------------------------------- ---------- -----------------
|
||||
36 LAN Static 1-4,25
|
||||
136 MOBILE Static 1-2
|
||||
236 GUEST Static 1,3
|
||||
SW-08(vlan)#"""
|
||||
|
||||
VLAN_PORTS = """
|
||||
Port PVID Frame Type Ingress Filter Egress Rule Port Type
|
||||
---- ---- ---------- -------------- ----------- -------------
|
||||
1 1 All Disabled Trunk C-Port
|
||||
2 36 All Disabled Hybrid C-Port
|
||||
3 36 All Disabled Hybrid C-Port
|
||||
4 36 All Disabled Access C-Port
|
||||
25 1 All Disabled Hybrid C-Port
|
||||
SW-08(vlan)#"""
|
||||
|
||||
IP = """
|
||||
Configured Current
|
||||
--------------- ---------------
|
||||
DHCP Client : Disabled
|
||||
IP Address : 10.0.0.8 10.0.0.8
|
||||
IP Mask : 255.255.255.0 255.255.255.0
|
||||
VLAN ID : 36 36
|
||||
SW-08(ip)#"""
|
||||
|
||||
|
||||
def outputs():
|
||||
return {"system": SYSTEM, "status": STATUS, "port_config": PORT_CONFIG, "vlans": VLANS,
|
||||
"vlan_ports": VLAN_PORTS, "ip": IP, "neighbors": ""}
|
||||
|
||||
|
||||
def test_snapshot():
|
||||
snapshot = build_snapshot(outputs(), "lancom_sx3")
|
||||
ports = {item["name"]: item for item in snapshot["interfaces"]}
|
||||
assert ports["1"]["description"] == "Uplink" and not ports["1"]["connected"]
|
||||
assert ports["2"]["connected"] and ports["2"]["speed_mbps"] == 1000
|
||||
assert ports["4"]["speed_mbps"] == 100
|
||||
assert ports["3"]["enabled"] is False
|
||||
assert ports["1"]["vlans"] == {"untagged": [], "tagged": [36, 136, 236], "tagged_all": False}
|
||||
assert ports["2"]["vlans"] == {"untagged": [36], "tagged": [136], "tagged_all": False}
|
||||
assert ports["4"]["vlans"]["untagged"] == [36]
|
||||
assert ports["25"]["vlans"] == {"untagged": [], "tagged": [36], "tagged_all": False}
|
||||
assert netbox_interface_type(ports["25"]) == "1000base-x-sfp"
|
||||
assert netbox_interface_type(ports["1"]) == "1000base-t"
|
||||
assert ports["vlan36"]["ip_addresses"] == ["10.0.0.8/24"]
|
||||
assert snapshot["vlan_names"] == {36: "LAN", 136: "MOBILE", 236: "GUEST"}
|
||||
assert snapshot["system"]["model"] == "LANCOM GS-2326P+"
|
||||
assert "show port-config" in snapshot["config_backup"]
|
||||
|
||||
|
||||
def test_detection_helpers():
|
||||
assert lancom.is_lancom(SYSTEM)
|
||||
assert suggest_platform("LANCOM Systems", "GS-2326P+") == "lancom_sx3"
|
||||
|
||||
|
||||
class FakeChannel:
|
||||
"""Answers like the mode-based CLI and records what was sent."""
|
||||
|
||||
def __init__(self):
|
||||
self.sent, self.mode, self.buffer = [], "", ""
|
||||
|
||||
def send(self, data):
|
||||
if not data.endswith("\r"):
|
||||
self.buffer += data # like the real CLI: "\n" is only echoed, nothing is executed
|
||||
return
|
||||
command = data.strip()
|
||||
self.sent.append(command)
|
||||
answers = {("system", "show"): SYSTEM, ("port", "show status"): STATUS,
|
||||
("port", "show configuration"): PORT_CONFIG, ("vlan", "show vlan"): VLANS,
|
||||
("vlan", "show port-config"): VLAN_PORTS, ("ip", "show"): IP}
|
||||
if command == "exit":
|
||||
self.mode = ""
|
||||
output = ""
|
||||
elif not self.mode and command in ("system", "port", "vlan", "ip", "lldp"):
|
||||
self.mode = command
|
||||
output = ""
|
||||
else:
|
||||
output = answers.get((self.mode, command), "% Unrecognized command")
|
||||
self.buffer += output + f"\nSW-08{'(' + self.mode + ')' if self.mode else ''}# "
|
||||
|
||||
def recv_ready(self):
|
||||
return bool(self.buffer)
|
||||
|
||||
def recv(self, _size):
|
||||
data, self.buffer = self.buffer, ""
|
||||
return data.encode()
|
||||
|
||||
|
||||
def test_run_commands_switches_modes():
|
||||
channel = FakeChannel()
|
||||
result = lancom.run_commands(channel)
|
||||
assert result["vlans"].strip().startswith("VID") and result["neighbors"] == ""
|
||||
assert channel.sent[:3] == ["system", "show", "exit"]
|
||||
assert channel.mode == ""
|
||||
assert "show info 1-4,25" in channel.sent
|
||||
|
||||
|
||||
LLDP_CONFIG = """
|
||||
Interval : 30
|
||||
Port System System System Management CDP
|
||||
Port Mode Description Name Description Capability Address awareness
|
||||
---- -------- ----------- -------- ----------- ----------- ---------- ---------
|
||||
1 Disabled Enabled Enabled Enabled Enabled Enabled Enabled
|
||||
2 Disabled Enabled Enabled Enabled Enabled Enabled Enabled
|
||||
SW-08(lldp)#"""
|
||||
|
||||
|
||||
def test_lldp_disabled_is_reported():
|
||||
snapshot = build_snapshot(dict(outputs(), lldp_config=LLDP_CONFIG, neighbors="No LLDP entries found"),
|
||||
"lancom_sx3")
|
||||
assert snapshot["lldp_disabled"] is True and snapshot["neighbors"] == []
|
||||
enabled = LLDP_CONFIG.replace("1 Disabled", "1 Enabled ")
|
||||
assert build_snapshot(dict(outputs(), lldp_config=enabled), "lancom_sx3")["lldp_disabled"] is False
|
||||
|
||||
|
||||
def test_enable_lldp_on_disabled_ports():
|
||||
channel = FakeChannel()
|
||||
state = {"config": LLDP_CONFIG}
|
||||
original = channel.send
|
||||
|
||||
def send(data):
|
||||
command = data.strip()
|
||||
if channel.mode == "lldp" and command == "show config":
|
||||
channel.sent.append(command)
|
||||
channel.buffer += state["config"] + "\nSW-08(lldp)# "
|
||||
elif channel.mode == "lldp" and command.startswith("mode "):
|
||||
channel.sent.append(command)
|
||||
state["config"] = LLDP_CONFIG.replace("Disabled Enabled", "Enabled Enabled")
|
||||
channel.buffer += "\nSW-08(lldp)# "
|
||||
else:
|
||||
original(data)
|
||||
|
||||
channel.send = send
|
||||
result = lancom.run_commands(channel, enable_lldp=True, wait=0)
|
||||
assert "mode 1-2 enable" in channel.sent
|
||||
assert result["lldp_enabled_automatically"] is True
|
||||
snapshot = build_snapshot(dict(outputs(), **result), "lancom_sx3")
|
||||
assert snapshot["lldp_enabled_automatically"] and not snapshot["lldp_disabled"]
|
||||
assert all(isinstance(value, str) for value in snapshot["raw"].values())
|
||||
|
||||
|
||||
def test_auto_detection_falls_back_to_carriage_return(monkeypatch):
|
||||
from netbox_sync.core import switches
|
||||
|
||||
real = switches._read_available
|
||||
|
||||
def quick(channel, timeout=20, initialize_session=False):
|
||||
return real(channel, timeout=min(timeout, 0.3), initialize_session=initialize_session)
|
||||
|
||||
monkeypatch.setattr(switches, "_read_available", quick)
|
||||
channel = FakeChannel()
|
||||
assert switches.detect_platform(channel, "SW-08# ") == "lancom_sx3"
|
||||
assert channel.mode == ""
|
||||
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, channel):
|
||||
self.channel = channel
|
||||
|
||||
def invoke_shell(self, **_kwargs):
|
||||
return self.channel
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
|
||||
def _quick_reads(monkeypatch):
|
||||
from netbox_sync.core import switches
|
||||
|
||||
real = switches._read_available
|
||||
monkeypatch.setattr(switches, "_read_available", lambda channel, timeout=20, initialize_session=False:
|
||||
real(channel, timeout=min(timeout, 0.3), initialize_session=initialize_session))
|
||||
command = lancom._run_cli_command
|
||||
monkeypatch.setattr(lancom, "_run_cli_command", lambda channel, text, timeout=20:
|
||||
command(channel, text, timeout=min(timeout, 0.3)))
|
||||
return switches
|
||||
|
||||
|
||||
def test_session_is_recorded(monkeypatch):
|
||||
switches = _quick_reads(monkeypatch)
|
||||
channel = FakeChannel()
|
||||
channel.buffer = "snmp community secret123\nSW-08# "
|
||||
monkeypatch.setattr(switches, "_open_client", lambda *_args: FakeClient(channel))
|
||||
outputs = switches.run_switch_commands({"host": "x", "platform": "lancom_sx3"})
|
||||
assert "»» system" in outputs["session"] and "Model Name" in outputs["session"]
|
||||
assert "secret123" not in outputs["session"]
|
||||
assert "Sitzung" not in outputs # only raw outputs, no UI titles
|
||||
assert build_snapshot(outputs, "lancom_sx3")["raw"]["session"] == outputs["session"]
|
||||
|
||||
|
||||
def test_session_is_attached_to_errors(monkeypatch):
|
||||
import pytest
|
||||
|
||||
switches = _quick_reads(monkeypatch)
|
||||
|
||||
class Silent(FakeChannel):
|
||||
def send(self, data):
|
||||
self.sent.append(data.strip()) # never answers with a prompt
|
||||
|
||||
channel = Silent()
|
||||
channel.buffer = "SW-08# "
|
||||
monkeypatch.setattr(switches, "_open_client", lambda *_args: FakeClient(channel))
|
||||
with pytest.raises(TimeoutError) as caught:
|
||||
switches.run_switch_commands({"host": "x", "platform": "lancom_sx3"})
|
||||
assert "SW-08#" in caught.value.transcript and "»» system" in caught.value.transcript
|
||||
|
||||
|
||||
def test_paging_is_answered_with_space():
|
||||
class Paging(FakeChannel):
|
||||
def send(self, data):
|
||||
if data == " ":
|
||||
self.sent.append("<space>")
|
||||
self.buffer += "\r \rFlash Size : 32\nSW-08(system)# "
|
||||
elif data.strip() == "show" and self.mode == "system":
|
||||
self.sent.append("show")
|
||||
self.buffer += "show\nModel Name : LANCOM GS-2326P+\nRAM Size : 128\n -- more --, next page: Space, q to quit"
|
||||
else:
|
||||
super().send(data)
|
||||
|
||||
channel = Paging()
|
||||
channel.mode = "system"
|
||||
output = lancom._run_cli_command(channel, "show", timeout=2)
|
||||
assert channel.sent == ["show", "<space>"]
|
||||
assert "RAM Size : 128" in output and "Flash Size : 32" in output
|
||||
assert "quit" not in output and "more" not in output
|
||||
|
||||
|
||||
def test_neighbor_on_named_local_port():
|
||||
neighbors = """
|
||||
Local Port : Port 2
|
||||
Chassis ID : 00-a0-57-11-22-33
|
||||
Port ID : LAN1
|
||||
System Name : AP-005
|
||||
Management Address : 10.0.0.50 (IPv4)
|
||||
SW-08(lldp)#"""
|
||||
snapshot = build_snapshot(dict(outputs(), neighbors=neighbors), "lancom_sx3")
|
||||
port = next(item for item in snapshot["interfaces"] if item["name"] == "2")
|
||||
assert port["neighbor"]["local_port"] == "2"
|
||||
assert port["neighbor"]["system_name"] == "AP-005" and port["neighbor"]["remote_port"] == "LAN1"
|
||||
assert port["neighbor"]["management_ip"] == "10.0.0.50"
|
||||
|
||||
|
||||
def test_reparse_fixes_older_exports():
|
||||
neighbors = "Local Port : Port 2\nPort ID : LAN1\nSystem Name : AP-005\nSW-08(lldp)#"
|
||||
snapshot = build_snapshot(dict(outputs(), neighbors=neighbors), "lancom_sx3")
|
||||
snapshot["neighbors"][0]["local_port"] = "Port 2" # as written by 4.16.3
|
||||
for item in snapshot["interfaces"]:
|
||||
item["neighbor"] = None
|
||||
snapshot["discovered_at"] = 123
|
||||
rebuilt = lancom.reparse(snapshot)
|
||||
assert rebuilt["discovered_at"] == 123
|
||||
assert next(item for item in rebuilt["interfaces"] if item["name"] == "2")["neighbor"]["system_name"] == "AP-005"
|
||||
assert lancom.reparse({"platform": "aruba_cx", "raw": {}}) == {"platform": "aruba_cx", "raw": {}}
|
||||
@@ -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"
|
||||
+334
-2
@@ -1,8 +1,18 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
from fake_netbox import FakeNetBox, Record
|
||||
from fake_netbox import Endpoint, FakeNetBox, Record
|
||||
|
||||
from netbox_sync.core.switches import build_snapshot, match_interfaces, plan_switch_sync, sync_snapshot_to_netbox
|
||||
from netbox_sync.core.switches import (
|
||||
build_snapshot,
|
||||
mask_config,
|
||||
match_interfaces,
|
||||
parse_lags,
|
||||
parse_stack,
|
||||
plan_switch_sync,
|
||||
port_label,
|
||||
stack_member,
|
||||
sync_snapshot_to_netbox,
|
||||
)
|
||||
from test_switches import COMWARE_BRIEF, COMWARE_LLDP
|
||||
|
||||
|
||||
@@ -280,3 +290,325 @@ def test_legacy_network_choices_still_work_and_migrate(tmp_path):
|
||||
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]
|
||||
|
||||
|
||||
CX_STACK_CONFIG = """
|
||||
hostname Switch36
|
||||
vsf member 1
|
||||
type jl661a
|
||||
link 1 1/1/49
|
||||
link 2 1/1/50
|
||||
vsf member 2
|
||||
type jl661a
|
||||
link 1 2/1/49
|
||||
link 2 2/1/51
|
||||
interface lag 1
|
||||
no shutdown
|
||||
no routing
|
||||
vlan trunk native 1
|
||||
vlan trunk allowed 10,200-204
|
||||
interface 1/1/1
|
||||
no routing
|
||||
vlan access 10
|
||||
interface 1/1/52
|
||||
lag 1
|
||||
interface 2/1/1
|
||||
no routing
|
||||
vlan access 10
|
||||
interface 2/1/52
|
||||
lag 1
|
||||
interface vlan 201
|
||||
ip address 172.16.201.2/24
|
||||
"""
|
||||
|
||||
|
||||
def _stack_snapshot():
|
||||
interfaces = [
|
||||
{"name": name, "enabled": True, "connected": True, "media": "1GbT", "speed_mbps": 1000, "ip_addresses": [],
|
||||
"vlans": {"untagged": [10], "tagged": [], "tagged_all": False}}
|
||||
for name in ("1/1/1", "1/1/2", "2/1/1", "2/1/2")
|
||||
] + [{"name": "lag1", "enabled": True, "connected": True, "ip_addresses": [], "vlans": None}]
|
||||
return {"platform": "aruba_cx", "interfaces": interfaces, "neighbors": [],
|
||||
"stack": parse_stack(CX_STACK_CONFIG, "aruba_cx", interfaces)}
|
||||
|
||||
|
||||
def test_aruba_cx_vsf_stack_is_detected():
|
||||
stack = parse_stack(CX_STACK_CONFIG, "aruba_cx")
|
||||
assert stack == [{"member": 1, "model": "jl661a", "mac": ""}, {"member": 2, "model": "jl661a", "mac": ""}]
|
||||
assert stack_member("2/1/5", "aruba_cx") == 2 and stack_member("lag1", "aruba_cx") is None
|
||||
assert stack_member("GigabitEthernet2/0/5", "hpe_comware") == 2 and stack_member("2/A3", "aruba_aos") == 2
|
||||
assert parse_stack("vsf member 1\n type jl661a\n", "aruba_cx") == [], "one member is no stack"
|
||||
aos = 'stacking\n member 1 type "JL256A" mac-address 9020c2-000001\n member 2 type "JL256A"\n exit\n'
|
||||
assert [(item["member"], item["model"]) for item in parse_stack(aos, "aruba_aos")] == [(1, "JL256A"), (2, "JL256A")]
|
||||
|
||||
|
||||
def test_stack_members_go_to_their_own_netbox_devices():
|
||||
nb, switch, _snapshot = _numbered_setup()
|
||||
snapshot = _stack_snapshot()
|
||||
# Member 2 is its own NetBox device whose device type named the ports "1/1/x".
|
||||
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=4, name="access-01-2", tenant=SimpleNamespace(id=7)))
|
||||
for index, name in enumerate(("1/1/1", "1/1/2"), start=60):
|
||||
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=index, name=name, device=SimpleNamespace(id=4),
|
||||
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None,
|
||||
label=""))
|
||||
|
||||
plan = plan_switch_sync(nb, switch, snapshot)
|
||||
assert [(entry["member"], entry["device_id"], entry["ports"]) for entry in plan["stack"]] == [(1, 1, 2), (2, None, 2)]
|
||||
assert plan["skipped_ports"] == 2
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||
assert report["notes"] == ["Stack-Mitglied 2: kein NetBox-Gerät gewählt – 2 Ports übersprungen"]
|
||||
|
||||
switch["stack_devices"] = {"1": 1, "2": 4}
|
||||
plan = plan_switch_sync(nb, switch, snapshot)
|
||||
by_name = {item["name"]: item for item in plan["interfaces"]}
|
||||
assert by_name["2/1/1"]["owner_id"] == 4 and by_name["2/1/1"]["netbox_name"] == "1/1/1"
|
||||
assert by_name["1/1/1"]["owner_id"] == 1 and by_name["1/1/1"]["netbox_name"] == "1"
|
||||
assert plan["owner_interfaces"]["4"] == ["1/1/1", "1/1/2"]
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert nb.dcim.interfaces.get(60).label == "10" and nb.dcim.interfaces.get(1).label == "10"
|
||||
assert [(payload["device"], payload["name"]) for payload in nb.dcim.interfaces.created] == [(1, "lag1")]
|
||||
|
||||
|
||||
def test_stack_is_filled_in_netbox_utilities_when_the_plugin_exists():
|
||||
nb, switch, _snapshot = _numbered_setup()
|
||||
snapshot = _stack_snapshot()
|
||||
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=4, name="access-01-2", tenant=SimpleNamespace(id=7)))
|
||||
switch["stack_devices"] = {"1": 1, "2": 4}
|
||||
# Without the plugin the stack is simply not written.
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert not report["errors"] and not any("Switch-Stack" in change for change in report["changes"])
|
||||
|
||||
nb.plugins = SimpleNamespace(utilities=SimpleNamespace(switch_stacks=Endpoint()))
|
||||
stacks = nb.plugins.utilities.switch_stacks
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||
assert "Switch-Stack access-01 neu mit Mitgliedern access-01-2 (NetBox Utilities)" in report["changes"]
|
||||
assert stacks.created == []
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert stacks.created == [{"device": 1, "members": [4]}]
|
||||
stacks.records[0].device = SimpleNamespace(id=1)
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||
assert not any("Switch-Stack" in change for change in report["changes"]), "already complete"
|
||||
|
||||
# Members entered by hand stay, missing ones are added.
|
||||
stacks.records[0].members = [9]
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert stacks.updates[-1] == (stacks.records[0].id, {"members": [9, 4]})
|
||||
|
||||
|
||||
def test_virtual_chassis_positions_are_suggested():
|
||||
nb, switch, _snapshot = _numbered_setup()
|
||||
snapshot = _stack_snapshot()
|
||||
nb.dcim.devices.get(1).virtual_chassis = SimpleNamespace(id=9)
|
||||
nb.dcim.devices.get(1).vc_position = 1
|
||||
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=4, name="access-01-2", tenant=SimpleNamespace(id=7),
|
||||
virtual_chassis=SimpleNamespace(id=9), vc_position=2))
|
||||
plan = plan_switch_sync(nb, switch, snapshot)
|
||||
assert [entry["device_id"] for entry in plan["stack"]] == [1, 4]
|
||||
|
||||
|
||||
CX_LAG_BRIEF = """
|
||||
Port Native Mode Type Enabled Status Reason Speed Description
|
||||
1/1/1 1 trunk 10G-SR yes up 10000 SOEM-E1
|
||||
1/1/2 1 trunk 10G-SR yes up 10000 SOEM-E1
|
||||
1/1/23 120 access 1G-BT yes up 1000 FritzBox
|
||||
lag1 1 trunk -- yes up -- 20000 Etage 1 Uplink
|
||||
"""
|
||||
|
||||
CX_LAG_CONFIG = """vlan 1
|
||||
vlan 100
|
||||
interface lag 1
|
||||
no routing
|
||||
vlan trunk native 1
|
||||
vlan trunk allowed 100,110,120,201,209-213
|
||||
interface 1/1/1
|
||||
no shutdown
|
||||
lag 1
|
||||
interface 1/1/2
|
||||
no shutdown
|
||||
lag 1
|
||||
interface 1/1/23
|
||||
no routing
|
||||
vlan access 120
|
||||
"""
|
||||
|
||||
|
||||
def test_lags_are_parsed_for_all_platforms():
|
||||
assert parse_lags(CX_LAG_CONFIG, "aruba_cx") == {"1/1/1": "lag1", "1/1/2": "lag1"}
|
||||
assert parse_lags("trunk 49-50 trk1 lacp\ntrunk 1/A1-1/A2 Trk2 trunk\n", "aruba_aos") == {
|
||||
"49": "Trk1", "50": "Trk1", "1/a1": "Trk2", "1/a2": "Trk2"}
|
||||
comware = "interface GigabitEthernet1/0/49\n port link-aggregation group 3\n#\n"
|
||||
assert parse_lags(comware, "hpe_comware") == {"ge1/0/49": "Bridge-Aggregation3"}
|
||||
|
||||
|
||||
def test_lag_members_take_the_lag_vlans_and_name_the_lag_in_the_label():
|
||||
snapshot = build_snapshot({"interfaces": CX_LAG_BRIEF, "neighbors": "", "config": CX_LAG_CONFIG}, "aruba_cx")
|
||||
ports = {item["name"]: item for item in snapshot["interfaces"]}
|
||||
assert ports["1/1/1"]["lag"] == "lag1" and ports["1/1/23"]["lag"] is None
|
||||
assert port_label(ports["1/1/1"]["vlans"], ports["1/1/1"]["lag"]) == "1,100,110,120,201,209-213 (LAG 1)"
|
||||
assert port_label(ports["1/1/23"]["vlans"], ports["1/1/23"]["lag"]) == "120"
|
||||
assert port_label(None, "Trk2") == "(LAG 2)"
|
||||
assert len(port_label({"untagged": [], "tagged": list(range(2, 400, 2)), "tagged_all": False}, "lag1")) <= 64
|
||||
assert " lag 1" in snapshot["raw"]["vlan_config"]
|
||||
|
||||
|
||||
def test_lag_members_are_assigned_to_their_lag_in_netbox():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=30, name="lag1", device=SimpleNamespace(id=1),
|
||||
type=SimpleNamespace(value="lag"), enabled=True, cable=None, label=""))
|
||||
snapshot["interfaces"].append({"name": "lag1", "enabled": True, "connected": True, "ip_addresses": [],
|
||||
"vlans": None})
|
||||
for item in snapshot["interfaces"][:2]:
|
||||
item["lag"] = "lag1"
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||
assert "Interface 1: LAG lag1" in report["changes"] and nb.dcim.interfaces.updates == []
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert nb.dcim.interfaces.get(1).lag == 30 and nb.dcim.interfaces.get(1).label == "10 (LAG 1)"
|
||||
assert not getattr(nb.dcim.interfaces.get(3), "lag", None)
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||
assert not any("LAG lag1" in change for change in report["changes"]), "already assigned"
|
||||
|
||||
|
||||
class _AttachmentEndpoint(Endpoint):
|
||||
def create(self, payload):
|
||||
record = super().create(payload)
|
||||
if self.assignments is not None:
|
||||
record.assignments = []
|
||||
return record
|
||||
|
||||
def filter(self, **kwargs):
|
||||
query = kwargs.pop("q", "")
|
||||
return [item for item in super().filter(**kwargs) if query in (getattr(item, "description", "") or "")]
|
||||
|
||||
|
||||
def _attachments(newer=True):
|
||||
attachments = _AttachmentEndpoint()
|
||||
attachments.assignments = [] if newer else None
|
||||
return SimpleNamespace(netbox_attachments=attachments, netbox_attachment_assignments=Endpoint())
|
||||
|
||||
|
||||
def test_config_backup_masks_secrets():
|
||||
config = ('hostname core\nuser admin group administrators password ciphertext AQBapW==\n'
|
||||
'snmp-server community geheim\nradius-server host 10.0.0.1 key plaintext topsecret\n')
|
||||
masked = mask_config(config)
|
||||
assert "AQBapW" not in masked and "geheim" not in masked and "topsecret" not in masked
|
||||
assert "hostname core" in masked and "password <entfernt>" in masked
|
||||
|
||||
|
||||
def test_config_is_attached_only_when_it_changed():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
snapshot["config_backup"] = "hostname access-01"
|
||||
# Without the plugin nothing happens.
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, backup_config=True)
|
||||
assert not report["errors"]
|
||||
|
||||
nb.plugins = SimpleNamespace(netbox_attachments=_attachments())
|
||||
app = nb.plugins.netbox_attachments
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True, backup_config=True)
|
||||
assert any(change.startswith("Konfigurations-Backup: Anhang „Running-Config access-01")
|
||||
for change in report["changes"]) and app.netbox_attachments.created == []
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, backup_config=True)
|
||||
payload = app.netbox_attachments.created[0]
|
||||
assert payload["file"][1].getvalue() == b"hostname access-01" and payload["file"][0].endswith(".txt")
|
||||
assert app.netbox_attachment_assignments.created == [
|
||||
{"attachment": app.netbox_attachments.records[0].id, "object_type": "dcim.device", "object_id": 1}]
|
||||
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True, backup_config=True)
|
||||
assert not any("Konfigurations-Backup" in change for change in report["changes"]), "unchanged"
|
||||
snapshot["config_backup"] = "hostname access-01\nvlan 10"
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, backup_config=True)
|
||||
assert len(app.netbox_attachments.created) == 2
|
||||
|
||||
|
||||
def test_config_backup_with_older_attachment_plugin():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
snapshot["config_backup"] = "hostname access-01"
|
||||
nb.plugins = SimpleNamespace(netbox_attachments=_attachments(newer=False))
|
||||
app = nb.plugins.netbox_attachments
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, backup_config=True)
|
||||
payload = app.netbox_attachments.created[0]
|
||||
assert (payload["object_type"], payload["object_id"]) == ("dcim.device", 1)
|
||||
assert app.netbox_attachment_assignments.created == []
|
||||
|
||||
|
||||
def test_cable_to_access_point_that_reports_its_mac_as_port():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=5, name="PC-AP-1", tenant=SimpleNamespace(id=7)))
|
||||
nb.dcim.interfaces.records += [
|
||||
Record(nb.dcim.interfaces, id=50, name="LAN", device=SimpleNamespace(id=5), mac_address="C8:4F:86:88:96:8E",
|
||||
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None),
|
||||
Record(nb.dcim.interfaces, id=51, name="LAN2", device=SimpleNamespace(id=5), mac_address=None,
|
||||
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None),
|
||||
]
|
||||
snapshot["neighbors"][0].update(system_name="AP6420-PA3007MFJ3BDX1A", remote_port="c8:4f:86:88:96:8e")
|
||||
switch["neighbor_devices"] = {"1/1/2": 5}
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot)
|
||||
assert nb.dcim.cables.created[0]["b_terminations"] == [{"object_type": "dcim.interface", "object_id": 50}]
|
||||
|
||||
# A device with a single port is cabled there even if neither name nor MAC match.
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=5, name="PC-AP-1", tenant=SimpleNamespace(id=7)))
|
||||
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=50, name="eth0", device=SimpleNamespace(id=5),
|
||||
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None))
|
||||
snapshot["neighbors"][0].update(system_name="AP6420", remote_port="c8:4f:86:88:96:cc")
|
||||
switch["neighbor_devices"] = {"1/1/2": 5}
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot)
|
||||
assert nb.dcim.cables.created[0]["b_terminations"] == [{"object_type": "dcim.interface", "object_id": 50}]
|
||||
|
||||
|
||||
def _cabled_setup(far_type="dcim.interface"):
|
||||
"""Port 1/1/2 (NetBox "2") has a cable to "old-device eth9"; LLDP reports server-01 eth0."""
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
nb.dcim.interfaces.get(2).cable = SimpleNamespace(id=70)
|
||||
far = {"object_type": far_type, "object_id": 99,
|
||||
"object": {"name": "eth9", "device": {"name": "old-device"}}}
|
||||
nb.dcim.cables.records.append(Record(nb.dcim.cables, id=70, a_terminations=[far],
|
||||
b_terminations=[{"object_type": "dcim.interface", "object_id": 2}]))
|
||||
switch["neighbor_devices"] = {"1/1/2": 2}
|
||||
return nb, switch, snapshot
|
||||
|
||||
|
||||
def test_differing_cable_is_only_reported_by_default():
|
||||
nb, switch, snapshot = _cabled_setup()
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot)
|
||||
assert report["cables_updated"] == 0 and nb.dcim.cables.updates == []
|
||||
assert any("in NetBox mit old-device eth9 verbunden – nicht angepasst" in note for note in report["notes"])
|
||||
|
||||
|
||||
def test_differing_cable_is_moved_when_allowed():
|
||||
nb, switch, snapshot = _cabled_setup()
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True, update_cables=True)
|
||||
assert report["cables_updated"] == 1 and nb.dcim.cables.updates == []
|
||||
assert any(change.startswith("⚠ Kabel access-01") and "old-device eth9" in change for change in report["changes"])
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, update_cables=True)
|
||||
assert nb.dcim.cables.updates == [(70, {
|
||||
"a_terminations": [{"object_type": "dcim.interface", "object_id": 2}],
|
||||
"b_terminations": [{"object_type": "dcim.interface", "object_id": 20}]})]
|
||||
assert nb.dcim.cables.created == []
|
||||
|
||||
|
||||
def test_cables_to_patch_panels_and_busy_far_ends_are_kept():
|
||||
nb, switch, snapshot = _cabled_setup(far_type="dcim.frontport")
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, update_cables=True)
|
||||
assert report["cables_updated"] == 0 and nb.dcim.cables.updates == [] and not report["notes"]
|
||||
|
||||
nb, switch, snapshot = _cabled_setup()
|
||||
nb.dcim.interfaces.get(20).cable = SimpleNamespace(id=71)
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, update_cables=True)
|
||||
assert nb.dcim.cables.updates == []
|
||||
assert any("Gegenstelle hat bereits ein anderes Kabel" in note for note in report["notes"])
|
||||
|
||||
|
||||
def test_vlans_of_another_site_are_only_labelled():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
nb.dcim.devices.get(1).site = SimpleNamespace(id=2)
|
||||
nb.ipam.vlans.records += [
|
||||
Record(nb.ipam.vlans, id=110, vid=10, name="MOBILE", tenant=SimpleNamespace(id=7), site=SimpleNamespace(id=1)),
|
||||
Record(nb.ipam.vlans, id=120, vid=20, name="CLIENTS", tenant=SimpleNamespace(id=7), site=None),
|
||||
]
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert report["errors"] == []
|
||||
assert nb.dcim.interfaces.get(1).label == "10" and getattr(nb.dcim.interfaces.get(1), "untagged_vlan", None) is None
|
||||
assert nb.dcim.interfaces.get(2).untagged_vlan == 120, "global VLANs are always assigned"
|
||||
assert [note for note in report["notes"] if "VLAN 10" in note] == [
|
||||
"VLAN 10 „MOBILE“ gehört zu einem anderen Standort als access-01 – nur im Label vermerkt, nicht am Port "
|
||||
"zugewiesen (VLAN global machen, um es zuzuweisen)"]
|
||||
Reference in new issue
Block a user