Compare commits

...
68 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 ef12531c8e chore: release 4.20.3
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 12:29:59 +01:00
MrBlakeandClaude Opus 5.5 98c8647501 feat: maintain netbox-inventory assets for clients and show the agent's software list
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 12:29:58 +01:00
MrBlakeandClaude Opus 5.5 d6622cf48f chore: release 4.20.2
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 12:13:24 +01:00
MrBlakeandClaude Opus 5.5 1f338902a7 feat: write the agent's hardware and software inventory into the device comments
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 12:13:23 +01:00
MrBlakeandClaude Opus 5.5 76f12069b5 chore: release 4.20.1
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 11:16:12 +01:00
MrBlakeandClaude Opus 5.5 76662dd378 docs: link the agent release and list the GPO share files in the setup guide
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 11:16:12 +01:00
MrBlakeandClaude Opus 5.5 9603add434 chore: release 4.20.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 11:05:32 +01:00
MrBlakeandClaude Opus 5.5 a67b0d3e5c feat: scan Windows clients with the NetBox Windows Agent in listen mode
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 11:05:32 +01:00
MrBlakeandClaude Opus 5.5 43c5e5e85a chore: release 4.19.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 10:15:56 +01:00
MrBlakeandClaude Opus 5.5 b1cfdf7a5c feat: map missing printer models to device types and ignore printers or models
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 10:15:55 +01:00
MrBlakeandClaude Opus 5.5 2db5e1f251 chore: release 4.18.1
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 10:07:44 +01:00
MrBlakeandClaude Opus 5.5 4d77528266 fix: start the printer comparison after the scan has ended and allow a site per printer
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 10:07:43 +01:00
MrBlakeandClaude Opus 5.5 596bbabb54 chore: release 4.18.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 09:39:50 +01:00
MrBlakeandClaude Opus 5.5 235fb8e26a feat: printer import via SNMP v2c/v3 scan with page counter and supplies
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 09:39:50 +01:00
MrBlakeandClaude Opus 5.5 05d34e4823 chore: release 4.17.1
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 09:05:46 +01:00
MrBlakeandClaude Opus 5.5 f134db0c16 fix: put access point IPs into the VRF of the matching tenant prefix instead of always global
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 09:05:45 +01:00
MrBlakeandClaude Opus 5.5 1352514577 chore: release 4.17.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 16:50:33 +01:00
MrBlakeandClaude Opus 5.5 fc503bd7d3 feat: choose the far-end interface of a cable in the review dialog
The neighbor tab gets a "Nachbar-Schnittstelle" column with the cable targets
of the neighbor device (no wireless interfaces) and the automatic choice;
the selection is stored per switch as neighbor_interfaces.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 16:50:33 +01:00
MrBlakeandClaude Opus 5.5 144e5f9eb8 fix: ignore wireless interfaces when looking for the far end of a cable
NetBox does not allow cables on wireless interfaces; wlan1 made "LAN1" on a
LANCOM LW-600 (eth1, wlan0, wlan1) ambiguous and prevented the single-port rule.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 16:46:24 +01:00
MrBlakeandClaude Opus 5.5 823d968b33 chore: release 4.16.5
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 16:39:23 +01:00
MrBlakeandClaude Opus 5.5 0241509845 fix: LANCOM LLDP fields with empty values, indented lines after paging and prompt as port description; explain skipped cables
Every skipped cable is reported as a note with its reason (local port,
neighbor device or far-end interface not found, far end already cabled).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 16:38:23 +01:00
MrBlakeandClaude Opus 5.5 b89a364bf0 chore: release 4.16.4
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 16:28:48 +01:00
MrBlakeandClaude Opus 5.5 97ee72e610 fix: LANCOM LLDP neighbors on "Port N" were not linked to the switch port
Also rebuild LANCOM snapshots from their raw outputs on file import, so
older exports get the fix without reading the switch again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 16:28:21 +01:00
MrBlakeandClaude Opus 5.5 c85df7402d chore: release 4.16.3
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 16:03:52 +01:00
MrBlakeandClaude Opus 5.5 5427cc015e fix: answer the paging prompt of LANCOM LCOS SX 3.x switches
Long outputs stop with "..., q to quit" and the pager cannot be disabled;
it is now answered with Space and removed from the output.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 16:03:52 +01:00
MrBlakeandClaude Opus 5.5 1aa1c15aa8 chore: release 4.16.2
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 15:47:49 +01:00
MrBlakeandClaude Opus 5.5 51f3fc70cd feat: record the CLI session and show it as raw data, also for failed discoveries
The raw data view builds its tabs from the available outputs (incl. LANCOM)
and adds a "Sitzung" tab with the masked session up to an error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 15:47:49 +01:00
MrBlakeandClaude Opus 5.5 411c5446fe fix: send carriage return as Enter to LANCOM LCOS SX 3.x switches
The CLI only echoes commands terminated with "\n". Auto-detection falls back
to "\r" when the first command is not completed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 15:34:34 +01:00
MrBlakeandClaude Opus 5.5 1bd2d42b5d chore: release 4.16.1
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 15:05:26 +01:00
MrBlakeandClaude Opus 5.5 2092f41624 fix: SSH to older switches offering only ssh-rsa/ssh-dss host keys; split switch result filters into two rows
Paramiko 4+ removed ssh-rsa (SHA-1) and ssh-dss; pin to 3.x so switches like
the LANCOM GS-2326P+ can be reached again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 15:04:59 +01:00
MrBlakeandClaude Opus 5.5 e9e1783360 chore: release 4.16.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 14:48:43 +01:00
MrBlakeandClaude Opus 5.5 576f245b7d feat: LANCOM LCOS SX 3.x switches over SSH (e.g. GS-2326P+)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 14:48:43 +01:00
MrBlakeandClaude Opus 5.5 0e04dae354 chore: release 4.15.1
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 12:50:50 +01:00
MrBlakeandClaude Opus 5.5 63ed535a37 fix: attach the original D-Link config.bin as configuration backup
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 12:50:19 +01:00
MrBlakeandClaude Opus 5.5 781ed7d17b chore: release 4.15.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 12:35:52 +01:00
MrBlakeandClaude Opus 5.5 05695a8471 feat: one-off switch import from D-Link and Linksys configuration backups
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 12:35:51 +01:00
MrBlakeandClaude Opus 5.5 1949f03bae chore: release 4.14.1
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 10:47:47 +01:00
MrBlakeandClaude Opus 5.5 dfe985bb9e fix: assign only VLANs of the device's site; show notes prominently
- VLANs of another site stay in the label but are not assigned to ports
  (NetBox rejects them); one note per device and VLAN instead of an error
  per port
- Preview shows a notes badge and expands switches with notes; notes are
  also written to the log after the transfer

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 10:47:33 +01:00
MrBlakeandClaude Opus 5.5 d853f08445 chore: release 4.14.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 10:29:56 +01:00
MrBlakeandClaude Opus 5.5 f4c507de6c feat: optional update of existing cables; cable APs reporting their MAC as port
- Cables to neighbors that report their MAC address as port ID (e.g. access
  points) are created via the MAC or the device's single physical port
- Existing cables are compared with LLDP/CDP; differences are reported, and
  only with the optional "Bestehende Kabel anpassen" the cable is moved

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 10:29:55 +01:00
MrBlakeandClaude Opus 5.5 3c8bc7879c chore: release 4.13.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 10:13:50 +01:00
MrBlakeandClaude Opus 5.5 770edc4a03 feat: optional running-config backup as NetBox attachment
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 10:13:49 +01:00
MrBlakeandClaude Opus 5.5 eee60d26ad chore: release 4.12.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 10:06:11 +01:00
MrBlakeandClaude Opus 5.5 63fd7b987a feat: LAG members get their LAG in the label and NetBox LAG field
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 10:06:10 +01:00
MrBlakeandClaude Opus 5.5 899b4c58fc chore: release 4.11.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 09:27:10 +01:00
MrBlakeandClaude Opus 5.5 89fe37ea04 feat: fill in detected stacks in the optional NetBox Utilities plugin
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 09:27:09 +01:00
MrBlakeandClaude Opus 5.5 34b1391ff0 chore: release 4.10.5
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 08:41:38 +01:00
MrBlakeandClaude Opus 5.5 340f404f94 fix: allow equal interface names on different stack member devices
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 08:41:24 +01:00
MrBlakeandClaude Opus 5.5 f1af9f8f86 chore: release 4.10.4
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 15:46:22 +01:00
MrBlakeandClaude Opus 5.5 2fb6ac38ec feat: ignore Sophos sites without site and tenant
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 15:46:21 +01:00
MrBlakeandClaude Opus 5.5 2dcd0b0855 chore: release 4.10.3
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 15:23:29 +01:00
MrBlakeandClaude Opus 5.5 159a933964 feat: Sophos AP import without upfront tenant, tenant never preselected
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 15:23:28 +01:00
MrBlakeandClaude Opus 5.5 c81d9a7edc chore: release 4.10.2
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 15:17:22 +01:00
MrBlakeandClaude Opus 5.5 dc8921aaea fix: read switch stacks through their master, group preview by stack member
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 15:17:22 +01:00
MrBlakeandClaude Opus 5.5 1942d6ecdf chore: release 4.10.1
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 13:18:21 +01:00
MrBlakeandClaude Opus 5.5 b402591cdf fix: adaptive empty state, escaped button ampersand, no tenant preselection for APs
- Empty states hide icon and text when space is short instead of being
  squeezed; title and button always stay readable
- "Standorte & Mandanten" button no longer shows a mnemonic underscore
- The tenant on the access point page is always chosen deliberately

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 13:18:21 +01:00
MrBlakeandClaude Opus 5.5 ba50527ee5 chore: release 4.10.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 13:08:30 +01:00
MrBlakeandClaude Opus 5.5 8d2bbafc8d feat: switch stacks per member device, optional AP sites with mandatory tenant
- Detect stacks (Aruba CX VSF, ArubaOS-Switch stacking/VSF, Comware IRF) from
  the configuration; new "Stack" tab assigns a NetBox device per member
  (suggested from virtual chassis positions, stored per switch); ports go to
  their member's device, LAGs and VLAN interfaces stay on the switch device
- Access points: site is optional with a default site for new APs; tenant is
  mandatory and can be chosen per Sophos site; new tenant column
- Empty states no longer get squeezed in small cards

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 13:08:30 +01:00
MrBlakeandClaude Opus 5.5 f400795cb5 chore: release 4.9.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 16:50:12 +01:00
MrBlakeandClaude Opus 5.5 9ce25d820a feat: import Sophos access points from a Sophos Central CSV export
- New "Access Points" page: load the Sophos Central export, check missing
  sites and duplicate IPs, serial numbers and MAC addresses
- Find existing APs globally by serial number and MAC (chunked queries) and
  by name within the tenant group; list NetBox APs missing in the export
- Map Sophos sites to NetBox sites of the tenant group (suggested by name,
  stored per profile, per-AP choice for APs without site)
- Create or update devices with Sophos device type, role, site, serial,
  firmware, interface, MAC and primary IP; tenant from the site or the chosen
  tenant, devices of other tenants are never changed; preview before writing

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 14:18:09 +01:00
44 changed files with 8405 additions and 274 deletions

No files matched your search

+147 -7
View File
@@ -21,7 +21,11 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
- Light and dark theme (optionally following Windows)
- Log with filter, search and export, plus a rotating log file under
`%APPDATA%\NetBox VM Import\logs`
- Keyboard shortcuts: `Ctrl+1…8` navigation, `F5` reload/read, `Ctrl+F` search
- Keyboard shortcuts: `Ctrl+1…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
restarts. A version can be skipped
### Virtual machines
@@ -45,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
@@ -57,20 +62,141 @@ 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
LLDP/CDP neighbour can be corrected; a neighbour can be assigned manually to
any device of the switch's tenant group. Choices are stored in the profile
- Networks and VLANs in the same review: per network the VRF (global, a tenant
VRF or a new one) and whether a missing prefix is created; missing VLANs
(named from the switch configuration) are only created when ticked. Existing
VLANs are assigned to the ports (802.1Q mode, untagged/tagged)
- Networks and VLANs in the same review: per network the VRF (global, a VRF of
the tenant group or a new one) and whether a missing prefix is created. Network
decisions are stored per profile like the VLAN decisions; networks whose
prefix exists or that were decided before sit in a collapsed, editable section
- VLAN mapping: switch VLANs are matched to NetBox VLANs of the switch's tenant
group by VID (own tenant, site and similar names decide between several);
each VLAN can be mapped manually, skipped or created with a name and a tenant
of the tenant group of your choice (pre-filled from the switch configuration
and the switch's tenant). VLANs can also be **ignored** on all switches –
they are neither created nor assigned and are left out of the labels. VLAN
decisions are stored per profile (shared by all its switches); only VLANs
that still need a decision are shown, stored and unambiguous ones are in a
collapsed section that can be expanded for editing. Mapped VLANs are assigned
to the ports (802.1Q mode, untagged/tagged)
- Tenant required: a switch without tenant in NetBox is refused; every created
IP address, prefix, VRF, VLAN and cable gets the switch's tenant
- Cables from LLDP/CDP, also with FQDN system names or via the management IP
- 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.
Wireless interfaces (Wi-Fi, LTE …) are never cable targets. In the review
dialog the far-end interface can be chosen per neighbor ("automatisch" shows
the interface that would be used); the choice is stored in the profile.
Every skipped cable is listed as a note with its reason
- 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
- IP addresses go into the VRF of the most specific matching prefix of the
tenant (group), otherwise global
### Printers (SNMP scan)
- Scans IP ranges for printers of any manufacturer via the standard Host
Resources and Printer MIBs (RFC 3805); hosts that do not answer ping are
still probed on the printer ports 9100/631/515
- SNMPv2c communities and SNMPv3 users (MD5, SHA-1, SHA-224/256/384/512; DES,
AES-128/192/256) are stored per profile (secrets encrypted with DPAPI) and
tried in order; the credential that worked is remembered per address and
tried first next time. Rejected SNMPv3 logins are explained (unknown user,
wrong password, wrong privacy settings)
- Reads name, location, contact, manufacturer (from sysObjectID), model,
serial number, firmware, MAC address, netmask, page counter, colour
capability, supplies (toner, drum, waste toner, fuser … with fill level),
paper trays, status, error flags, display text and alerts
- Devices with open printer ports but no SNMP answer are listed as
"without SNMP"
- Printers can be ignored this time or permanently (context menu); models
missing in NetBox as device type can be created, mapped to an existing
device type (with suggestion), skipped this time or ignored permanently
("Modelle …", asked before the transfer)
- The model is taken from prtGeneralPrinterName, hrDeviceDescr or the HP
device ID – not from generic JetDirect descriptions
- Same workflow as the access point import: matching by serial number, MAC
address, name and IP address, site/tenant mapping by SNMP location, default
site, preview before writing
- Optionally stores page counter, supplies, colour capability and scan date in
custom fields of the device (created on first transfer, group "Drucker")
### 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)
@@ -93,6 +219,20 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
permissions, common errors, check commands and a connection test for single
clients
### Windows clients with the NetBox Windows Agent
- Third target mode **NetBox-Agent (Netzwerk-Scan)**: scans IP ranges for the
[NetBox Windows Agent](https://git.mrblake.cc/MrBlake/Netbox-Client-Agent-for-Windows)
in listen mode – no WinRM, no admin account and no NetBox access needed on the
clients; only hosts with an answering agent are listed
- One shared key per profile (encrypted with DPAPI); requests are signed with
HMAC-SHA256, the inventory comes back encrypted with AES-256-GCM
- "Agent-Konfiguration speichern …" writes the ready `config.json` (port,
key, optional allowed networks) for unattended deployment with Intune or a
Group Policy startup script; the setup guide has a tab with all steps
- The agent data runs through the same table and NetBox transfer as the WinRM
scan, plus disks and the number of installed programs in the tooltip
### Offline mode (without NetBox)
- "Offline mode (without NetBox)" checkbox in the sidebar — global, independent
+3 -1
View File
@@ -3,7 +3,7 @@
#define AppName "NetBox Synchronizer"
#ifndef AppVersion
#define AppVersion "4.4.0"
#define AppVersion "4.20.3"
#endif
#define AppPublisher "Louis-Alexander Kerst"
#define AppExeName "NetBoxSynchronizer.exe"
@@ -66,6 +66,8 @@ Name: "{autodesktop}\{#AppName}"; Filename: "{app}\{#AppExeName}"; AppUserModelI
[Run]
Filename: "{app}\{#AppExeName}"; Description: "{cm:LaunchProgram,{#AppName}}"; Flags: nowait postinstall skipifsilent
; Restart after an update started from within the application (silent mode).
Filename: "{app}\{#AppExeName}"; Flags: nowait; Check: WizardSilent
[Code]
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
+1 -1
View File
@@ -1,7 +1,7 @@
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
APP_NAME = "NetBox Synchronizer"
APP_VERSION = "4.4.0"
APP_VERSION = "4.20.3"
APP_PUBLISHER = "Louis-Alexander Kerst"
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
+114
View File
@@ -0,0 +1,114 @@
"""Query the NetBox Windows Agent in "listen" mode (protocol v1).
The agent answers ``GET /v1/info`` without authentication. The inventory at
``GET /v1/inventory`` needs a signature (HMAC-SHA256 with a key derived from
the shared scan key) over a fresh nonce and the current time, and comes back
encrypted with AES-256-GCM, so serial numbers and software lists never cross
the network in clear text even without TLS certificates.
The decrypted inventory has the same shape as the WinRM scan
(:func:`netbox_sync.core.wsman.query_client`), so it runs through the same
table and NetBox transfer as the agentless client scan.
"""
import base64
import hashlib
import hmac
import http.client
import json
import secrets
import time
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
DEFAULT_PORT = 8731
PROTOCOL = 1
AGENT_NAME = "netbox-windows-agent"
class AgentError(Exception):
"""The host answered, but not as an agent we can read (wrong key, other service …)."""
def derive_key(secret, purpose):
return hmac.new(secret.encode(), purpose.encode(), hashlib.sha256).digest()
def new_scan_key():
"""Random shared key for the agents of one customer (URL-safe, 43 characters)."""
return secrets.token_urlsafe(32)
def _get(host, port, path, headers=None, timeout=5.0):
connection = http.client.HTTPConnection(host, port, timeout=timeout)
try:
connection.request("GET", path, headers=headers or {})
response = connection.getresponse()
body = response.read(16 * 1024 * 1024)
return response.status, body
finally:
connection.close()
def _json(body):
try:
return json.loads(body.decode("utf-8"))
except (UnicodeDecodeError, ValueError) as error:
raise AgentError("keine gültige Antwort (kein NetBox-Agent?)") from error
def info(host, port=DEFAULT_PORT, timeout=3.0):
status, body = _get(host, port, "/v1/info", timeout=timeout)
data = _json(body)
if status != 200 or data.get("agent") != AGENT_NAME:
raise AgentError("kein NetBox-Agent auf diesem Port")
return data
def inventory(host, key, port=DEFAULT_PORT, timeout=60.0):
"""Decrypted inventory dict of one agent."""
nonce = secrets.token_hex(16)
ts = str(int(time.time()))
signature = hmac.new(derive_key(key, "netbox-agent auth v1"), f"GET\n/v1/inventory\n{nonce}\n{ts}".encode(),
hashlib.sha256).hexdigest()
status, body = _get(host, port, f"/v1/inventory?nonce={nonce}&ts={ts}", {"X-Agent-Signature": signature},
timeout)
data = _json(body)
if status != 200:
reason = data.get("error", f"HTTP {status}")
raise AgentError({
"wrong key": "Agent-Schlüssel stimmt nicht",
"clock skew too large": "Uhrzeit von Client und diesem Rechner weicht mehr als 5 Minuten ab",
"address not allowed": "dieser Rechner ist in allowed_networks des Agenten nicht freigegeben",
}.get(reason, f"Agent meldet: {reason}"))
try:
payload = AESGCM(derive_key(key, "netbox-agent enc v1")).decrypt(
base64.b64decode(data["iv"]), base64.b64decode(data["data"]), nonce.encode())
except Exception as error: # noqa: BLE001 - InvalidTag, KeyError, binascii.Error
raise AgentError("Antwort lässt sich nicht entschlüsseln (falscher Schlüssel?)") from error
return json.loads(payload.decode("utf-8"))
def query(host, key, port=DEFAULT_PORT, timeout=60.0):
"""Raw result for :func:`netbox_sync.core.clients.apply_scan` – never raises."""
try:
result = inventory(host, key, port, timeout)
except AgentError as error:
return {"host": host, "ok": False, "error": str(error)}
except (OSError, http.client.HTTPException) as error:
return {"host": host, "ok": False, "error": f"Agent nicht erreichbar: {error}"}
result.update(host=host, ok=True)
return result
def agent_config(key, port=DEFAULT_PORT, allowed_networks=(), collect_software=True):
"""``config.json`` for agents in listen mode (no NetBox access needed on the clients)."""
return {
"mode": "listen",
"listen_port": port,
"scan_key": key,
"allowed_networks": list(allowed_networks),
"inventory_cache_seconds": 300,
"collect_software": collect_software,
"max_software_entries": 250,
}
+436
View File
@@ -0,0 +1,436 @@
"""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.switches import candidate_vrfs
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())
self.netbox_aps = self._known_devices({})
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())
self.netbox_aps = self._known_devices(scope)
return self.ap_sites
def _known_devices(self, scope):
"""Devices of this kind in NetBox (``scope`` limits them to the tenant group)."""
manufacturer = (self.nb.dcim.manufacturers.get(slug="sophos")
or next(iter(self.nb.dcim.manufacturers.filter(name__ie=MANUFACTURER)), None))
return list(self.nb.dcim.devices.filter(manufacturer_id=manufacturer.id, **scope)) if manufacturer else []
def _identity(self, ap):
"""``(manufacturer, model, platform or None)`` of a new device."""
return MANUFACTURER, ap["model"] or "Access Point", PLATFORM
def _mapped_type(self, ap):
"""Device type ID chosen by the user instead of creating one, or ``None``."""
return None
def _extra_payload(self, ap):
"""Additional fields for a new device."""
return {}
def _extra_updates(self, device, ap):
"""Additional field changes for an existing device: ``(updates, change texts)``."""
return {}, []
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()
self._vrf_cache = {}
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
extra, extra_texts = self._extra_updates(device, ap)
updates.update(extra)
if updates:
report["devices_updated"] += 1
changes.append("Aktualisieren: " + ", ".join(
[f"{key} → {value}" for key, value in updates.items() if key not in ("tenant", *extra)]
+ extra_texts) + (" (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, model, platform = self._identity(ap)
manufacturer_id = self._manufacturer(manufacturer, report, dry_run)
type_id = self._mapped_type(ap) or self._device_type(manufacturer, manufacturer_id, model, report,
dry_run)
platform_id = self._platform(platform, report, dry_run) if platform else None
# 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"}
if platform:
payload["platform"] = platform_id
if ap["serial"]:
payload["serial"] = ap["serial"]
if description:
payload["description"] = description
payload.update(self._extra_payload(ap))
report["devices_created"] += 1
changes.append(f"Gerät anlegen ({model})")
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
prefix = self._prefix_for(ap["ip"], tenant_id)
vrf = getattr(prefix, "vrf", None) if prefix else None
changes.append(f"IP-Adresse {ap['ip']} anlegen" + (f" (VRF {vrf.name})" if vrf else ""))
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 _prefix_for(self, ip, tenant_id):
"""Most specific prefix containing ``ip``, globally or in a VRF of the tenant (group).
With the same length a VRF prefix wins over a global one.
"""
if tenant_id not in self._vrf_cache:
# VRFs of the device's tenant and of the tenant chosen for the import (and their groups).
owners = {owner for owner in (tenant_id, self.tenant_id) if owner}
self._vrf_cache[tenant_id] = {vrf.id for owner in owners for vrf in candidate_vrfs(self.nb, owner)}
allowed = self._vrf_cache[tenant_id]
prefixes = [prefix for prefix in self.nb.ipam.prefixes.filter(contains=ip)
if related_id(prefix, "vrf") is None or related_id(prefix, "vrf") in allowed]
return max(prefixes, default=None, key=lambda prefix: (
ipaddress.ip_network(str(prefix.prefix), strict=False).prefixlen, related_id(prefix, "vrf") is not None))
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 = self._prefix_for(ap["ip"], tenant_id)
length = str(getattr(prefix, "prefix", "")).split("/")[-1] if prefix else str(ap.get("prefix_length") or 32)
vrf_id = related_id(prefix, "vrf") if prefix else None
address = f"{ap['ip']}/{length}"
where = f" (VRF {getattr(getattr(prefix, 'vrf', None), 'name', vrf_id)})" if vrf_id else ""
existing = list(self.nb.ipam.ip_addresses.filter(address=ap["ip"], vrf_id=vrf_id or "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{where}")
if dry_run or interface is None:
return changes
ip = self.nb.ipam.ip_addresses.create({
"address": address, "status": "active", "tenant": tenant_id, "vrf": vrf_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
+342
View File
@@ -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))
+151 -1
View File
@@ -7,11 +7,80 @@ written; the report lists what would change.
"""
import re
import time
from netbox_sync.core.netbox import assign_mac, normalize_mac, related_id
from netbox_sync.core.clients import os_label
REPORT_START = "<!-- netbox-sync:inventory -->"
REPORT_END = "<!-- /netbox-sync:inventory -->"
def inventory_report(client):
"""Markdown hardware and software report of an agent scan, or ``""`` for other sources."""
if client.get("source") != "agent":
return ""
lines = ["## Inventar (NetBox Windows Agent)", ""]
for caption, value in (
("System", " ".join(part for part in (client.get("manufacturer"), client.get("model")) if part)),
("Seriennummer", client.get("serial")),
("Betriebssystem", " ".join(part for part in (client.get("os"), client.get("os_display_version"),
f"(Build {client['os_build']})" if client.get("os_build")
else "") if part)),
("CPU", f"{client['cpu']} ({client.get('cores') or '?'} Kerne)" if client.get("cpu") else ""),
("RAM", f"{client['memory'] / 1024 ** 3:.0f} GB" if client.get("memory") else ""),
("Erfasst", client.get("scanned_at") and time.strftime("%d.%m.%Y %H:%M", time.localtime(client["scanned_at"]))),
):
if value:
lines.append(f"- **{caption}:** {value}")
if client.get("disks"):
lines += ["", "### Datenträger"]
lines += [f"- {disk['model']} – {disk['size'] / 1e9:.0f} GB" + (f" – S/N {disk['serial']}" if disk.get("serial")
else "") for disk in client["disks"]]
if client.get("memory_modules"):
lines += ["", "### Arbeitsspeicher"]
lines += [f"- {item['bank'] or 'RAM'}: {item['capacity'] / 1024 ** 3:.0f} GB"
+ (f" {item['manufacturer']}" if item.get("manufacturer") else "")
+ (f" {item['part_number']}" if item.get("part_number") else "") for item in client["memory_modules"]]
software = client.get("software") or []
if software:
lines += ["", f"### Installierte Software ({len(software)})", "", "| Programm | Version | Hersteller |",
"|---|---|---|"]
lines += [f"| {_cell(item['name'])} | {_cell(item['version'])} | {_cell(item['publisher'])} |"
for item in software]
return "\n".join(lines)
def _cell(text):
return str(text or "").replace("|", "/").replace("\n", " ").strip()
def merge_report(comments, report):
"""Replace the managed report block in ``comments`` and keep everything written by hand."""
comments = comments or ""
block = f"{REPORT_START}\n{report}\n{REPORT_END}"
if REPORT_START in comments and REPORT_END in comments:
before, rest = comments.split(REPORT_START, 1)
after = rest.split(REPORT_END, 1)[1]
return f"{before}{block}{after}"
return f"{comments.rstrip()}\n\n{block}" if comments.strip() else block
def _without_timestamp(text):
"""The scan time changes every scan – it alone is no reason to update the report."""
return re.sub(r"^- \*\*Erfasst:\*\*.*$", "", text or "", flags=re.MULTILINE)
def _report_body(comments):
if REPORT_START in (comments or "") and REPORT_END in comments:
return comments.split(REPORT_START, 1)[1].split(REPORT_END, 1)[0].strip()
return None
_UNKNOWN = object()
def _noop(*_args, **_kwargs):
pass
@@ -66,6 +135,7 @@ class ClientSyncEngine:
self._device_types = {}
self._platforms = {}
self._planned = set()
self._asset_endpoint = _UNKNOWN
# ------------------------------------------------------------------
# Lookups
@@ -156,7 +226,71 @@ class ClientSyncEngine:
@staticmethod
def new_report():
return {"devices_created": 0, "devices_updated": 0, "devices_unchanged": 0, "objects_created": 0,
"interfaces_created": 0, "ips_created": 0, "changes": [], "errors": [], "items": []}
"interfaces_created": 0, "ips_created": 0, "assets_created": 0, "assets_updated": 0,
"changes": [], "errors": [], "items": []}
# ------------------------------------------------------------------
# netbox-inventory plugin (asset management)
# ------------------------------------------------------------------
def asset_endpoint(self):
"""``plugins/inventory/assets`` when the netbox-inventory plugin is installed, else ``None``."""
if self._asset_endpoint is _UNKNOWN:
try:
endpoint = self.nb.plugins.inventory.assets
list(endpoint.filter(serial="netbox-sync-probe"))
self._asset_endpoint = endpoint
except Exception as error: # noqa: BLE001 - plugin missing (404), no permission or no plugins API
self._asset_endpoint = None
if hasattr(self.nb, "plugins"):
self.log(f"netbox-inventory nicht verfügbar – Assets werden übersprungen ({error})", "info")
return self._asset_endpoint
def _sync_asset(self, client, device, type_id, dry_run, report):
"""Create or update the inventory asset of a client (found by serial number)."""
endpoint = self.asset_endpoint()
serial = clean_serial(client.get("serial"))
if endpoint is None or not serial:
return []
assets = list(endpoint.filter(serial=serial))
if len(assets) > 1:
return [f"Asset übersprungen – {len(assets)} Assets mit der Seriennummer {serial}"]
report_text = inventory_report(client)
description = f"Windows-Client; UUID {client['uuid']}" if client.get("uuid") else "Windows-Client"
if not assets:
report["assets_created"] += 1
if not dry_run:
payload = {"name": client["name"], "serial": serial, "status": "used", "device_type": type_id,
"description": description}
if device is not None:
payload["device"] = device.id
if report_text:
payload["comments"] = merge_report("", report_text)
endpoint.create(payload)
return ["Asset im Inventory-Plugin anlegen"]
asset = assets[0]
updates = {}
if (getattr(asset, "name", "") or "") != client["name"]:
updates["name"] = client["name"]
if str(getattr(getattr(asset, "status", None), "value", getattr(asset, "status", "")) or "") != "used":
updates["status"] = "used"
if type_id is not None and related_id(asset, "device_type") != type_id:
updates["device_type"] = type_id
if device is not None and related_id(asset, "device") != device.id:
updates["device"] = device.id
if client.get("uuid") and (getattr(asset, "description", "") or "") != description:
updates["description"] = description
current = getattr(asset, "comments", "") or ""
if report_text and _without_timestamp(_report_body(current)) != _without_timestamp(report_text):
updates["comments"] = merge_report(current, report_text)
if not updates:
return []
report["assets_updated"] += 1
if not dry_run:
asset.update(updates)
labels = {"name": "Name", "status": "Status", "device_type": "Gerätetyp", "device": "Gerät",
"description": "UUID", "comments": "Inventarbericht"}
return ["Asset aktualisieren: " + ", ".join(labels[key] for key in updates)]
def sync(self, clients, site_id, role_id, tenant_id=None, interfaces=True, update_existing=True, dry_run=True,
progress=_noop, cancelled=lambda: False):
@@ -191,8 +325,11 @@ class ClientSyncEngine:
if device is None:
changes.append(f"Gerät anlegen · {manufacturer} {model}" + (f" · {platform}" if platform else "")
+ (f" · S/N {serial}" if serial else ""))
if client.get("source") == "agent":
changes.append(f"Inventarbericht in den Kommentaren ({len(client.get('software') or [])} Programme)")
report["devices_created"] += 1
if dry_run:
changes.extend(self._sync_asset(client, None, type_id, dry_run, report))
if interfaces:
for interface in client.get("interfaces", []):
changes.append(f"Schnittstelle {interface['name']} anlegen"
@@ -207,6 +344,9 @@ class ClientSyncEngine:
payload["serial"] = serial
if tenant_id:
payload["tenant"] = tenant_id
report_text = inventory_report(client)
if report_text:
payload["comments"] = merge_report("", report_text)
device = self.nb.dcim.devices.create(payload)
self.existing[name.casefold()] = device.id
elif not update_existing:
@@ -226,12 +366,22 @@ class ClientSyncEngine:
if tenant_id and related_id(device, "tenant") is None:
updates["tenant"] = tenant_id
changes.append("Mandant setzen")
report_text = inventory_report(client)
current = getattr(device, "comments", "") or ""
if report_text and _without_timestamp(_report_body(current)) != _without_timestamp(report_text):
updates["comments"] = merge_report(current, report_text)
changes.append(f"Inventarbericht aktualisieren ({len(client.get('software') or [])} Programme)")
if updates:
report["devices_updated"] += 1
if not dry_run:
device.update(updates)
if interfaces:
changes.extend(self._sync_interfaces(device, client, tenant_id, dry_run, report))
try:
changes.extend(self._sync_asset(client, device, type_id, dry_run, report))
except Exception as error: # noqa: BLE001 - the device itself is fine; report the asset problem
report["errors"].append(f"{name}: Asset – {error}")
changes.append(f"Asset fehlgeschlagen: {error}")
if not changes:
report["devices_unchanged"] += 1
return changes
+24 -6
View File
@@ -21,7 +21,7 @@ WINRM_HTTPS_PORT = 5986
MAX_RANGE = 4096
DEFAULT_CLIENT_OPTIONS = {
"mode": "ad", # ad | hosts
"mode": "ad", # ad | hosts | agent
"ad_server": "", # domain or domain controller, empty = own domain
"ad_base": "", # search base (OU DN), empty = whole domain
"include_servers": False,
@@ -31,6 +31,10 @@ DEFAULT_CLIENT_OPTIONS = {
"use_current_user": False,
"username": "", # remembered for the logon prompt, never the password
"use_ssl": False,
# NetBox Windows Agent in listen mode (the key itself is a profile secret).
"agent_targets": "",
"agent_port": 8731,
"agent_networks": "", # allowed_networks written into the agent configuration
# Last choices in the NetBox transfer dialog.
"netbox_site": None,
"netbox_role": "Client",
@@ -269,6 +273,17 @@ def apply_scan(row, raw, now=None):
"os_architecture": raw.get("os_architecture", ""),
"installed": raw.get("installed", ""),
"last_boot": raw.get("last_boot", ""),
"source": raw.get("source", "winrm"),
"uuid": raw.get("uuid", ""),
"agent_version": raw.get("agent_version", ""),
"software_count": len(raw.get("software") or []),
"software": [{"name": item.get("name", ""), "version": item.get("version", ""),
"publisher": item.get("publisher", "")} for item in raw.get("software") or []],
"disks": [{"model": disk.get("model", ""), "size": int(disk.get("size") or 0),
"serial": disk.get("serial", "")} for disk in raw.get("disks") or []],
"memory_modules": [{"bank": item.get("bank", ""), "manufacturer": item.get("manufacturer", ""),
"part_number": item.get("part_number", ""), "capacity": int(item.get("capacity") or 0)}
for item in raw.get("memory_modules") or []],
# Only real adapters: VPN/TAP drivers report no MAC or are not physical.
"interfaces": [_interface(nic) for nic in raw.get("nics") or [] if nic.get("physical") and nic.get("mac")],
})
@@ -358,11 +373,14 @@ def friendly_error(text):
# --------------------------------------------------------------------------
def scan_clients(rows, credential=None, use_ssl=False, parallel=8, timeout=30, log=lambda *_args: None,
on_result=lambda _row: None, cancelled=lambda: False, query=None):
"""Query every row's host. ``on_result`` is called for each finished row (any thread)."""
on_result=lambda _row: None, cancelled=lambda: False, query=None, port=None, service="WinRM"):
"""Query every row's host. ``on_result`` is called for each finished row (any thread).
``query``/``port``/``service`` replace the WinRM query, e.g. by the NetBox Windows Agent.
"""
if sys.platform != "win32" and query is None:
raise ClientScanError("Die Abfrage von Windows-Clients ist nur unter Windows verfügbar.")
port = WINRM_HTTPS_PORT if use_ssl else WINRM_HTTP_PORT
port = port or (WINRM_HTTPS_PORT if use_ssl else WINRM_HTTP_PORT)
results = []
def scan(row):
@@ -374,7 +392,7 @@ def scan_clients(rows, credential=None, use_ssl=False, parallel=8, timeout=30, l
scanned_at=time.time())
if not port_open(host, port):
return dict(row, status="offline", scanned_at=time.time(),
message=f"Nicht erreichbar – ausgeschaltet oder WinRM-Port {port} geschlossen.")
message=f"Nicht erreichbar – ausgeschaltet oder {service}-Port {port} geschlossen.")
if cancelled():
return None
if query is not None:
@@ -386,7 +404,7 @@ def scan_clients(rows, credential=None, use_ssl=False, parallel=8, timeout=30, l
raw = wsman.query_client(host, credential, use_ssl, port, timeout)
return apply_scan(row, raw)
log(f"Frage {len(rows)} Client(s) über WinRM (Port {port}) ab …")
log(f"Frage {len(rows)} Client(s) über {service} (Port {port}) ab …")
with ThreadPoolExecutor(max_workers=max(1, min(parallel, len(rows) or 1))) as pool:
futures = [pool.submit(scan, row) for row in rows]
for future in as_completed(futures):
+41 -1
View File
@@ -11,7 +11,7 @@ from pathlib import Path
from netbox_sync import CONFIG_DIR_NAME
from netbox_sync.core.clients import DEFAULT_CLIENT_OPTIONS
SECRET_KEYS = ("password", "token_secret")
SECRET_KEYS = ("password", "token_secret", "community", "auth_password", "priv_password")
CONFIG_VERSION = 5
DEFAULT_SETTINGS = {
@@ -21,6 +21,10 @@ DEFAULT_SETTINGS = {
"create_cables": True,
"offline_mode": False, # collect and export to JSON without NetBox
"parallel_wmi": 8, # concurrent WinRM sessions for client scans
"auto_update_check": True, # look for a newer Gitea release on start
"skipped_version": "", # release the user chose to skip
"scanner_targets": "", # last IP ranges of the network scanner
"scanner_ports": "", # empty = default port list
}
log = logging.getLogger(__name__)
@@ -111,11 +115,24 @@ def empty_profile(name):
"netbox_url": "",
"netbox_token": "",
"netbox_ignore_ssl": False,
# Shared key of the NetBox Windows Agents of this customer (listen mode).
"agent_key": "",
"sources": [],
"switches": [],
# Remembered assignment "<source id>:<hypervisor cluster>" -> NetBox cluster name.
"cluster_map": {},
"host_map": {},
# Switch VLAN decisions for all switches: "<vid>" -> {"action": "map"|"new"|"skip"|"ignore", ...}.
"vlan_map": {},
# Switch network decisions: "<network>" -> {"vrf_id", "vrf_name" (new VRF), "create": prefix}.
"network_map": {},
# 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": {},
# SNMP printer scan: targets, role, site choices and remembered credential per address.
"printers": {},
# SNMP credentials (v2c communities and v3 users) – secrets encrypted.
"snmp_credentials": [],
# Windows client scan: targets and options, never a password.
"clients": dict(DEFAULT_CLIENT_OPTIONS),
}
@@ -161,16 +178,33 @@ class ProfileStore:
profile.update({
"netbox_url": record.get("netbox_url", ""),
"netbox_token": self._decrypt(record.get("netbox_token_encrypted", ""), f"{name}: NetBox-Token"),
"agent_key": self._decrypt(record.get("agent_key_encrypted", ""), f"{name}: Agent-Schlüssel")
if record.get("agent_key_encrypted") else "",
"netbox_ignore_ssl": bool(record.get("netbox_ignore_ssl", record.get("ignore_ssl_errors", False))),
"cluster_map": dict(record.get("cluster_map", {})),
"host_map": dict(record.get("host_map", {})),
"vlan_map": dict(record.get("vlan_map", {})),
"network_map": dict(record.get("network_map", {})),
"access_points": dict(record.get("access_points", {})),
"printers": dict(record.get("printers", {})),
"clients": {**DEFAULT_CLIENT_OPTIONS, **{key: value for key, value in record.get("clients", {}).items()
if key in DEFAULT_CLIENT_OPTIONS}},
})
for source in record.get("sources", []):
profile["sources"].append(self._decrypt_record(source, f"{name}: {source.get('name', 'Quelle')}"))
for credential in record.get("snmp_credentials", []):
profile["snmp_credentials"].append(self._decrypt_record(credential, f"{name}: SNMP"))
for switch in record.get("switches", []):
profile["switches"].append(self._decrypt_record(switch, f"{name}: {switch.get('name', 'Switch')}"))
# Migration from 4.5/4.6: VLAN and network decisions were stored per switch.
for switch in profile["switches"]:
for vid, choice in (switch.pop("vlan_map", None) or {}).items():
profile["vlan_map"].setdefault(vid, choice)
switch.pop("create_vlans", None)
approved = switch.pop("create_prefixes", None) or []
for network, vrf_name in (switch.pop("network_vrfs", None) or {}).items():
profile["network_map"].setdefault(network, {"vrf_id": None, "vrf_name": vrf_name or "",
"create": network in approved})
# Migration from v2: one VMware source embedded in each profile.
if not profile["sources"] and record.get("esxi_host"):
@@ -223,11 +257,17 @@ class ProfileStore:
"name": name,
"netbox_url": profile.get("netbox_url", ""),
"netbox_token_encrypted": protect(profile.get("netbox_token", "")),
"agent_key_encrypted": protect(profile.get("agent_key", "")) if profile.get("agent_key") else "",
"netbox_ignore_ssl": bool(profile.get("netbox_ignore_ssl", False)),
"sources": [self._encrypt_record(source) for source in profile.get("sources", [])],
"switches": [self._encrypt_record(switch) for switch in profile.get("switches", [])],
"cluster_map": dict(profile.get("cluster_map", {})),
"host_map": dict(profile.get("host_map", {})),
"vlan_map": dict(profile.get("vlan_map", {})),
"network_map": dict(profile.get("network_map", {})),
"access_points": dict(profile.get("access_points", {})),
"printers": dict(profile.get("printers", {})),
"snmp_credentials": [self._encrypt_record(item) for item in profile.get("snmp_credentials", [])],
"clients": dict(profile.get("clients", DEFAULT_CLIENT_OPTIONS)),
})
+326
View File
@@ -0,0 +1,326 @@
"""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,
MAC_PATTERN,
_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):
# Only spaces/tabs around the colon: an empty value must not swallow the next line. Lines after a
# paging prompt are indented, hence the optional leading blanks.
match = re.search(rf"(?im)^[ \t]*{re.escape(label)}[ \t]*:[ \t]*(.*?)[ \t]*$", 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, directly followed by its (possibly empty) 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:
text = line.strip()
if text and not set(text) <= {"-"} and not CLI_PROMPT.search(text):
ports[current]["description"] = text
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
chassis = _field(block, "Chassis ID")
name = _field(block, "System Name")
if not name and chassis and not MAC_PATTERN.fullmatch(chassis) and not re.fullmatch(r"[\d.]+", chassis):
name = chassis # e.g. Windows hosts send their name only as chassis ID
neighbors.append({
"local_port": port.group(1) if port else local,
"system_name": 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": chassis,
"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
+329
View File
@@ -0,0 +1,329 @@
"""Network scanner: find hosts in IP ranges and compare them with NetBox (read only).
Reachability uses the Windows ICMP API (no administrator rights, no ping.exe),
ARP for the local subnet and TCP ports, so hosts that block ICMP are found as
well. Names come from reverse DNS and NetBIOS. Nothing is written to NetBox.
"""
import ctypes
import ipaddress
import re
import socket
import struct
import sys
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from netbox_sync.core.netbox import related_id
SERVICES = {
21: "FTP", 22: "SSH", 23: "Telnet", 25: "SMTP", 53: "DNS", 80: "HTTP", 110: "POP3", 135: "RPC",
139: "NetBIOS", 143: "IMAP", 161: "SNMP", 389: "LDAP", 443: "HTTPS", 445: "SMB", 515: "LPD", 631: "IPP",
636: "LDAPS", 993: "IMAPS", 1433: "MSSQL", 3306: "MySQL", 3389: "RDP", 5432: "PostgreSQL", 5900: "VNC",
5985: "WinRM", 5986: "WinRM-HTTPS", 8006: "Proxmox", 8080: "HTTP-Alt", 8443: "HTTPS-Alt", 9100: "Druck",
}
DEFAULT_PORTS = "21-23,25,53,80,135,139,443,445,3389,5900,5985,8006,8080,8443,9100"
# Probed on hosts that do not answer ping, to find hosts behind a firewall.
QUICK_PORTS = (445, 3389, 80, 443, 22)
MAX_HOSTS = 4096
class ScanError(ValueError):
pass
def parse_ports(text):
"""``"21-23,80, 443"`` → sorted unique port numbers."""
ports = set()
for part in re.split(r"[\s,;]+", (text or "").strip()):
if not part:
continue
match = re.fullmatch(r"(\d+)(?:-(\d+))?", part)
if not match:
raise ScanError(f"Ungültige Port-Angabe: {part}")
start, end = int(match.group(1)), int(match.group(2) or match.group(1))
if not 1 <= start <= end <= 65535:
raise ScanError(f"Ungültiger Port-Bereich: {part}")
ports.update(range(start, end + 1))
if len(ports) > 1024:
raise ScanError("Bitte höchstens 1024 Ports angeben.")
return sorted(ports)
def expand_ips(text):
"""IPv4 addresses from ranges, networks and names (names are resolved)."""
from netbox_sync.core.clients import ClientScanError, expand_targets
try:
targets = expand_targets(text)
except ClientScanError as error:
raise ScanError(str(error)) from error
result = []
for target in targets:
try:
address = ipaddress.ip_address(target)
except ValueError:
try:
address = ipaddress.ip_address(socket.gethostbyname(target))
except (OSError, ValueError) as error:
raise ScanError(f"Name nicht auflösbar: {target}") from error
if address.version != 4:
raise ScanError(f"Nur IPv4 wird gescannt: {target}")
if str(address) not in result:
result.append(str(address))
if not result:
raise ScanError("Bitte IP-Adressen, Bereiche (192.0.2.1-254) oder Netze (192.0.2.0/24) angeben.")
if len(result) > MAX_HOSTS:
raise ScanError(f"Zu viele Adressen ({len(result)}) – höchstens {MAX_HOSTS} pro Scan.")
return result
def local_networks():
"""IPv4 /24 networks of this computer (for the "own network" button)."""
addresses = set()
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as probe:
probe.connect(("192.0.2.1", 9)) # no packet is sent for UDP connect
addresses.add(probe.getsockname()[0])
except OSError:
pass
try:
addresses.update(info[4][0] for info in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET))
except OSError:
pass
networks = []
for address in sorted(addresses):
ip = ipaddress.ip_address(address)
if not (ip.is_loopback or ip.is_link_local):
network = str(ipaddress.ip_network(f"{address}/24", strict=False))
if network not in networks:
networks.append(network)
return networks
# --------------------------------------------------------------------------
# Probes
# --------------------------------------------------------------------------
def _inet_addr(ip):
return struct.unpack("<I", socket.inet_aton(ip))[0]
if sys.platform == "win32":
class _IpOptions(ctypes.Structure):
_fields_ = [("Ttl", ctypes.c_ubyte), ("Tos", ctypes.c_ubyte), ("Flags", ctypes.c_ubyte),
("OptionsSize", ctypes.c_ubyte), ("OptionsData", ctypes.c_void_p)]
class _EchoReply(ctypes.Structure):
_fields_ = [("Address", ctypes.c_ulong), ("Status", ctypes.c_ulong), ("RoundTripTime", ctypes.c_ulong),
("DataSize", ctypes.c_ushort), ("Reserved", ctypes.c_ushort), ("Data", ctypes.c_void_p),
("Options", _IpOptions)]
_iphlpapi = ctypes.windll.iphlpapi
_iphlpapi.IcmpCreateFile.restype = ctypes.c_void_p
_iphlpapi.IcmpCloseHandle.argtypes = [ctypes.c_void_p]
_iphlpapi.IcmpSendEcho.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p, ctypes.c_ushort,
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong]
_iphlpapi.SendARP.argtypes = [ctypes.c_ulong, ctypes.c_ulong, ctypes.c_void_p, ctypes.POINTER(ctypes.c_ulong)]
def ping(ip, timeout_ms=800):
"""Round-trip time in ms, or ``None`` without answer."""
if sys.platform != "win32":
return None
handle = _iphlpapi.IcmpCreateFile()
if not handle or handle == ctypes.c_void_p(-1).value:
return None
try:
payload = b"netbox-sync-scan"
buffer = ctypes.create_string_buffer(ctypes.sizeof(_EchoReply) + len(payload) + 8)
count = _iphlpapi.IcmpSendEcho(handle, _inet_addr(ip), payload, len(payload), None, buffer,
ctypes.sizeof(buffer), timeout_ms)
if count:
reply = _EchoReply.from_buffer(buffer)
if reply.Status == 0:
return int(reply.RoundTripTime)
return None
finally:
_iphlpapi.IcmpCloseHandle(handle)
def arp_mac(ip):
"""MAC address via ARP – only for hosts in a directly connected subnet."""
if sys.platform != "win32":
return None
mac = (ctypes.c_ubyte * 8)()
length = ctypes.c_ulong(8)
if _iphlpapi.SendARP(_inet_addr(ip), 0, mac, ctypes.byref(length)) != 0 or length.value < 6:
return None
value = ":".join(f"{byte:02X}" for byte in mac[:6])
return None if value == "00:00:00:00:00:00" else value
def reverse_dns(ip):
try:
return socket.gethostbyaddr(ip)[0]
except (OSError, UnicodeError):
return ""
_NBSTAT_QUERY = (b"\x13\x37\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00"
b"\x20CKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\x00\x00\x21\x00\x01")
def parse_nbstat(data):
"""``(computer name, workgroup, MAC)`` from a NetBIOS node status answer."""
if len(data) < 57:
return "", "", None
count = data[56]
offset = 57
name = group = ""
for _index in range(count):
entry = data[offset:offset + 18]
if len(entry) < 18:
break
text = entry[:15].decode("latin-1").strip()
suffix, flags = entry[15], struct.unpack(">H", entry[16:18])[0]
if suffix == 0x00 and not flags & 0x8000 and not name:
name = text
elif suffix == 0x00 and flags & 0x8000 and not group:
group = text
offset += 18
mac_bytes = data[offset:offset + 6]
mac = ":".join(f"{byte:02X}" for byte in mac_bytes) if len(mac_bytes) == 6 and any(mac_bytes) else None
return name, group, mac
def netbios(ip, timeout=0.8):
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.settimeout(timeout)
sock.sendto(_NBSTAT_QUERY, (ip, 137))
data, _address = sock.recvfrom(2048)
except OSError:
return "", "", None
return parse_nbstat(data)
def tcp_open(ip, port, timeout=0.6):
try:
with socket.create_connection((ip, port), timeout=timeout):
return True
except OSError:
return False
def scan_host(ip, ports, timeout=0.6):
"""Probe one address. ``alive`` is false when nothing answered."""
started = time.monotonic()
rtt = ping(ip, int(timeout * 1000) + 200)
mac = arp_mac(ip)
open_ports = []
alive = rtt is not None or mac is not None
if not alive:
# Windows hosts often block ping; a few typical ports reveal them anyway.
for port in QUICK_PORTS:
if tcp_open(ip, port, timeout):
open_ports.append(port)
alive = True
break
if not alive:
return {"ip": ip, "alive": False}
with ThreadPoolExecutor(max_workers=min(16, max(1, len(ports)))) as pool:
results = pool.map(lambda port: (port, tcp_open(ip, port, timeout)), [p for p in ports if p not in open_ports])
open_ports += [port for port, is_open in results if is_open]
name, workgroup, nb_mac = netbios(ip)
return {
"ip": ip, "alive": True, "rtt": rtt, "mac": mac or nb_mac, "dns_name": reverse_dns(ip),
"netbios_name": name, "workgroup": workgroup,
"ports": [{"port": port, "service": SERVICES.get(port, "")} for port in sorted(open_ports)],
"duration": round(time.monotonic() - started, 2),
}
def scan(ips, ports, on_result, cancelled=lambda: False, workers=64, timeout=0.6):
"""Scan ``ips`` in parallel; ``on_result`` gets every host as soon as it is done."""
with ThreadPoolExecutor(max_workers=min(workers, len(ips))) as pool:
futures = {pool.submit(scan_host, ip, ports, timeout): ip for ip in ips}
for future in as_completed(futures):
if cancelled():
for pending in futures:
pending.cancel()
break
try:
on_result(future.result())
except Exception as error: # noqa: BLE001 - one host must not stop the scan
on_result({"ip": futures[future], "alive": False, "error": str(error)})
# --------------------------------------------------------------------------
# NetBox comparison (read only)
# --------------------------------------------------------------------------
def _assigned_name(record):
obj = getattr(record, "assigned_object", None)
if obj is None:
return "", ""
for attribute, kind in (("device", "Gerät"), ("virtual_machine", "VM")):
parent = getattr(obj, attribute, None)
if parent is not None:
return getattr(parent, "name", "") or "", kind
return getattr(obj, "name", "") or "", ""
def netbox_lookup(nb, ips):
"""``{ip: [entry, …]}`` for all NetBox IP addresses of the scanned hosts.
Queries one ``parent`` filter per /24 instead of one request per host.
"""
wanted = set(ips)
blocks = sorted({str(ipaddress.ip_network(f"{ip}/24", strict=False)) for ip in ips})
found = {}
for block in blocks:
for record in nb.ipam.ip_addresses.filter(parent=block):
host = str(record.address).split("/")[0]
if host not in wanted:
continue
name, kind = _assigned_name(record)
vrf = getattr(getattr(record, "vrf", None), "name", None)
status = getattr(record, "status", None)
found.setdefault(host, []).append({
"id": record.id,
"dns_name": getattr(record, "dns_name", "") or "",
"object": name, "object_kind": kind,
"vrf": vrf or "", "tenant_id": related_id(record, "tenant"),
"tenant": getattr(getattr(record, "tenant", None), "name", "") or "",
"status": getattr(status, "label", None) or getattr(status, "value", None) or str(status or ""),
"description": getattr(record, "description", "") or "",
"url": getattr(record, "display_url", None) or "",
})
return found
def _short(name):
return (name or "").split(".")[0].strip().casefold()
def compare(host, entries):
"""Comparison state of one scanned host with its NetBox entries."""
alive = host.get("alive")
if not entries:
return "missing" if alive else "unknown"
if not alive:
return "offline"
names = {_short(host.get("dns_name")), _short(host.get("netbios_name"))} - {""}
if not names:
return "match" # nothing to compare against – the address is documented
for entry in entries:
if names & ({_short(entry["dns_name"]), _short(entry["object"])} - {""}):
return "match"
return "differs"
COMPARE_TEXT = {
"match": "stimmt überein",
"differs": "Name abweichend",
"missing": "nicht in NetBox",
"offline": "in NetBox, nicht erreichbar",
"unknown": "",
"pending": "…",
}
+500
View File
@@ -0,0 +1,500 @@
"""Printers found by an SNMP network scan, documented in NetBox.
Every address is pinged (or probed on the printer ports 9100/515/631), then
queried via SNMP. The credentials of the profile are tried in order – SNMPv2c
communities and SNMPv3 users – and the one that works is remembered per
address. Printers are recognised by the Host Resources MIB (hrDeviceType
printer) or the Printer MIB (RFC 3805), so this works for every manufacturer.
Devices that only answer on printer ports are listed as "printer without SNMP".
The sync reuses the access point import: devices are matched by serial number,
MAC address, name and IP address. Page counter, supplies, colour capability and
the date of the scan are optionally stored in custom fields.
"""
import datetime
import ipaddress
import re
from concurrent.futures import ThreadPoolExecutor, as_completed
from netbox_sync.core import netscan, snmp
from netbox_sync.core.ap_sync import CHUNK, APSyncEngine
from netbox_sync.core.netbox import normalize_mac, related_id, version_tuple
PRINTER_PORTS = (9100, 631, 515)
SYS = "1.3.6.1.2.1.1"
SYS_DESCR, SYS_OBJECT_ID, SYS_UPTIME = f"{SYS}.1.0", f"{SYS}.2.0", f"{SYS}.3.0"
SYS_CONTACT, SYS_NAME, SYS_LOCATION = f"{SYS}.4.0", f"{SYS}.5.0", f"{SYS}.6.0"
HR_DEVICE_TYPE = "1.3.6.1.2.1.25.3.2.1.2"
HR_DEVICE_DESCR = "1.3.6.1.2.1.25.3.2.1.3"
HR_PRINTER = "1.3.6.1.2.1.25.3.1.5"
HR_PRINTER_STATUS = "1.3.6.1.2.1.25.3.5.1.1"
HR_PRINTER_ERRORS = "1.3.6.1.2.1.25.3.5.1.2"
PRT_SERIAL = "1.3.6.1.2.1.43.5.1.1.17"
PRT_PRINTER_NAME = "1.3.6.1.2.1.43.5.1.1.16"
HP_DEVICE_ID = "1.3.6.1.4.1.11.2.3.9.1.1.7.0" # IEEE 1284 device ID "MFG:HP;MDL:HP LaserJet …;"
GENERIC_DESCR = re.compile(r"ETHERNET MULTI-ENVIRONMENT|JETDIRECT|^\s*$", re.IGNORECASE)
PRT_INPUT = "1.3.6.1.2.1.43.8.2.1"
PRT_LIFE_COUNT = "1.3.6.1.2.1.43.10.2.1.4"
PRT_SUPPLIES = "1.3.6.1.2.1.43.11.1.1"
PRT_COLORANT = "1.3.6.1.2.1.43.12.1.1.4"
PRT_DISPLAY = "1.3.6.1.2.1.43.16.5.1.2"
PRT_ALERT_DESCR = "1.3.6.1.2.1.43.18.1.1.8"
IF_TABLE = "1.3.6.1.2.1.2.2.1"
IP_ADDR_IFINDEX = "1.3.6.1.2.1.4.20.1.2"
IP_ADDR_MASK = "1.3.6.1.2.1.4.20.1.3"
ENT_SOFTWARE_REV = "1.3.6.1.2.1.47.1.1.1.1.10"
ENT_FIRMWARE_REV = "1.3.6.1.2.1.47.1.1.1.1.9"
# IANA enterprise numbers of printer manufacturers (from sysObjectID).
ENTERPRISES = {
11: "HP", 1347: "Kyocera", 2435: "Brother", 367: "Ricoh", 1602: "Canon", 18334: "Konica Minolta",
641: "Lexmark", 253: "Xerox", 1248: "Epson", 2001: "OKI", 674: "Dell", 236: "Samsung", 297: "Fujifilm",
1129: "Toshiba", 2385: "Sharp", 26696: "HP", 2699: "Printer Working Group", 1552: "Utax", 3369: "Sharp",
10642: "Zebra", 683: "Zebra", 5530: "Develop", 4322: "Develop", 15315: "Muratec", 3793: "Panasonic",
}
MANUFACTURER_NAMES = (
"Hewlett-Packard", "HP", "Kyocera", "Brother", "Ricoh", "Canon", "Konica Minolta", "Lexmark", "Xerox", "Epson",
"OKI", "Dell", "Samsung", "Fujifilm", "Fuji Xerox", "Toshiba", "Sharp", "Utax", "TA Triumph-Adler", "Develop",
"Zebra", "Muratec", "Panasonic", "Olivetti", "Kyocera Mita", "Konica", "Minolta", "Nashuatec", "Gestetner",
)
PRINTER_STATUS = {1: "sonstiges", 2: "unbekannt", 3: "bereit", 4: "druckt", 5: "wärmt auf"}
ERROR_BITS = ("wenig Papier", "kein Papier", "wenig Toner", "kein Toner", "Klappe offen", "Papierstau", "offline",
"Service angefordert", "Papierfach fehlt", "Ausgabefach fehlt", "Verbrauchsmaterial fehlt",
"Ausgabefach fast voll", "Ausgabefach voll", "Papierfach leer", "Wartung überfällig")
SUPPLY_TYPES = {3: "Toner", 4: "Resttoner", 5: "Tinte", 6: "Tintenpatrone", 7: "Tintenbehälter", 9: "Trommel",
10: "Entwickler", 15: "Fixiereinheit", 20: "Transfereinheit", 21: "Tonerkassette",
22: "Fixieröl", 32: "Heftklammern"}
CUSTOM_FIELDS = (
("printer_page_count", "Seitenzähler", "integer"),
("printer_supplies", "Verbrauchsmaterial", "longtext"),
("printer_color", "Farbdrucker", "boolean"),
("printer_last_scan", "Letzter Drucker-Scan", "date"),
)
ROLE_HINTS = ("drucker", "printer", "multifunktion", "mfp", "mfd", "multifunction")
class PrinterError(ValueError):
pass
# ----------------------------------------------------------------------
# Reading a printer
# ----------------------------------------------------------------------
def _first(values):
return next((value for _key, value in sorted(values.items(), key=lambda item: snmp.oid_key(item[0]))
if snmp.text(value)), None)
def manufacturer_from(object_id, *texts):
for text in texts:
for name in MANUFACTURER_NAMES:
if re.search(rf"\b{re.escape(name)}\b", text or "", re.IGNORECASE):
return {"Hewlett-Packard": "HP", "Kyocera Mita": "Kyocera", "Fuji Xerox": "Fujifilm",
"Konica": "Konica Minolta", "Minolta": "Konica Minolta"}.get(name, name)
parts = snmp.oid_key(object_id) if object_id else ()
if parts[:6] == (1, 3, 6, 1, 4, 1) and len(parts) > 6:
return ENTERPRISES.get(parts[6], "")
return ""
def clean_model(text, manufacturer):
model = re.sub(r"\s+", " ", snmp.text(text)).strip(" ;,")
model = re.split(r";|,| - |\bFW\b|\bFirmware\b|\bS/N\b", model)[0].strip()
for prefix in (manufacturer, "Hewlett-Packard", "HP", "Kyocera Mita", "Konica Minolta", "KONICA MINOLTA"):
if prefix and model.casefold().startswith(prefix.casefold() + " "):
model = model[len(prefix) + 1:].strip()
return model[:100]
def mac_text(value):
if isinstance(value, bytes) and len(value) == 6 and any(value):
return normalize_mac(value.hex()) or ""
return normalize_mac(snmp.text(value)) or "" if value else ""
def error_flags(value):
if not isinstance(value, bytes):
return []
flags = []
for index, name in enumerate(ERROR_BITS):
byte, bit = divmod(index, 8)
if byte < len(value) and value[byte] & (0x80 >> bit):
flags.append(name)
return flags
def supplies_from(walked, colorants):
"""List of ``{"name", "type", "level", "max", "percent"}`` from prtMarkerSuppliesTable."""
supplies = []
for _index, row in sorted(snmp.table(walked, PRT_SUPPLIES).items()):
name = snmp.text(row.get(6))
kind = SUPPLY_TYPES.get(row.get(5), "")
level, maximum = row.get(9), row.get(8)
if not name and not kind:
continue
colour = colorants.get(row.get(3)) if row.get(3) else ""
percent = None
if isinstance(level, int) and isinstance(maximum, int) and level >= 0 and maximum > 0:
percent = max(0, min(100, round(level * 100 / maximum)))
state = {-3: "vorhanden", -2: "unbekannt", -1: "sonstiges"}.get(level, "") if isinstance(level, int) else ""
if isinstance(level, int) and level >= 0 and maximum in (-1, -2, None):
state = f"{level}"
supplies.append({"name": name or " ".join(filter(None, (kind, colour))), "type": kind, "colour": colour,
"level": level, "max": maximum, "percent": percent, "state": state})
return supplies
def supplies_text(supplies):
lines = []
for item in supplies:
value = f"{item['percent']} %" if item["percent"] is not None else (item["state"] or "–")
lines.append(f"{item['name']}: {value}")
return "\n".join(lines)
def trays_from(walked):
trays = []
for _index, row in sorted(snmp.table(walked, PRT_INPUT).items()):
name = snmp.text(row.get(13)) or snmp.text(row.get(18)) or f"Fach {len(trays) + 1}"
media = snmp.text(row.get(12))
capacity, current = row.get(9), row.get(10)
level = ""
if isinstance(current, int) and isinstance(capacity, int) and capacity > 0 and current >= 0:
level = f"{current}/{capacity} Blatt"
elif current == -3:
level = "Papier vorhanden"
elif current == 0:
level = "leer"
trays.append({"name": name, "media": media, "capacity": capacity if isinstance(capacity, int) else None,
"level": level})
return trays
def read_printer(client, ip):
"""Printer data via SNMP, or ``None`` when the device is no printer."""
base = client.get([SYS_DESCR, SYS_OBJECT_ID, SYS_NAME, SYS_LOCATION, SYS_CONTACT, SYS_UPTIME])
types = client.walk(HR_DEVICE_TYPE, limit=200)
printer_indexes = [snmp.oid_key(oid)[-1] for oid, value in types.items() if value == HR_PRINTER]
serials = client.walk(PRT_SERIAL, limit=20)
counters = client.walk(PRT_LIFE_COUNT, limit=20)
if not printer_indexes and not serials and not counters:
return None
descr = client.get([f"{HR_DEVICE_DESCR}.{index}" for index in printer_indexes]) if printer_indexes else {}
printer_name = snmp.text(_first(client.walk(PRT_PRINTER_NAME, limit=20)))
device_id = snmp.text(client.get([HP_DEVICE_ID]).get(HP_DEVICE_ID))
device_model = next((part.split(":", 1)[1].strip() for part in device_id.split(";")
if part.strip().upper().startswith(("MDL:", "MODEL:"))), "")
status = client.get([f"{oid}.{index}" for index in printer_indexes[:1]
for oid in (HR_PRINTER_STATUS, HR_PRINTER_ERRORS)]) if printer_indexes else {}
colorants_raw = client.walk(PRT_COLORANT, limit=50)
colorants = {snmp.oid_key(oid)[-1]: snmp.text(value) for oid, value in colorants_raw.items()}
supplies = supplies_from(client.walk(PRT_SUPPLIES, limit=600), colorants)
trays = trays_from(client.walk(PRT_INPUT, limit=600))
display = [snmp.text(value) for value in client.walk(PRT_DISPLAY, limit=20).values() if snmp.text(value)]
alerts = list(dict.fromkeys(snmp.text(value) for value in client.walk(PRT_ALERT_DESCR, limit=100).values()
if snmp.text(value)))
interfaces = snmp.table(client.walk(IF_TABLE, limit=800), IF_TABLE)
addressing = client.get([f"{IP_ADDR_IFINDEX}.{ip}", f"{IP_ADDR_MASK}.{ip}"])
firmware = snmp.text(_first(client.walk(ENT_SOFTWARE_REV, limit=50)) or _first(
client.walk(ENT_FIRMWARE_REV, limit=50)))
sys_descr = snmp.text(base.get(SYS_DESCR))
object_id = base.get(SYS_OBJECT_ID) or ""
candidates = [printer_name, snmp.text(next(iter(descr.values()), "")) if descr else "", device_model, sys_descr]
model_text = next((text for text in candidates if text and not GENERIC_DESCR.search(text)), "")
manufacturer = manufacturer_from(object_id, model_text, sys_descr)
model = clean_model(model_text, manufacturer)
if not firmware:
match = re.search(r"(?:firmware|fw|version|ver\.?)\s*[:=]?\s*([\w.\-]+)", sys_descr, re.IGNORECASE)
firmware = match.group(1) if match else ""
if_index = addressing.get(f"{IP_ADDR_IFINDEX}.{ip}")
mac = mac_text(interfaces.get((if_index,), {}).get(6)) if isinstance(if_index, int) else ""
if not mac:
for _index, row in sorted(interfaces.items()):
if row.get(3) in (6, 71, 117) and mac_text(row.get(6)):
mac = mac_text(row.get(6))
break
prefix_length = None
mask = addressing.get(f"{IP_ADDR_MASK}.{ip}")
if isinstance(mask, str):
try:
prefix_length = ipaddress.ip_network(f"0.0.0.0/{mask}").prefixlen
except ValueError:
prefix_length = None
colours = [name for name in colorants.values() if name]
colour = any(name.casefold() not in ("black", "schwarz", "unknown", "other") for name in colours) or any(
item["colour"] and item["colour"].casefold() not in ("black", "schwarz") for item in supplies)
page_count = max((value for value in counters.values() if isinstance(value, int)), default=None)
status_value = status.get(f"{HR_PRINTER_STATUS}.{printer_indexes[0]}") if printer_indexes else None
errors = error_flags(status.get(f"{HR_PRINTER_ERRORS}.{printer_indexes[0]}")) if printer_indexes else []
serial = snmp.text(_first(serials)).upper()
return {
"name": snmp.text(base.get(SYS_NAME)), "sys_descr": sys_descr, "object_id": object_id,
"manufacturer": manufacturer, "model": model, "serial": serial, "firmware": firmware,
"site_hint": snmp.text(base.get(SYS_LOCATION)), "contact": snmp.text(base.get(SYS_CONTACT)),
"uptime": base.get(SYS_UPTIME), "mac": mac, "prefix_length": prefix_length,
"page_count": page_count, "color": bool(colour), "supplies": supplies, "trays": trays,
"status": PRINTER_STATUS.get(status_value, ""), "errors": errors, "display": display, "alerts": alerts,
}
# ----------------------------------------------------------------------
# Scan
# ----------------------------------------------------------------------
def credential_label(record):
try:
return snmp.Credential(record).label
except snmp.SnmpError:
return "ungültig"
def _ordered(credentials, preferred_id):
if not preferred_id:
return list(credentials)
return sorted(credentials, key=lambda record: record.get("id") != preferred_id)
def scan_host(ip, credentials, preferred=None, timeout=1.0):
"""``{"ip", "alive", "printer": bool, ...}`` for one address."""
alive = netscan.ping(ip) is not None
ports = []
if not alive:
ports = [port for port in PRINTER_PORTS if netscan.tcp_open(ip, port, 0.6)]
if not ports:
return {"ip": ip, "alive": False, "printer": False}
result = {"ip": ip, "alive": True, "printer": False, "snmp": "", "credential_id": None, "notes": []}
try:
client, notes = snmp.connect(ip, _ordered(credentials, (preferred or {}).get(ip)), timeout=timeout)
result["notes"] += notes
info = read_printer(client, ip)
result["snmp"] = client.credential.label
result["credential_id"] = client.credential.record.get("id")
if info:
result.update(info, printer=True)
if not result["mac"]:
result["mac"] = netscan.arp_mac(ip) or ""
return result
except snmp.SnmpAuthError as error:
result["notes"].append(str(error))
except snmp.SnmpError as error:
if not isinstance(error, snmp.SnmpTimeout):
result["notes"].append(f"SNMP-Fehler: {error}")
except OSError as error:
result["notes"].append(f"SNMP-Fehler: {error}")
if result["snmp"]:
return result # answers SNMP but is no printer
if not ports:
ports = [port for port in PRINTER_PORTS if netscan.tcp_open(ip, port, 0.6)]
if 9100 in ports or (631 in ports and 515 in ports):
result.update(printer=True, name=netscan.reverse_dns(ip) or "", mac=netscan.arp_mac(ip) or "",
manufacturer="", model="", serial="", firmware="", site_hint="", supplies=[], trays=[],
page_count=None, color=None, errors=[], display=[], alerts=[], status="",
prefix_length=None)
result["notes"].append("Druckerports offen (" + ", ".join(map(str, ports)) + "), aber keine SNMP-Antwort"
" – Zugangsdaten prüfen")
return result
def scan(ips, credentials, on_result, cancelled=lambda: False, preferred=None, workers=48, timeout=1.0):
if not credentials:
raise PrinterError("Bitte mindestens eine SNMP-Community oder einen SNMPv3-Benutzer hinterlegen.")
for record in credentials:
snmp.Credential(record) # validates protocols early
with ThreadPoolExecutor(max_workers=workers) as pool:
futures = {pool.submit(scan_host, ip, credentials, preferred, 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": True, "printer": False, "notes": [str(error)]})
def to_import(host):
"""Scan result → record for the sync (same keys as an access point)."""
name = host.get("name") or netscan.reverse_dns(host["ip"]) or f"Drucker {host['ip']}"
issues = list(host.get("notes", []))
if host.get("errors"):
issues.append("Gerät meldet: " + ", ".join(host["errors"]))
defaults = {"manufacturer": "", "model": "", "firmware": "", "supplies": [], "trays": [], "page_count": None,
"color": None, "errors": [], "display": [], "alerts": [], "status": "", "prefix_length": None,
"snmp": ""}
return dict({**defaults, **host}, name=re.sub(r"\s+", " ", name).strip()[:64], serial=(host.get("serial") or "").upper(),
mac=normalize_mac(host.get("mac")) or "", issues=issues, site_hint=host.get("site_hint") or "")
def mark_duplicates(printers):
for key, text in (("serial", "Seriennummer"), ("mac", "MAC-Adresse")):
groups = {}
for printer in printers:
if printer.get(key):
groups.setdefault(printer[key], []).append(printer)
for value, members in groups.items():
if len(members) > 1:
for printer in members:
others = ", ".join(other["ip"] for other in members if other is not printer)
printer["issues"].append(f"{text} {value} doppelt (auch {others})")
def model_key(printer):
"""Key of the NetBox device type a new printer needs (``manufacturer|model``, case-insensitive)."""
return f"{printer.get('manufacturer') or 'Unbekannt'}|{printer.get('model') or 'Drucker'}".casefold()
def printer_key(printer):
return printer.get("serial") or printer.get("mac") or printer["ip"]
# ----------------------------------------------------------------------
# NetBox
# ----------------------------------------------------------------------
class PrinterSyncEngine(APSyncEngine):
"""Access point import with printer identity, IP matching and custom fields."""
def __init__(self, nb, log=None, role_id=None, counters=True):
super().__init__(nb, log)
self.role_id = role_id
self.counters = counters
self.today = datetime.date.today().isoformat()
self.device_types = []
self.type_map = {} # model_key -> device type ID chosen by the user
def load_context(self, tenant_id=None):
result = super().load_context(tenant_id)
self.device_types = sorted(({"id": item.id, "model": item.model,
"manufacturer": getattr(getattr(item, "manufacturer", None), "name", "") or ""}
for item in self.nb.dcim.device_types.all()),
key=lambda row: (row["manufacturer"].casefold(), row["model"].casefold()))
return result
def type_exists(self, printer):
"""Is the device type of ``printer`` already in NetBox (same manufacturer and model)?"""
manufacturer, model, _platform = self._identity(printer)
return any(row["model"].casefold() == model.casefold() and row["manufacturer"].casefold() in (
manufacturer.casefold(), "hewlett-packard" if manufacturer.casefold() == "hp" else "")
for row in self.device_types)
def suggest_type(self, printer):
"""Device type with a similar model name, or ``None``."""
model = re.sub(r"[^0-9a-z]", "", (printer.get("model") or "").casefold())
if len(model) < 4:
return None
matches = [row["id"] for row in self.device_types
if model in re.sub(r"[^0-9a-z]", "", row["model"].casefold())
or re.sub(r"[^0-9a-z]", "", row["model"].casefold()) in model]
return matches[0] if len(matches) == 1 else None
def _mapped_type(self, printer):
return self.type_map.get(model_key(printer))
def _known_devices(self, scope):
if not self.role_id:
return []
return list(self.nb.dcim.devices.filter(role_id=self.role_id, **scope))
def _identity(self, printer):
return printer.get("manufacturer") or "Unbekannt", printer.get("model") or "Drucker", None
def _custom_values(self, printer):
if not self.counters or not printer.get("snmp"):
return {}
values = {"printer_last_scan": self.today}
if printer.get("page_count") is not None:
values["printer_page_count"] = printer["page_count"]
if printer.get("supplies"):
values["printer_supplies"] = supplies_text(printer["supplies"])
if printer.get("color") is not None:
values["printer_color"] = bool(printer["color"])
return values
def _extra_payload(self, printer):
values = self._custom_values(printer)
return {"custom_fields": values} if values else {}
def _extra_updates(self, device, printer):
values = self._custom_values(printer)
current = dict(getattr(device, "custom_fields", None) or {})
changed = {key: value for key, value in values.items() if current.get(key) != value}
if not changed or set(changed) == {"printer_last_scan"} and len(values) > 1:
return {}, []
texts = []
if "printer_page_count" in changed:
texts.append(f"Seitenzähler {current.get('printer_page_count') or '–'} → {changed['printer_page_count']}")
if "printer_supplies" in changed:
texts.append("Verbrauchsmaterial")
if "printer_color" in changed:
texts.append("Farbdrucker" if changed["printer_color"] else "Schwarzweiß")
return {"custom_fields": dict(current, **values)}, texts or ["Scan-Datum"]
def match(self, printers):
"""Base matching plus the IP address assigned to a device interface."""
only_netbox = super().match(printers)
open_items = [printer for printer in printers if printer.get("device") is None and printer.get("ip")]
if not open_items:
return only_netbox
by_ip = {}
ips = sorted({printer["ip"] for printer in open_items})
for start in range(0, len(ips), CHUNK):
for record in self.nb.ipam.ip_addresses.filter(address=ips[start:start + CHUNK]):
if getattr(record, "assigned_object_type", None) != "dcim.interface":
continue
device_id = related_id(getattr(record, "assigned_object", None), "device")
if device_id:
by_ip.setdefault(str(record.address).split("/")[0], set()).add(device_id)
matched = set()
for printer in open_items:
devices = by_ip.get(printer["ip"], set())
if len(devices) == 1:
device = self.nb.dcim.devices.get(next(iter(devices)))
if device is not None:
printer["device"], printer["method"] = device, "IP-Adresse"
matched.add(device.id)
if related_id(device, "tenant") not in self.tenant_ids:
printer["issues"].append("NetBox-Gerät gehört " + (
f"Mandant „{getattr(device.tenant, 'name', '')}“ außerhalb der Mandantengruppe"
if related_id(device, "tenant") else "keinem Mandanten"))
return [device for device in only_netbox if device.id not in matched]
def ensure_custom_fields(self, dry_run, report):
"""Create the printer custom fields that are missing."""
if not self.counters:
return
existing = {field.name for field in self.nb.extras.custom_fields.filter(
name=[name for name, _label, _type in CUSTOM_FIELDS])}
key = "object_types" if version_tuple(self.nb) >= (4, 0) else "content_types"
for name, label, kind in CUSTOM_FIELDS:
if name in existing:
continue
report["changes"].append(f"Benutzerdefiniertes Feld {label} ({name}) anlegen")
report["objects_created"] += 1
if not dry_run:
self.nb.extras.custom_fields.create({
"name": name, "label": label, "type": kind, key: ["dcim.device"], "group_name": "Drucker",
"required": False, "description": "Aus dem SNMP-Drucker-Scan",
})
def sync(self, printers, placements, role_id, rename=True, dry_run=True, default_site=None):
report = self.new_report()
try:
self.ensure_custom_fields(dry_run, report)
except Exception as error: # noqa: BLE001 - devices can still be documented
report["errors"].append(f"Benutzerdefinierte Felder: {error}")
self.counters = False
result = super().sync(printers, placements, role_id, rename, dry_run, default_site)
for key, value in result.items():
if isinstance(value, list):
report[key] = report.get(key, []) + value
else:
report[key] = report.get(key, 0) + value
return report
+540
View File
@@ -0,0 +1,540 @@
"""Small SNMP client (v2c and v3 USM) for reading devices – no external SNMP library.
Supports GET and GETBULK walks. SNMPv3 handles engine discovery, time
synchronisation, authentication (MD5, SHA-1, SHA-224/256/384/512) and privacy
(DES, AES-128 and AES-192/256 with Blumenthal key extension) using the
``cryptography`` package that paramiko already brings along.
"""
import hashlib
import hmac
import itertools
import random
import socket
import struct
import time
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
try: # cryptography >= 43 moved TripleDES (used for single DES with K1=K2=K3)
from cryptography.hazmat.decrepit.ciphers.algorithms import TripleDES
except ImportError: # pragma: no cover - older cryptography
TripleDES = algorithms.TripleDES
PORT = 161
# ASN.1 / SNMP tags
INTEGER, OCTET_STRING, NULL, OID, SEQUENCE = 0x02, 0x04, 0x05, 0x06, 0x30
IP_ADDRESS, COUNTER32, GAUGE32, TIMETICKS, OPAQUE, COUNTER64 = 0x40, 0x41, 0x42, 0x43, 0x44, 0x46
NO_SUCH_OBJECT, NO_SUCH_INSTANCE, END_OF_MIB_VIEW = 0x80, 0x81, 0x82
GET, GET_NEXT, RESPONSE, GET_BULK, REPORT = 0xA0, 0xA1, 0xA2, 0xA5, 0xA8
AUTH_PROTOCOLS = { # name -> (hash, length of the truncated HMAC)
"MD5": (hashlib.md5, 12), "SHA": (hashlib.sha1, 12), "SHA-224": (hashlib.sha224, 16),
"SHA-256": (hashlib.sha256, 24), "SHA-384": (hashlib.sha384, 32), "SHA-512": (hashlib.sha512, 48),
}
PRIV_PROTOCOLS = {"DES": 8, "AES": 16, "AES-192": 24, "AES-256": 32} # name -> key length
REPORT_TEXT = {
"1.3.6.1.6.3.15.1.1.1.0": "Sicherheitsstufe wird nicht unterstützt",
"1.3.6.1.6.3.15.1.1.2.0": "nicht im Zeitfenster",
"1.3.6.1.6.3.15.1.1.3.0": "unbekannter Benutzer",
"1.3.6.1.6.3.15.1.1.4.0": "unbekannte Engine-ID",
"1.3.6.1.6.3.15.1.1.5.0": "falsches Authentifizierungs-Passwort oder -Protokoll",
"1.3.6.1.6.3.15.1.1.6.0": "Entschlüsselung fehlgeschlagen (Privacy-Passwort oder -Protokoll falsch)",
}
class SnmpError(Exception):
"""Base error."""
class SnmpTimeout(SnmpError):
"""No answer – host down, SNMP off or (for v2c) wrong community."""
class SnmpAuthError(SnmpError):
"""The agent answered but rejected the credentials (SNMPv3 report)."""
# ----------------------------------------------------------------------
# BER encoding
# ----------------------------------------------------------------------
def _length(size):
if size < 0x80:
return bytes([size])
raw = size.to_bytes((size.bit_length() + 7) // 8, "big")
return bytes([0x80 | len(raw)]) + raw
def tlv(tag, content):
return bytes([tag]) + _length(len(content)) + content
def enc_int(value, tag=INTEGER):
size = max(1, (value.bit_length() + 8) // 8)
return tlv(tag, value.to_bytes(size, "big", signed=True))
def enc_str(value):
return tlv(OCTET_STRING, value if isinstance(value, bytes) else str(value).encode())
def enc_oid(oid):
parts = [int(part) for part in str(oid).strip(".").split(".")]
body = bytearray([parts[0] * 40 + parts[1]])
for part in parts[2:]:
chunk = [part & 0x7F]
part >>= 7
while part:
chunk.append(0x80 | (part & 0x7F))
part >>= 7
body += bytes(reversed(chunk))
return tlv(OID, bytes(body))
def seq(*items):
return tlv(SEQUENCE, b"".join(items))
def decode(data, pos=0):
"""``(tag, content, next position)`` of the TLV at ``pos``."""
if pos + 2 > len(data):
raise SnmpError("Antwort unvollständig")
tag, size = data[pos], data[pos + 1]
pos += 2
if size & 0x80:
count = size & 0x7F
size = int.from_bytes(data[pos:pos + count], "big")
pos += count
if pos + size > len(data):
raise SnmpError("Antwort unvollständig")
return tag, data[pos:pos + size], pos + size
def children(content):
items, pos = [], 0
while pos < len(content):
tag, value, pos = decode(content, pos)
items.append((tag, value))
return items
def dec_oid(content):
first = content[0]
parts = [first // 40 if first < 80 else 2, first % 40 if first < 80 else first - 80]
value = 0
for byte in content[1:]:
value = (value << 7) | (byte & 0x7F)
if not byte & 0x80:
parts.append(value)
value = 0
return ".".join(map(str, parts))
def dec_value(tag, content):
if tag == INTEGER:
return int.from_bytes(content, "big", signed=True)
if tag in (COUNTER32, GAUGE32, TIMETICKS, COUNTER64):
return int.from_bytes(content, "big")
if tag == OID:
return dec_oid(content)
if tag == IP_ADDRESS:
return ".".join(str(byte) for byte in content)
if tag in (OCTET_STRING, OPAQUE):
return bytes(content)
return None # NULL, noSuchObject, noSuchInstance, endOfMibView
def oid_key(oid):
return tuple(int(part) for part in oid.strip(".").split("."))
def in_subtree(oid, root):
return oid_key(oid)[:len(oid_key(root))] == oid_key(root)
def text(value):
"""OCTET STRING as readable text (trailing NULs and control characters removed)."""
if value is None:
return ""
if isinstance(value, bytes):
for encoding in ("utf-8", "cp1252"):
try:
value = value.decode(encoding)
break
except UnicodeDecodeError:
continue
return "".join(char for char in str(value) if char.isprintable()).strip()
# ----------------------------------------------------------------------
# PDUs
# ----------------------------------------------------------------------
def _pdu(kind, request_id, oids, non_repeaters=0, max_repetitions=0):
varbinds = seq(*(seq(enc_oid(oid), tlv(NULL, b"")) for oid in oids))
return tlv(kind, enc_int(request_id) + enc_int(non_repeaters) + enc_int(max_repetitions) + varbinds)
def _parse_pdu(tag, content):
request_id, status, index, varbinds = children(content)
bindings = []
for _tag, binding in children(varbinds[1]):
(_oid_tag, oid_raw), (value_tag, value_raw) = children(binding)
bindings.append((dec_oid(oid_raw), value_tag, dec_value(value_tag, value_raw)))
return {"type": tag, "request_id": dec_value(INTEGER, request_id[1]), "error_status": dec_value(INTEGER, status[1]),
"error_index": dec_value(INTEGER, index[1]), "varbinds": bindings}
# ----------------------------------------------------------------------
# SNMPv3 keys and crypto
# ----------------------------------------------------------------------
_KEY_CACHE = {}
def aes_cfb(key, iv, data, decrypt=False):
"""AES-CFB128 (RFC 3826) built on ECB – the CFB mode of ``cryptography`` is being deprecated."""
encryptor = Cipher(algorithms.AES(key), modes.ECB()).encryptor()
out, register = bytearray(), iv
for start in range(0, len(data), 16):
block = data[start:start + 16]
stream = encryptor.update(register)
chunk = bytes(a ^ b for a, b in zip(block, stream))
out += chunk
register = (block if decrypt else chunk).ljust(16, b"\0")
return bytes(out)
def password_to_key(password, hash_func):
"""RFC 3414 A.2: hash of the password repeated to 1 MB."""
key = (password, hash_func().name)
if key not in _KEY_CACHE:
data = password.encode()
if not data:
raise SnmpError("leeres SNMPv3-Passwort")
digest = hash_func()
repeated = (data * (64 // len(data) + 2))
chunk = (repeated * (1048576 // len(repeated) + 1))[:1048576]
digest.update(chunk)
_KEY_CACHE[key] = digest.digest()
return _KEY_CACHE[key]
def localize(key, engine_id, hash_func):
return hash_func(key + engine_id + key).digest()
def priv_key(password, engine_id, hash_func, size):
key = localize(password_to_key(password, hash_func), engine_id, hash_func)
while len(key) < size: # Blumenthal key extension for AES-192/256
key += hash_func(key).digest()
return key[:size] if size > 8 else key[:16] # DES needs key + pre-IV
class Credential:
"""One set of credentials: ``{"version": "2c", "community": …}`` or a v3 user."""
def __init__(self, record):
self.record = record
self.version = str(record.get("version") or "2c")
self.community = record.get("community") or "public"
self.username = record.get("username") or ""
self.auth_protocol = record.get("auth_protocol") or ""
self.auth_password = record.get("auth_password") or ""
self.priv_protocol = record.get("priv_protocol") or ""
self.priv_password = record.get("priv_password") or ""
self.context = record.get("context") or ""
if self.version == "3":
if self.auth_protocol and self.auth_protocol not in AUTH_PROTOCOLS:
raise SnmpError(f"unbekanntes Authentifizierungs-Protokoll {self.auth_protocol}")
if self.priv_protocol and self.priv_protocol not in PRIV_PROTOCOLS:
raise SnmpError(f"unbekanntes Privacy-Protokoll {self.priv_protocol}")
if self.priv_protocol and not self.auth_protocol:
raise SnmpError("Privacy ohne Authentifizierung ist bei SNMPv3 nicht möglich")
@property
def label(self):
if self.version != "3":
return "SNMPv2c"
level = ("authPriv" if self.priv_protocol else "authNoPriv") if self.auth_protocol else "noAuthNoPriv"
return f"SNMPv3 {self.username} ({level})"
# ----------------------------------------------------------------------
# Client
# ----------------------------------------------------------------------
_ids = itertools.count(random.randint(1, 1 << 30))
class SnmpClient:
def __init__(self, host, credential, timeout=1.0, retries=1, port=PORT):
self.host, self.port = host, port
self.credential = credential if isinstance(credential, Credential) else Credential(credential)
self.timeout, self.retries = timeout, retries
self.engine_id = b""
self.boots = self.engine_time = 0
self._time_base = 0.0
self._salt = random.getrandbits(64)
self.bulk = True
# transport ----------------------------------------------------------
def _exchange(self, packet, accept):
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.settimeout(self.timeout)
for _attempt in range(self.retries + 1):
try:
sock.sendto(packet, (self.host, self.port))
except OSError as error:
raise SnmpTimeout(str(error)) from error
deadline = time.monotonic() + self.timeout
while True:
remaining = deadline - time.monotonic()
if remaining <= 0:
break
sock.settimeout(remaining)
try:
data, _addr = sock.recvfrom(65535)
except (socket.timeout, ConnectionResetError):
break
except OSError:
break
try:
result = accept(data)
except SnmpAuthError:
raise
except (SnmpError, ValueError, IndexError):
continue
if result is not None:
return result
raise SnmpTimeout(f"{self.host}: keine SNMP-Antwort")
# v2c ----------------------------------------------------------------
def _request_v2(self, pdu_type, oids, non_repeaters=0, max_repetitions=0):
request_id = next(_ids) & 0x7FFFFFFF
community = self.credential.community.encode()
packet = seq(enc_int(1), enc_str(community), _pdu(pdu_type, request_id, oids, non_repeaters, max_repetitions))
def accept(data):
_tag, content, _pos = decode(data)
version, community_raw, (pdu_tag, pdu_content) = children(content)
if community_raw[1] != community:
return None
pdu = _parse_pdu(pdu_tag, pdu_content)
return pdu if pdu["request_id"] == request_id else None
return self._exchange(packet, accept)
# v3 -----------------------------------------------------------------
def _hash(self):
return AUTH_PROTOCOLS[self.credential.auth_protocol][0] if self.credential.auth_protocol else None
def _discover(self):
msg_id = next(_ids) & 0x7FFFFFFF
usm = seq(enc_str(b""), enc_int(0), enc_int(0), enc_str(b""), enc_str(b""), enc_str(b""))
scoped = seq(enc_str(b""), enc_str(b""), _pdu(GET, msg_id, []))
packet = seq(enc_int(3), seq(enc_int(msg_id), enc_int(65507), enc_str(b"\x04"), enc_int(3)),
enc_str(usm), scoped)
message = self._exchange(packet, lambda data: self._parse_v3(data, msg_id, verify=False))
if not message["engine_id"]:
raise SnmpError(f"{self.host}: keine SNMPv3-Engine-ID erhalten")
self._set_engine(message)
def _set_engine(self, message):
self.engine_id = message["engine_id"]
self.boots, self.engine_time = message["boots"], message["time"]
self._time_base = time.monotonic()
hash_func = self._hash()
cred = self.credential
self._auth_key = localize(password_to_key(cred.auth_password, hash_func), self.engine_id, hash_func) \
if hash_func else None
self._priv_key = priv_key(cred.priv_password, self.engine_id, hash_func, PRIV_PROTOCOLS[cred.priv_protocol]) \
if cred.priv_protocol else None
def _now(self):
return self.engine_time + int(time.monotonic() - self._time_base)
def _encrypt(self, plain, now):
cred = self.credential
self._salt = (self._salt + 1) & 0xFFFFFFFFFFFFFFFF
if cred.priv_protocol == "DES":
salt = struct.pack(">II", self.boots & 0xFFFFFFFF, self._salt & 0xFFFFFFFF)
iv = bytes(a ^ b for a, b in zip(self._priv_key[8:16], salt))
plain += b"\x00" * (-len(plain) % 8)
encryptor = Cipher(TripleDES(self._priv_key[:8] * 3), modes.CBC(iv)).encryptor()
else:
salt = struct.pack(">Q", self._salt)
iv = struct.pack(">II", self.boots, now) + salt
return aes_cfb(self._priv_key, iv, plain), salt
return encryptor.update(plain) + encryptor.finalize(), salt
def _decrypt(self, data, salt, boots, engine_time):
if self.credential.priv_protocol == "DES":
iv = bytes(a ^ b for a, b in zip(self._priv_key[8:16], salt))
decryptor = Cipher(TripleDES(self._priv_key[:8] * 3), modes.CBC(iv)).decryptor()
else:
iv = struct.pack(">II", boots, engine_time) + salt
return aes_cfb(self._priv_key, iv, data, decrypt=True)
return decryptor.update(data) + decryptor.finalize()
def _parse_v3(self, data, msg_id, verify=True):
_tag, content, _pos = decode(data)
version, header, (_usm_tag, usm_raw), (data_tag, data_raw) = children(content)
if dec_value(INTEGER, version[1]) != 3:
raise SnmpError("keine SNMPv3-Antwort")
header_items = children(header[1])
if dec_value(INTEGER, header_items[0][1]) != msg_id:
return None
flags = header_items[2][1][0] if header_items[2][1] else 0
_t, usm_content, _p = decode(usm_raw)
engine_id, boots, engine_time, user, auth_params, priv_params = (item[1] for item in children(usm_content))
message = {"engine_id": bytes(engine_id), "boots": dec_value(INTEGER, boots),
"time": dec_value(INTEGER, engine_time)}
if verify and flags & 0x01 and self._auth_key:
hash_func, size = AUTH_PROTOCOLS[self.credential.auth_protocol]
position = data.find(auth_params)
zeroed = data[:position] + b"\x00" * len(auth_params) + data[position + len(auth_params):]
if hmac.new(self._auth_key, zeroed, hash_func).digest()[:size] != auth_params:
raise SnmpError("Antwort mit ungültiger Signatur")
if data_tag == OCTET_STRING:
if not self._priv_key:
raise SnmpError("verschlüsselte Antwort ohne Privacy-Schlüssel")
plain = self._decrypt(bytes(data_raw), bytes(priv_params), message["boots"], message["time"])
_t, scoped, _p = decode(plain)
else:
scoped = data_raw
_context_engine, _context_name, (pdu_tag, pdu_content) = children(scoped)
message["pdu"] = _parse_pdu(pdu_tag, pdu_content)
return message
def _request_v3(self, pdu_type, oids, non_repeaters=0, max_repetitions=0, resync=True):
if not self.engine_id:
self._discover()
cred = self.credential
msg_id = next(_ids) & 0x7FFFFFFF
pdu = _pdu(pdu_type, msg_id, oids, non_repeaters, max_repetitions)
scoped = seq(enc_str(self.engine_id), enc_str(cred.context), pdu)
flags = 0x04 | (0x01 if cred.auth_protocol else 0) | (0x02 if cred.priv_protocol else 0)
salt, now = b"", self._now()
if cred.priv_protocol:
encrypted, salt = self._encrypt(scoped, now)
body = enc_str(encrypted)
else:
body = scoped
auth_size = AUTH_PROTOCOLS[cred.auth_protocol][1] if cred.auth_protocol else 0
def build(auth_params):
usm = seq(enc_str(self.engine_id), enc_int(self.boots), enc_int(now), enc_str(cred.username),
enc_str(auth_params), enc_str(salt))
return seq(enc_int(3), seq(enc_int(msg_id), enc_int(65507), enc_str(bytes([flags])), enc_int(3)),
enc_str(usm), body)
packet = build(b"\x00" * auth_size)
if cred.auth_protocol:
hash_func, size = AUTH_PROTOCOLS[cred.auth_protocol]
packet = build(hmac.new(self._auth_key, packet, hash_func).digest()[:size])
def accept(data):
return self._parse_v3(data, msg_id)
message = self._exchange(packet, accept)
pdu = message["pdu"]
if pdu["type"] == REPORT:
oid = pdu["varbinds"][0][0] if pdu["varbinds"] else ""
if oid == "1.3.6.1.6.3.15.1.1.2.0" and resync: # not in time window: resynchronise once
self.boots, self.engine_time = message["boots"], message["time"]
self._time_base = time.monotonic()
return self._request_v3(pdu_type, oids, non_repeaters, max_repetitions, resync=False)
raise SnmpAuthError(f"SNMPv3 {cred.username}: {REPORT_TEXT.get(oid, 'abgelehnt (' + oid + ')')}")
return pdu
# public API ---------------------------------------------------------
def request(self, pdu_type, oids, non_repeaters=0, max_repetitions=0):
if self.credential.version == "3":
return self._request_v3(pdu_type, oids, non_repeaters, max_repetitions)
return self._request_v2(pdu_type, oids, non_repeaters, max_repetitions)
def get(self, oids):
"""``{oid: value}``; missing objects are left out."""
result = {}
oids = list(oids)
for start in range(0, len(oids), 20):
pdu = self.request(GET, oids[start:start + 20])
if pdu["error_status"]:
# v1-style error for one bad OID: fall back to single requests
for oid in oids[start:start + 20]:
single = self.request(GET, [oid])
if not single["error_status"]:
result.update({o: v for o, tag, v in single["varbinds"] if tag < NO_SUCH_OBJECT})
continue
result.update({oid: value for oid, tag, value in pdu["varbinds"] if tag < NO_SUCH_OBJECT})
return result
def walk(self, root, limit=2000):
"""``{oid: value}`` of the subtree below ``root``."""
result, current = {}, root
while len(result) < limit:
if self.bulk:
pdu = self.request(GET_BULK, [current], 0, 25)
if pdu["error_status"]:
self.bulk = False
continue
else:
pdu = self.request(GET_NEXT, [current])
if pdu["error_status"]:
break
if not pdu["varbinds"]:
break
done = False
for oid, tag, value in pdu["varbinds"]:
if tag == END_OF_MIB_VIEW or not in_subtree(oid, root) or oid_key(oid) <= oid_key(current):
done = True
break
result[oid] = value
current = oid
if done:
break
return result
def connect(host, credentials, timeout=1.0, retries=1, check_oid="1.3.6.1.2.1.1.2.0", port=PORT):
"""First credential that works for ``host``: ``(client, notes)``.
``notes`` collects why other credentials failed (e.g. a wrong v3 password),
which helps to spot misconfigured devices. Raises ``SnmpTimeout`` when no
credential got an answer.
"""
notes = []
for record in credentials:
try:
client = SnmpClient(host, record, timeout, retries, port)
if client.get([check_oid]):
return client, notes
notes.append(f"{client.credential.label}: keine Daten")
except SnmpAuthError as error:
notes.append(str(error))
except SnmpTimeout:
continue
except SnmpError as error:
notes.append(str(error))
if notes:
raise SnmpAuthError("; ".join(notes))
raise SnmpTimeout(f"{host}: keine SNMP-Antwort")
def table(walked, root):
"""Group a walked table by row index: ``{index tuple: {column: value}}``."""
rows = {}
base = len(oid_key(root))
for oid, value in walked.items():
key = oid_key(oid)
if len(key) <= base + 1:
continue
rows.setdefault(key[base + 1:], {})[key[base]] = value
return rows
File diff suppressed because it is too large. Load diff
+143
View File
@@ -0,0 +1,143 @@
"""Updates from the Gitea releases of the project.
The latest release is read anonymously from the Gitea API. The installed
version updates by running the new installer silently (it restarts the
application afterwards); the portable EXE is swapped in place: Windows allows
renaming a running EXE, so the old file is moved aside and removed on the next
start.
"""
import re
import subprocess
import sys
from pathlib import Path
import requests
from netbox_sync import APP_VERSION
REPOSITORY_API = "https://git.mrblake.cc/api/v1/repos/MrBlake/NetBox-Import-Desktop"
LATEST_RELEASE_URL = f"{REPOSITORY_API}/releases/latest"
PORTABLE_ASSET = "NetBox VM Import.exe"
INSTALLER_ASSET = re.compile(r"(?i)^NetBoxSynchronizer-Setup-[\d.]+\.exe$")
INSTALLER_ARGUMENTS = ("/SILENT", "/SUPPRESSMSGBOXES", "/NORESTART", "/CLOSEAPPLICATIONS")
_DETACHED = 0x00000008 | 0x00000200 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
class UpdateError(RuntimeError):
pass
def parse_version(text):
"""``"v4.6.0"`` → ``(4, 6, 0)``."""
numbers = [int(part) for part in re.findall(r"\d+", text or "")[:3]]
return tuple(numbers + [0] * (3 - len(numbers)))
def install_kind():
"""``"installer"``, ``"portable"`` or ``None`` when running from source."""
if not getattr(sys, "frozen", False):
return None
exe_dir = Path(sys.executable).resolve().parent
bundle = Path(getattr(sys, "_MEIPASS", exe_dir)).resolve()
# A one-file (portable) build unpacks itself into a temporary folder.
return "installer" if bundle == exe_dir or exe_dir in bundle.parents else "portable"
def check_for_update(current=APP_VERSION, timeout=10):
"""Return the newer release or ``None``."""
try:
response = requests.get(LATEST_RELEASE_URL, timeout=timeout, headers={"Accept": "application/json"})
response.raise_for_status()
release = response.json()
except (requests.RequestException, ValueError) as error:
raise UpdateError(f"Update-Server nicht erreichbar: {error}") from error
if release.get("draft") or release.get("prerelease"):
return None
tag = release.get("tag_name") or ""
if parse_version(tag) <= parse_version(current):
return None
return {
"version": tag.lstrip("vV"),
"name": release.get("name") or tag,
"notes": release.get("body") or "",
"page": release.get("html_url") or "",
"assets": {asset["name"]: {"url": asset["browser_download_url"], "size": int(asset.get("size") or 0)}
for asset in release.get("assets", []) if asset.get("browser_download_url")},
}
def pick_asset(release, kind):
"""``(name, asset)`` matching the running installation, or ``None``."""
for name, asset in release["assets"].items():
if kind == "portable" and name.casefold() == PORTABLE_ASSET.casefold():
return name, asset
if kind == "installer" and INSTALLER_ASSET.match(name):
return name, asset
return None
def download(asset, target, progress=None, cancelled=None, timeout=30):
"""Stream ``asset`` to ``target``; the size is verified before the file is kept."""
target = Path(target)
partial = target.with_name(target.name + ".part")
try:
with requests.get(asset["url"], stream=True, timeout=timeout) as response:
response.raise_for_status()
total = asset.get("size") or int(response.headers.get("Content-Length") or 0)
done = 0
with partial.open("wb") as handle:
for chunk in response.iter_content(256 * 1024):
if cancelled and cancelled():
raise UpdateError("Download abgebrochen.")
handle.write(chunk)
done += len(chunk)
if progress:
progress(done, total)
except requests.RequestException as error:
partial.unlink(missing_ok=True)
raise UpdateError(f"Download fehlgeschlagen: {error}") from error
except BaseException:
partial.unlink(missing_ok=True)
raise
if total and done != total:
partial.unlink(missing_ok=True)
raise UpdateError(f"Download unvollständig ({done} von {total} Bytes).")
partial.replace(target)
return target
def portable_download_path():
exe = Path(sys.executable)
return exe.with_name(exe.stem + ".new.exe")
def apply_portable(new_exe):
"""Swap the running portable EXE for ``new_exe`` and start it."""
exe = Path(sys.executable)
old = exe.with_name(exe.stem + ".old.exe")
old.unlink(missing_ok=True)
exe.replace(old)
try:
Path(new_exe).replace(exe)
except OSError:
old.replace(exe)
raise
subprocess.Popen([str(exe)], close_fds=True, creationflags=_DETACHED) # noqa: S603
def apply_installer(setup_exe):
"""Run the installer silently; it closes and restarts the application."""
subprocess.Popen([str(setup_exe), *INSTALLER_ARGUMENTS], close_fds=True, creationflags=_DETACHED) # noqa: S603
def remove_leftovers():
"""Delete the previous portable EXE left behind by an update."""
if install_kind() != "portable":
return
exe = Path(sys.executable)
for leftover in (exe.with_name(exe.stem + ".old.exe"), portable_download_path()):
try:
leftover.unlink(missing_ok=True)
except OSError:
pass
+1
View File
@@ -217,6 +217,7 @@ def query_client(host, credential=None, use_ssl=False, port=None, timeout=30):
"model": system.get("Model") or "",
"product_name": product.get("Name") or "",
"product_version": product.get("Version") or "",
"uuid": product.get("UUID") or "",
"serial": bios.get("SerialNumber") or "",
"bios_version": bios.get("SMBIOSBIOSVersion") or "",
"chassis": [as_int(value) for value in as_list(enclosure.get("ChassisTypes"))],
+144 -21
View File
@@ -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,13 +9,14 @@ 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 agent_client, backups, exchange, lancom, netbox
from netbox_sync.core.client_sync import ClientSyncEngine
from netbox_sync.core.clients import ClientScanError, expand_targets, new_row, query_ad, scan_clients
from netbox_sync.core.config import known_hosts_path
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,
cable_targets,
describe_snapshot,
discover_switch,
plan_switch_sync,
@@ -42,8 +44,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 +63,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 +321,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 +331,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 +388,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 +405,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 +415,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 +437,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,7 +487,13 @@ class Actions:
if not self.require_netbox_config():
return
by_id = {switch["id"]: switch for switch in self.state.switches}
items = [(dict(by_id[switch_id]), self.state.switch_snapshots[switch_id])
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", {})
items = [(dict(by_id[switch_id], vlan_map=dict(vlan_map), network_map=dict(network_map)),
self.state.switch_snapshots[switch_id])
for switch_id in switch_ids if switch_id in by_id and switch_id in self.state.switch_snapshots]
if not items:
widgets.message(self.window, "Keine Daten", "Bitte die Switche zuerst auslesen.", "info")
@@ -429,24 +517,36 @@ 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 item["networks"] or any(not vlan["netbox_name"] for vlan in item["vlans"])
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)
def ask():
# Started after the planning task has finished, so the next
# task is not rejected as "still busy".
if needs_review:
dialog = SwitchMappingDialog(self.window, reviewable, create_cables)
dialog = SwitchMappingDialog(self.window, reviewable, create_cables,
interface_loader=lambda device_id: cable_targets(nb, device_id))
if not dialog.exec():
return
stored = {switch["id"]: switch for switch in self.state.switches}
vlan_map.clear()
vlan_map.update(dialog.vlan_map)
network_map.clear()
network_map.update(dialog.network_map)
for switch, _snapshot in items:
choices = dialog.result.get(switch["id"])
if choices:
switch.update(choices)
if switch["id"] in stored:
stored[switch["id"]].update(choices)
switch.update(vlan_map=dict(vlan_map), network_map=dict(network_map))
for legacy in ("network_vrfs", "create_prefixes", "create_vlans"):
switch.pop(legacy, None)
stored.get(switch["id"], {}).pop(legacy, None)
self.state.touch()
self.state.switches_changed.emit() # ignored VLANs vanish from the VLAN column
self.tasks.run(lambda ctx: preview(ctx, nb), title="Änderungen berechnen", area="switch",
on_success=show_preview, on_error=self._netbox_failed)
QTimer.singleShot(0, ask)
@@ -456,7 +556,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):
@@ -467,22 +568,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
@@ -540,9 +645,19 @@ class Actions:
parallel = max(1, int(self.state.settings.get("parallel_wmi", 8)))
mode = options.get("mode", "ad")
hosts = []
if rows is None and mode == "hosts":
agent = mode == "agent"
agent_key = (self.state.profile or {}).get("agent_key", "")
agent_port = int(options.get("agent_port") or agent_client.DEFAULT_PORT)
if agent and not agent_key:
widgets.message(self.window, "Agent-Schlüssel fehlt",
"Bitte zuerst einen Agent-Schlüssel erzeugen und mit der Agent-Konfiguration verteilen.",
"info")
return
if agent:
parallel = max(parallel, 32)
if rows is None and mode in ("hosts", "agent"):
try:
hosts = expand_targets(options.get("hosts", ""))
hosts = expand_targets(options.get("agent_targets" if agent else "hosts", ""))
except ClientScanError as error:
widgets.error(self.window, "Ungültige Eingabe", str(error))
return
@@ -579,11 +694,17 @@ class Actions:
ctx.progress(done[0], len(targets), row["name"])
ctx.progress(0, len(targets), "")
extra = ({"query": lambda host: agent_client.query(host, agent_key, agent_port), "port": agent_port,
"service": "Agent"} if agent else {})
results = scan_clients(targets, credential, bool(options.get("use_ssl")), parallel, log=ctx.log,
on_result=on_result, cancelled=lambda: ctx.cancelled)
on_result=on_result, cancelled=lambda: ctx.cancelled, **extra)
ctx.check_cancelled()
by_host = {row["host"]: row for row in results}
return nb, engine, [by_host.get(row["host"], row) for row in targets]
scanned = [by_host.get(row["host"], row) for row in targets]
if agent and targets_given is None:
# A range scan: only hosts where an agent answered (or rejected us) are of interest.
scanned = [row for row in scanned if row["status"] != "offline"]
return nb, engine, scanned
def success(result):
nb, engine, scanned = result
@@ -689,7 +810,9 @@ class Actions:
self.state.client_engine = engine
self.state.clients_changed.emit()
text = (f"{report['devices_created']} Geräte angelegt, {report['devices_updated']} aktualisiert, "
f"{report['interfaces_created']} Schnittstellen, {report['ips_created']} IP-Adressen")
f"{report['interfaces_created']} Schnittstellen, {report['ips_created']} IP-Adressen"
+ (f", {report['assets_created']} Assets angelegt, {report['assets_updated']} aktualisiert"
if report.get("assets_created") or report.get("assets_updated") else ""))
area_log("client")(f"Client-Übertragung: {text}", "success")
if report["errors"]:
widgets.message(self.window, "Mit Problemen abgeschlossen", text + ".", "warning",
+1
View File
@@ -84,6 +84,7 @@ def main():
hints.colorSchemeChanged.connect(lambda _scheme: theme.mode == "system" and theme.apply())
install_excepthook(lambda: window)
window.show()
window.updates.check_on_start()
return app.exec()
+73 -2
View File
@@ -1,15 +1,83 @@
"""Dialogs for transferring scanned Windows clients to NetBox."""
from PySide6.QtWidgets import QFormLayout, QHBoxLayout, QTreeWidget, QTreeWidgetItem
import csv
from PySide6.QtCore import Qt
from PySide6.QtGui import QGuiApplication
from PySide6.QtWidgets import QFileDialog, QFormLayout, QHBoxLayout, QTreeWidget, QTreeWidgetItem
from netbox_sync.ui.dialogs import _Dialog, _mark_invalid
from netbox_sync.ui.icons import icon
from netbox_sync.ui.theme import theme
from netbox_sync.ui.widgets import Badge, Banner, SearchableComboBox, checkbox, form_dialog_buttons, label
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
from netbox_sync.ui.widgets import (
Badge,
Banner,
SearchableComboBox,
SearchField,
Table,
button,
checkbox,
error,
form_dialog_buttons,
label,
)
ROLE_HINTS = ("client", "arbeitsplatz", "workstation", "pc", "notebook")
class ClientSoftwareDialog(_Dialog):
"""Installed software of one client (from the NetBox Windows Agent), searchable and exportable."""
def __init__(self, parent, row):
software = row.get("software") or []
super().__init__(parent, f"Software – {row['name']}",
f"{len(software)} Programme laut NetBox-Agent (maschinenweit installierte Software)"
+ (f" · erfasst {row['scanned_text']}" if row.get("scanned_text") else ""), width=760)
self.resize(900, 640)
self.row = row
self.search = SearchField("Programm, Version, Hersteller …")
self.root.addWidget(self.search)
columns = [Column("name", "Programm", 420), Column("version", "Version", 150),
Column("publisher", "Hersteller", 260)]
self.model = RowTableModel(columns, row_id=lambda item: (item["name"], item["version"]))
self.model.set_rows(software)
self.proxy = FilterProxy(self.model)
self.search.textChanged.connect(self.proxy.set_text)
table = Table()
table.setModel(self.proxy)
table.sortByColumn(0, Qt.AscendingOrder)
for index, column in enumerate(columns):
table.setColumnWidth(index, column.width)
self.root.addWidget(table, 1)
buttons = QHBoxLayout()
buttons.addWidget(button("Als CSV speichern …", "download", on_click=self.save_csv))
buttons.addWidget(button("Kopieren", "copy", on_click=self.copy))
buttons.addStretch(1)
buttons.addWidget(button("Schließen", variant="primary", on_click=self.accept))
self.root.addLayout(buttons)
def _lines(self):
return [(item["name"], item["version"], item["publisher"]) for item in self.row.get("software") or []]
def copy(self):
QGuiApplication.clipboard().setText("\n".join("\t".join(line) for line in self._lines()))
def save_csv(self):
path, _filter = QFileDialog.getSaveFileName(self, "Software speichern", f"{self.row['name']}-software.csv",
"CSV (*.csv)")
if not path:
return
try:
# utf-8-sig and semicolons so that Excel opens it directly
with open(path, "w", encoding="utf-8-sig", newline="") as stream:
writer = csv.writer(stream, delimiter=";")
writer.writerow(("Programm", "Version", "Hersteller"))
writer.writerows(self._lines())
except OSError as problem:
error(self, "Speichern fehlgeschlagen", str(problem))
class ClientTargetDialog(_Dialog):
"""Choose site, role and tenant for the new devices."""
@@ -95,6 +163,9 @@ class ClientPreviewDialog(_Dialog):
(f"{report['interfaces_created']} Schnittstellen", "info"),
(f"{report['ips_created']} IP-Adressen", "info"),
]
assets = report.get("assets_created", 0) + report.get("assets_updated", 0)
if assets:
items.append((f"{assets} Assets", "info"))
if report["errors"]:
items.append((f"{len(report['errors'])} Probleme", "error"))
for text, kind in items:
+79
View File
@@ -119,6 +119,80 @@ winrm/config/listener</span>.</td></tr>
"""
AGENT_REPO = "https://git.mrblake.cc/MrBlake/Netbox-Client-Agent-for-Windows"
def _agent_html():
accent = theme.color("accent")
code_bg = theme.color("log_bg")
return f"""
<style>
h2 {{ font-size: 13pt; margin: 14px 0 6px 0; }}
h3 {{ font-size: 10.5pt; margin: 12px 0 4px 0; color: {accent}; }}
p, li {{ line-height: 140%; }}
.path {{ font-family: 'Cascadia Mono', Consolas, monospace; background: {code_bg}; }}
td {{ padding: 3px 10px 3px 0; vertical-align: top; }}
</style>
<h2>NetBox-Agent statt WinRM</h2>
<p>Der <b>NetBox Windows Agent</b> läuft unsichtbar als SYSTEM-Aufgabe auf den Clients und stellt sein
Inventar auf einem TCP-Port (Standard 8731) bereit. Dieser Rechner scannt IP-Bereiche und liest die Agenten
aus – <b>ohne WinRM, ohne Administratorkonto und ohne NetBox-Zugang auf den Clients</b>. Die Abfrage ist mit
dem Agent-Schlüssel signiert, die Antwort mit AES-256 verschlüsselt. Benutzer bemerken nichts: kein Fenster,
keine Firewall-Abfrage.</p>
<h3>1. Schlüssel und Konfiguration</h3>
<ol>
<li>Modus <b>NetBox-Agent (Netzwerk-Scan)</b> wählen und <b>Schlüssel erzeugen</b> (einer pro Kunde,
verschlüsselt im Profil gespeichert).</li>
<li>Optional unter <b>Freigegebene Netze</b> das Admin-Netz eintragen – dann nehmen die Agenten nur von dort
Verbindungen an.</li>
<li><b>Agent-Konfiguration speichern …</b> erzeugt die fertige <span class="path">config.json</span>.</li>
</ol>
<h3>2. Agent herunterladen</h3>
<p>Auf der <a href="{AGENT_REPO}/releases/latest">Release-Seite des Agenten</a> das ZIP-Paket laden –
<span class="path">win-x64</span> für Intel/AMD, <span class="path">win-arm64</span> für ARM-Geräte. Es enthält
<span class="path">agent.exe</span>, <span class="path">install.ps1</span>, <span class="path">uninstall.ps1</span>
und <span class="path">gpo-startup.ps1</span>. Dazu kommt die eben gespeicherte
<span class="path">config.json</span>.</p>
<h3>3a. Verteilung per Intune</h3>
<table>
<tr><td>Paket</td><td>agent.exe, config.json, install.ps1, uninstall.ps1 als Win32-App (.intunewin)</td></tr>
<tr><td>Installation</td><td><span class="path">powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\\install.ps1
-SourceDirectory .</span></td></tr>
<tr><td>Deinstallation</td><td><span class="path">powershell.exe -NoProfile -ExecutionPolicy Bypass -File
.\\uninstall.ps1</span></td></tr>
<tr><td>Verhalten</td><td>System · als <b>Erforderlich</b> einer Gerätegruppe zuweisen</td></tr>
<tr><td>Erkennung</td><td>Datei <span class="path">C:\\Program Files\\NetBox Windows Agent</span> /
<span class="path">agent.exe</span>, Methode „Zeichenfolge (Version)“, „Größer als oder gleich“, z. B. 0.2.0</td></tr>
</table>
<h3>3b. Verteilung per Gruppenrichtlinie</h3>
<ol>
<li>Diese fünf Dateien in eine Freigabe legen, die „Domänencomputer“ lesen dürfen, z. B.
<span class="path">\\\\fileserver\\NetBoxAgent$</span>:
<span class="path">agent.exe</span>, <span class="path">config.json</span>, <span class="path">install.ps1</span>,
<span class="path">uninstall.ps1</span> und <span class="path">gpo-startup.ps1</span>.</li>
<li>GPO für die OU der Clients: <b>Computerkonfiguration › Richtlinien › Windows-Einstellungen › Skripts ›
Starten › PowerShell-Skripts</b> – <span class="path">\\\\fileserver\\NetBoxAgent$\\gpo-startup.ps1</span>
ohne Parameter.</li>
<li><b>Computerkonfiguration › Administrative Vorlagen › System › Anmelden › Beim Neustart des Computers und
bei der Anmeldung immer auf das Netzwerk warten</b> = Aktiviert.</li>
</ol>
<p>Das Skript installiert beim Start nur, wenn sich agent.exe oder config.json auf der Freigabe geändert
haben – neue Versionen oder ein neuer Schlüssel werden so automatisch verteilt.</p>
<h3>4. Scannen</h3>
<p>IP-Bereiche als Ziele eintragen und <b>Abfragen</b>. Es erscheinen nur Rechner, auf denen ein Agent
antwortet; die Übertragung nach NetBox läuft wie beim WinRM-Scan mit Vorschau.</p>
<p>Findet der Scan keinen Agenten: Läuft die Aufgabe „NetBox Windows Agent Listener“? Ist Port 8731
zwischen den Netzen offen (<span class="path">Test-NetConnection PC0815 -Port 8731</span>)? Liegt dieser
Rechner in den freigegebenen Netzen? Die Firewall-Regel gilt für die Profile Domäne und Privat.</p>
"""
class ClientHelpDialog(_Dialog):
def __init__(self, parent, state, tab=0):
super().__init__(parent, "Einrichtungshilfe: Windows-Clients",
@@ -169,6 +243,11 @@ class ClientHelpDialog(_Dialog):
layout.addStretch(1)
self.tabs.addTab(test, "Verbindung testen")
agent = QTextBrowser()
agent.setOpenExternalLinks(True)
agent.setHtml(_agent_html())
self.tabs.addTab(agent, "NetBox-Agent")
self.root.addWidget(self.tabs, 1)
self.root.addWidget(button("Schließen", variant="primary", on_click=self.accept), 0, Qt.AlignRight)
self.tabs.setCurrentIndex(tab)
+379 -107
View File
@@ -1,5 +1,6 @@
"""Modal dialogs for editing connections and reviewing changes."""
import re
import uuid
from PySide6.QtCore import QThreadPool, Qt
@@ -26,7 +27,7 @@ from PySide6.QtWidgets import (
)
from netbox_sync.core.config import known_hosts_path
from netbox_sync.core.switches import MATCH_METHODS, PLATFORMS, forget_host_key
from netbox_sync.core.switches import MATCH_METHODS, PLATFORMS, VLAN_METHODS, forget_host_key
from netbox_sync.core.virtualization import test_source
from netbox_sync.ui.icons import icon
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
@@ -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"))
@@ -582,7 +619,10 @@ class SwitchMappingDialog(_Dialog):
NEW = "\x00new"
def __init__(self, parent, plans, create_cables):
def __init__(self, parent, plans, create_cables, interface_loader=None):
# interface_loader(device_id) → cable targets of another chosen neighbor device.
self.interface_loader = interface_loader
self._far_end_cache = {}
super().__init__(parent, "Zuordnung prüfen",
"Schnittstellen, Nachbarn, Netze und VLANs prüfen und bei Bedarf korrigieren. Neue Objekte "
"erhalten immer den Mandanten des Switches – die Auswahl wird im Profil gespeichert.",
@@ -590,8 +630,45 @@ class SwitchMappingDialog(_Dialog):
self.resize(1120, 680)
self.plans = plans
self.result = None
# Profile-wide VLAN decisions; every switch config carries the same map.
self.previous_vlan_map = dict((plans[0][0].get("vlan_map") if plans else None) or {})
self.vlan_map = dict(self.previous_vlan_map)
self.previous_network_map = dict((plans[0][0].get("network_map") if plans else None) or {})
self.network_map = dict(self.previous_network_map)
self._new_vrf_names = []
tabs = QTabWidget()
# 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)
@@ -604,10 +681,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()
@@ -640,9 +719,9 @@ class SwitchMappingDialog(_Dialog):
"Für jeden Nachbarn kann ein bestehendes NetBox-Gerät gewählt werden (Auswahl aus: "
f"{', '.join(scopes)}). Die Gegenstelle wird über den Portnamen gesucht; „kein Kabel“ "
"überspringt den Nachbarn.", muted=True, wrap=True))
self.neighbor_table = QTableWidget(0, 5)
self.neighbor_table = QTableWidget(0, 6)
self.neighbor_table.setHorizontalHeaderLabels(["Switch", "Lokaler Port", "Nachbar (LLDP/CDP)",
"Nachbar-Port", "NetBox-Gerät"])
"Nachbar-Port", "NetBox-Gerät", "Nachbar-Schnittstelle"])
for switch, plan in plans:
for neighbor in plan["neighbors"]:
row = self.neighbor_table.rowCount()
@@ -651,84 +730,92 @@ class SwitchMappingDialog(_Dialog):
combo.set_items([("– kein Kabel –", 0)] + [(device["name"], device["id"]) for device in plan["devices"]],
neighbor.get("device_id") or 0)
texts = (switch["name"], neighbor["local_port"], neighbor.get("system_name") or
neighbor.get("management_ip") or "", neighbor.get("remote_port") or "")
neighbor.get("management_ip") or neighbor.get("chassis_id") or "",
neighbor.get("remote_port") or "")
for column, text in enumerate(texts):
self.neighbor_table.setItem(row, column, QTableWidgetItem(text))
self.neighbor_table.setCellWidget(row, 4, combo)
self.neighbor_rows.append((switch, neighbor, combo))
self._prepare_table(self.neighbor_table, (140, 110, 220, 150, 260))
port_combo = SearchableComboBox("Schnittstelle suchen …")
self._fill_far_ends(port_combo, neighbor.get("interfaces") or [],
neighbor.get("suggested_interface"), neighbor.get("interface_id"))
self.neighbor_table.setCellWidget(row, 5, port_combo)
combo.currentIndexChanged.connect(
lambda _index, device_combo=combo, target=port_combo, item=neighbor:
self._device_changed(device_combo, target, item))
self.neighbor_rows.append((switch, neighbor, combo, port_combo))
self._prepare_table(self.neighbor_table, (130, 95, 200, 140, 220, 220))
neighbor_layout.addWidget(self.neighbor_table, 1)
found = sum(1 for _switch, neighbor, _combo in self.neighbor_rows if neighbor.get("device_id"))
found = sum(1 for _switch, neighbor, *_combos in self.neighbor_rows if neighbor.get("device_id"))
tabs.addTab(neighbor_page, f"Nachbarn ({found} von {len(self.neighbor_rows)} zugeordnet)")
# Networks --------------------------------------------------------------
# Network decisions apply to all switches of the profile: one row per network.
self.network_rows = []
networks = [(switch, plan, item) for switch, plan in plans for item in plan["networks"]]
networks = {}
for switch, plan in plans:
for item in plan["networks"]:
entry = networks.setdefault(item["network"], {"item": item, "switches": [], "tenants": [], "vrfs": {}})
entry["switches"].append(switch["name"])
if plan["tenant"] not in entry["tenants"]:
entry["tenants"].append(plan["tenant"])
entry["vrfs"].update({vrf["id"]: vrf["label"] for vrf in plan["vrfs"]})
if networks:
network_page = QWidget()
network_layout = QVBoxLayout(network_page)
network_layout.setContentsMargins(0, 12, 0, 0)
network_layout.addWidget(label(
"Netze der Switch-IP-Adressen. Die VRF gilt für Prefix und IP-Adressen; zur Auswahl stehen die "
"globale Tabelle und die VRFs des Mandanten. Fehlende Prefixe werden nur angelegt, wenn sie "
"angehakt sind – immer mit dem Mandanten des Switches.", muted=True, wrap=True))
self.network_table = QTableWidget(0, 5)
self.network_table.setHorizontalHeaderLabels(["Switch", "Mandant", "Netz", "VRF", "Prefix in NetBox"])
for switch, plan, item in networks:
row = self.network_table.rowCount()
self.network_table.insertRow(row)
combo = QComboBox()
combo.addItem("Global (keine VRF)", "")
for name in plan["vrfs"]:
combo.addItem(name, name)
combo.addItem("+ Neue VRF …", self.NEW)
combo.setCurrentIndex(max(0, combo.findData(item["vrf"])))
combo.setProperty("previous", combo.currentIndex())
for column, text in enumerate((switch["name"], plan["tenant"], item["network"])):
self.network_table.setItem(row, column, QTableWidgetItem(text))
self.network_table.setCellWidget(row, 3, combo)
status = QTableWidgetItem()
self.network_table.setItem(row, 4, status)
entry = (row, switch, item, combo, status)
self.network_rows.append(entry)
combo.activated.connect(lambda _index, entry=entry: self._vrf_chosen(entry))
self._update_network_row(entry, item["create"])
self._prepare_table(self.network_table, (140, 140, 150, 220, 200))
network_layout.addWidget(self.network_table, 1)
missing = sum(1 for _row, _switch, item, _combo, _status in self.network_rows if not item["existing_vrfs"])
tabs.addTab(network_page, f"Netze ({missing} Prefix(e) fehlen)")
"globale Tabelle und die VRFs der Mandantengruppe. Fehlende Prefixe werden nur angelegt, wenn sie "
"angehakt sind – mit dem Mandanten des Switches. Die Auswahl gilt für alle Switche des Profils.",
muted=True, wrap=True))
settled = {network: entry["item"]["stored"] or bool(entry["item"]["existing"])
for network, entry in networks.items()}
self.open_network_table = self._network_table()
self.settled_network_table = self._network_table()
for network, entry in networks.items():
table = self.settled_network_table if settled[network] else self.open_network_table
self._add_network_row(table, entry)
for table in (self.open_network_table, self.settled_network_table):
self._prepare_table(table, (160, 150, 150, 300, 200))
open_count = sum(1 for value in settled.values() if not value)
self.settled_network_toggle = self._collapsible(network_layout, self.open_network_table,
self.settled_network_table, open_count,
len(networks) - open_count, "Netze")
missing = sum(1 for entry in networks.values() if not entry["item"]["existing"])
tabs.addTab(network_page, f"Netze ({open_count} zu prüfen, {missing} Prefix(e) fehlen)")
# VLANs -----------------------------------------------------------------
# VLAN decisions apply to all switches of the profile: one row per VID.
self.vlan_rows = []
vlans = [(switch, plan, item) for switch, plan in plans for item in plan["vlans"]]
if vlans:
merged = {}
for switch, plan in plans:
for item in plan["vlans"]:
entry = merged.setdefault(item["vid"], {"item": item, "switches": [], "candidates": {}, "tenants": {}})
entry["switches"].append(switch["name"])
entry["candidates"].update({candidate["id"]: candidate["label"] for candidate in item["candidates"]})
entry["tenants"].update({tenant["id"]: tenant["name"] for tenant in plan["tenants"]})
if merged:
vlan_page = QWidget()
vlan_layout = QVBoxLayout(vlan_page)
vlan_layout.setContentsMargins(0, 12, 0, 0)
vlan_layout.addWidget(label(
"VLANs der Switch-Ports. Vorhandene VLANs des Mandanten werden den Schnittstellen zugeordnet "
"(802.1Q-Modus, untagged/tagged). Fehlende VLANs werden nur angelegt, wenn sie angehakt sind.",
muted=True, wrap=True))
self.vlan_table = QTableWidget(0, 5)
self.vlan_table.setHorizontalHeaderLabels(["Switch", "Mandant", "VLAN", "Name (Switch)", "In NetBox"])
for switch, plan, item in vlans:
row = self.vlan_table.rowCount()
self.vlan_table.insertRow(row)
for column, text in enumerate((switch["name"], plan["tenant"], str(item["vid"]), item["name"])):
self.vlan_table.setItem(row, column, QTableWidgetItem(text))
status = QTableWidgetItem(item["netbox_name"] or "fehlt – anlegen")
if item["netbox_name"]:
status.setFlags(Qt.ItemIsEnabled)
else:
status.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
status.setCheckState(Qt.Checked if item["create"] else Qt.Unchecked)
status.setForeground(QColor(theme.color("warning")))
self.vlan_table.setItem(row, 4, status)
self.vlan_rows.append((switch, item, status))
self._prepare_table(self.vlan_table, (140, 140, 70, 200, 200))
vlan_layout.addWidget(self.vlan_table, 1)
missing = sum(1 for _switch, item, _status in self.vlan_rows if not item["netbox_name"])
tabs.addTab(vlan_page, f"VLANs ({missing} fehlen)")
"Gesucht wird in der Mandantengruppe über die VLAN-ID; bei mehreren Treffern entscheiden Mandant, "
"Standort und Name. Neue VLANs erhalten den eingetragenen Namen und Mandanten. Ignorierte VLANs "
"werden weder angelegt noch zugeordnet und fehlen im Label. Die Auswahl gilt für alle Switche "
"des Profils und wird gespeichert.", muted=True, wrap=True))
settled = {vid: entry["item"]["stored"] or entry["item"]["method"] in ("vid", "name")
for vid, entry in merged.items()}
self.open_vlan_table = self._vlan_table()
self.settled_vlan_table = self._vlan_table()
for vid in sorted(merged):
self._add_vlan_row(self.settled_vlan_table if settled[vid] else self.open_vlan_table, merged[vid])
for table in (self.open_vlan_table, self.settled_vlan_table):
self._prepare_table(table, (130, 60, 150, 280, 190, 170, 110))
open_count = sum(1 for value in settled.values() if not value)
self.settled_toggle = self._collapsible(vlan_layout, self.open_vlan_table, self.settled_vlan_table,
open_count, len(merged) - open_count, "VLANs")
missing = sum(1 for entry in merged.values() if entry["item"]["method"] == "new")
tabs.addTab(vlan_page, f"VLANs ({open_count} zu prüfen, {missing} fehlen)")
self.root.addWidget(tabs, 1)
self.root.addWidget(self.error_banner)
@@ -749,25 +836,129 @@ class SwitchMappingDialog(_Dialog):
for column, width in enumerate(widths):
table.setColumnWidth(column, width)
IGNORE = "\x00ignore"
@staticmethod
def _vlan_table():
table = QTableWidget(0, 7)
table.setHorizontalHeaderLabels(["Switch(e)", "VLAN", "Name (Switch)", "NetBox-VLAN",
"Name des neuen VLANs", "Mandant (neu)", "Zuordnung"])
return table
def _add_vlan_row(self, table, entry):
item = entry["item"]
row = table.rowCount()
table.insertRow(row)
switches = ", ".join(entry["switches"])
for column, text in enumerate((switches, str(item["vid"]), item["name"])):
table.setItem(row, column, QTableWidgetItem(text))
combo = QComboBox()
for candidate_id, text in sorted(entry["candidates"].items(), key=lambda pair: pair[1].casefold()):
combo.addItem(text, candidate_id)
combo.addItem("+ neu anlegen", self.NEW)
combo.addItem("– nicht zuordnen –", 0)
combo.addItem("⊘ ignorieren (auf allen Switchen)", self.IGNORE)
current = {"skip": 0, "ignore": self.IGNORE}.get(item["method"], item["netbox_id"] or self.NEW)
combo.setCurrentIndex(max(0, combo.findData(current)))
name = QLineEdit(item["new_name"])
name.setMaxLength(64)
name.setPlaceholderText(item["name"])
tenant = QComboBox()
for tenant_id, text in sorted(entry["tenants"].items(), key=lambda pair: pair[1].casefold()):
tenant.addItem(text, tenant_id)
tenant.setCurrentIndex(max(0, tenant.findData(item["new_tenant"])))
method = QTableWidgetItem(VLAN_METHODS.get(item["method"], item["method"])
+ (" · gespeichert" if item["stored"] else ""))
if not item["stored"] and item["method"] in ("ambiguous", "new"):
method.setForeground(QColor(theme.color("warning")))
table.setCellWidget(row, 3, combo)
table.setCellWidget(row, 4, name)
table.setCellWidget(row, 5, tenant)
table.setItem(row, 6, method)
def toggle(_index=None):
for widget in (name, tenant):
widget.setEnabled(combo.currentData() == self.NEW)
combo.currentIndexChanged.connect(toggle)
toggle()
self.vlan_rows.append((item, combo, name, tenant))
@staticmethod
def _collapsible(layout, open_table, settled_table, open_count, settled_count, noun):
"""Open items on top, decided ones in a collapsed section that can be expanded."""
layout.addWidget(label(f"<b>Zu prüfen ({open_count})</b>" if open_count else
f"Alle {noun} sind zugeordnet oder gespeichert.", wrap=True))
layout.addWidget(open_table, 1)
open_table.setVisible(bool(open_count))
toggle = button("", variant="link")
toggle.setCheckable(True)
def update(expanded):
arrow = "▾" if expanded else "▸"
toggle.setText(f"{arrow} Gespeicherte und eindeutig zugeordnete {noun} ({settled_count})"
+ ("" if expanded else " – zum Bearbeiten ausklappen"))
settled_table.setVisible(expanded and settled_count > 0)
toggle.toggled.connect(update)
update(False)
toggle.setVisible(settled_count > 0)
layout.addWidget(toggle, 0, Qt.AlignLeft)
layout.addWidget(settled_table, 1)
return toggle
@staticmethod
def _network_table():
table = QTableWidget(0, 5)
table.setHorizontalHeaderLabels(["Switch(e)", "Mandant", "Netz", "VRF", "Prefix in NetBox"])
return table
def _add_network_row(self, table, entry):
item = entry["item"]
row = table.rowCount()
table.insertRow(row)
texts = (", ".join(entry["switches"]), ", ".join(entry["tenants"]), item["network"])
for column, text in enumerate(texts):
table.setItem(row, column, QTableWidgetItem(text))
combo = QComboBox()
combo.addItem("Global (keine VRF)", 0)
for vrf_id, text in sorted(entry["vrfs"].items(), key=lambda pair: pair[1].casefold()):
combo.addItem(text, vrf_id)
new_names = list(self._new_vrf_names)
if item["vrf_name"] and item["vrf_name"] not in new_names:
new_names.append(item["vrf_name"])
for name in new_names:
combo.addItem(f"{name} (neu)", f"new:{name}")
combo.addItem("+ Neue VRF …", self.NEW)
current = f"new:{item['vrf_name']}" if item["vrf_name"] else item["vrf_id"]
combo.setCurrentIndex(max(0, combo.findData(current)))
combo.setProperty("previous", combo.currentIndex())
table.setCellWidget(row, 3, combo)
status = QTableWidgetItem()
table.setItem(row, 4, status)
row_entry = (item, combo, status)
self.network_rows.append(row_entry)
combo.activated.connect(lambda _index, row_entry=row_entry: self._vrf_chosen(row_entry))
self._update_network_row(row_entry, item["create"])
def _vrf_chosen(self, entry):
_row, switch, _item, combo, _status = entry
_item, combo, _status = entry
if combo.currentData() == self.NEW:
name = ask_text(self, "Neue VRF", "Name der neuen VRF. Sie wird beim Übertragen mit dem Mandanten "
"des Switches angelegt.")
if not name:
combo.setCurrentIndex(combo.property("previous"))
return
# Offer the new VRF in every row of the same switch.
for _r, other_switch, _i, other, _s in self.network_rows:
if other_switch["id"] == switch["id"] and other.findData(name) < 0:
other.insertItem(other.count() - 1, name, name)
combo.setCurrentIndex(combo.findData(name))
self._new_vrf_names.append(name)
# Offer the new VRF in every network row.
for _other_item, other, _other_status in self.network_rows:
if other.findData(f"new:{name}") < 0:
other.insertItem(other.count() - 1, f"{name} (neu)", f"new:{name}")
combo.setCurrentIndex(combo.findData(f"new:{name}"))
combo.setProperty("previous", combo.currentIndex())
self._update_network_row(entry)
def _update_network_row(self, entry, create=None):
_row, _switch, item, combo, status = entry
if combo.currentData() in item["existing_vrfs"]:
item, combo, status = entry
if combo.currentData() in item["existing"]:
status.setText("vorhanden")
status.setFlags(Qt.ItemIsEnabled)
status.setData(Qt.CheckStateRole, None)
@@ -779,31 +970,74 @@ class SwitchMappingDialog(_Dialog):
status.setCheckState(Qt.Checked if create is not False else Qt.Unchecked)
status.setForeground(QColor(theme.color("warning")))
@staticmethod
def _fill_far_ends(combo, interfaces, suggested=None, current=None, evaluated=True):
""""automatic" (with the interface it would pick) plus the cable targets of the device.
``evaluated`` is False for a device chosen in the dialog: its automatic match is only known at sync time.
"""
automatic = f"automatisch ({suggested})" if suggested else (
"automatisch – keine passende gefunden" if interfaces and evaluated else "automatisch")
items = [(automatic, 0)] + [(item["name"] + (" (hat Kabel)" if item.get("cabled") else ""), item["id"])
for item in interfaces]
combo.set_items(items, current or 0)
combo.setEnabled(bool(interfaces) or bool(suggested))
def _device_changed(self, device_combo, target, neighbor):
device_id = int(device_combo.valid_data() or 0)
if not device_id:
self._fill_far_ends(target, [])
return
if device_id == (neighbor.get("device_id") or 0):
self._fill_far_ends(target, neighbor.get("interfaces") or [], neighbor.get("suggested_interface"),
neighbor.get("interface_id"))
return
if device_id not in self._far_end_cache:
try:
self._far_end_cache[device_id] = self.interface_loader(device_id) if self.interface_loader else []
except Exception: # noqa: BLE001 – the choice stays "automatic"
self._far_end_cache[device_id] = []
self._fill_far_ends(target, self._far_end_cache[device_id], evaluated=False)
def _filter_interfaces(self, only_unclear):
for row, _switch, item, _combo in self.interface_rows:
self.interface_table.setRowHidden(row, only_unclear and item["method"] == "name")
def accept(self):
result = {switch["id"]: {"interface_map": dict(switch.get("interface_map") or {}),
"neighbor_devices": dict(switch.get("neighbor_devices") or {})}
"neighbor_devices": dict(switch.get("neighbor_devices") or {}),
"neighbor_interfaces": dict(switch.get("neighbor_interfaces") 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)
else:
mapping[item["name"]] = target
for switch, neighbor, combo in self.neighbor_rows:
for switch, neighbor, combo, port_combo in self.neighbor_rows:
chosen = combo.valid_data()
chosen = int(chosen or 0)
stored = result[switch["id"]]["neighbor_devices"]
@@ -811,16 +1045,39 @@ class SwitchMappingDialog(_Dialog):
stored.pop(neighbor["local_port"], None)
else:
stored[neighbor["local_port"]] = chosen
for switch, plan in self.plans:
result[switch["id"]].update({"network_vrfs": {}, "create_prefixes": [], "create_vlans": []})
for _row, switch, item, combo, status in self.network_rows:
choices = result[switch["id"]]
choices["network_vrfs"][item["network"]] = combo.currentData()
if status.data(Qt.CheckStateRole) is not None and status.checkState() == Qt.Checked:
choices["create_prefixes"].append(item["network"])
for switch, item, status in self.vlan_rows:
if not item["netbox_name"] and status.checkState() == Qt.Checked:
result[switch["id"]]["create_vlans"].append(item["vid"])
# 0 = automatic (name, port number, MAC or single port); otherwise the chosen NetBox interface.
interface_id = int(port_combo.valid_data() or 0) if chosen else 0
interfaces = result[switch["id"]]["neighbor_interfaces"]
if interface_id:
interfaces[neighbor["local_port"]] = interface_id
else:
interfaces.pop(neighbor["local_port"], None)
network_map = dict(self.previous_network_map)
for item, combo, status in self.network_rows:
chosen = combo.currentData()
new_name = chosen[4:] if isinstance(chosen, str) and chosen.startswith("new:") else ""
network_map[item["network"]] = {
"vrf_id": chosen if isinstance(chosen, int) and chosen else None,
"vrf_name": new_name,
"create": status.data(Qt.CheckStateRole) is not None and status.checkState() == Qt.Checked,
}
self.network_map = network_map
vlan_map = dict(self.previous_vlan_map)
for item, combo, name, tenant in self.vlan_rows:
chosen = combo.currentData()
if chosen == self.NEW:
if not name.text().strip():
self.show_error(f"Bitte einen Namen für das neue VLAN {item['vid']} eingeben.")
return
choice = {"action": "new", "name": name.text().strip(), "tenant": tenant.currentData()}
elif chosen == self.IGNORE:
choice = {"action": "ignore"}
elif chosen:
choice = {"action": "map", "id": chosen}
else:
choice = {"action": "skip"}
vlan_map[str(item["vid"])] = choice
self.vlan_map = vlan_map
self.result = result
super().accept()
@@ -829,17 +1086,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)
@@ -847,14 +1109,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)
@@ -864,15 +1118,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)")
@@ -880,9 +1151,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))
+4
View File
@@ -26,8 +26,12 @@ _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"/>',
"printer": '<path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/>'
'<path d="M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6"/><rect x="6" y="14" width="12" height="8" rx="1"/>',
"play": '<polygon points="6 3 20 12 6 21 6 3"/>',
"search": '<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>',
"check": '<path d="M20 6 9 17l-5-5"/>',
+16 -3
View File
@@ -23,11 +23,14 @@ 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.printers import PrintersPage
from netbox_sync.ui.pages.scanner import ScannerPage
from netbox_sync.ui.pages.settings import SettingsPage
from netbox_sync.ui.pages.switches import SwitchesPage
from netbox_sync.ui.pages.vms import VMsPage
@@ -35,6 +38,7 @@ from netbox_sync.ui.resources import resource_path
from netbox_sync.ui.state import AppState
from netbox_sync.ui.tasks import TaskManager, log_bus
from netbox_sync.ui.theme import theme
from netbox_sync.ui.updates import UpdateManager
from netbox_sync.ui.widgets import Badge, Toast, button, label
NAVIGATION = (
@@ -43,7 +47,10 @@ NAVIGATION = (
("vms", "Virtuelle Maschinen", "server"),
("switches", "Switche", "network"),
("clients", "Windows-Clients", "monitor"),
("aps", "Access Points", "wifi"),
("printers", "Drucker", "printer"),
("ipam", "VRFs && Netze", "globe"),
("scanner", "Netzwerk-Scanner", "search"),
("log", "Protokoll", "list"),
)
@@ -81,6 +88,7 @@ class MainWindow(QMainWindow):
self.state = AppState()
self.tasks = TaskManager()
self.actions = Actions(self)
self.updates = UpdateManager(self)
self.pages = {}
self.nav_buttons = {}
self.unseen_errors = 0
@@ -102,7 +110,10 @@ 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),
("printers", PrintersPage),
("ipam", IpamPage), ("scanner", ScannerPage),
("log", LogPage),
("settings", SettingsPage)):
page = page_class(self)
self.pages[key] = page
@@ -120,7 +131,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)
@@ -271,6 +282,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)
@@ -361,7 +374,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", "printers", "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()
+497
View File
@@ -0,0 +1,497 @@
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, header="Sophos-Standort / Access Point", noun="APs"):
super().__init__(parent, "Standorte & Mandanten zuordnen",
f"Der Standort ist optional – {noun} 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([header, noun, "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"
# Overridden by pages that reuse this workflow (printers).
settings_key = "access_points"
noun = "Access Points"
source_name = "Sophos"
role_hints = ROLE_HINTS
key_func = staticmethod(ap_key)
mapping_header = "Sophos-Standort / Access Point"
mapping_noun = "APs"
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(self.settings_key, {}) 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 self._suggest_role(roles)
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 _suggest_role(self, roles):
return next((role_id for name, role_id in roles if name.casefold() in self.role_hints
or "access point" in name.casefold()), None)
def _make_engine(self, nb, log):
return APSyncEngine(nb, log)
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 = self._make_engine(connect(ctx), ctx.log)
ctx.log("Lade Standorte, Mandanten und vorhandene Geräte …")
engine.load_context()
ctx.log(f"Suche {len(aps)} {self.noun} in NetBox …")
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 %s in NetBox, %s nur in NetBox", found, len(self.aps),
self.noun, len(self.only_netbox))
self._refresh()
self.tasks.run(work, title=f"{self.noun} 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(self.key_func(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._excluded(ap) else ("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=self.key_func(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": [f"In NetBox, aber nicht im {self.source_name}-Ergebnis"]})
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)} {self.noun}" + (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 _excluded(self, ap):
"""Left out deliberately (overridden by the printer page)."""
return False
def _new_aps(self):
return [ap for ap in self.aps if not ap.get("device") and not self._excluded(ap)]
def _prepare_sync(self):
return self.engine
def _mapping_rows(self, new):
"""``(text, count, (kind, key), placement)`` per Sophos site, plus APs without one."""
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 {self.source_name}-Standort)", 1, ("ap", self.key_func(ap)),
self._placement(ap))
for ap in new if not ap["site_hint"]]
return rows
def map_sites(self):
if not self.engine:
return False
rows = self._mapping_rows(self._new_aps())
if not rows:
self.window.toast(f"Alle {self.noun} sind bereits in NetBox.", "info")
return False
dialog = SiteMappingDialog(self.window, rows, self.engine.ap_sites, self.engine.group_tenants,
self.mapping_header, self.mapping_noun)
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"Für neue {self.noun} 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[self.key_func(ap)] = {"site": placement["site"], "tenant": self._tenant_for(placement)}
homeless = [ap["name"] for ap in new if not placements[self.key_func(ap)]["site"]]
if homeless and not default_site:
widgets.message(self.window, "Standard-Standort fehlt",
f"{len(homeless)} neue {self.noun} 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._prepare_sync(), self.rename.isChecked()
aps = [ap for ap in self.aps if (ap.get("device") and not self._excluded(ap))
or self.key_func(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=f"{self.noun} ü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']} {self.noun} 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)
+185 -13
View File
@@ -1,13 +1,18 @@
import ipaddress
import json
import os
import time
from PySide6.QtCore import Qt
from PySide6.QtGui import QGuiApplication
from PySide6.QtWidgets import (
QButtonGroup,
QFileDialog,
QComboBox,
QGridLayout,
QHBoxLayout,
QLineEdit,
QMenu,
QPlainTextEdit,
QRadioButton,
QSpinBox,
@@ -15,14 +20,29 @@ from PySide6.QtWidgets import (
QWidget,
)
from netbox_sync.core import agent_client
from netbox_sync.core.client_sync import clean_manufacturer
from netbox_sync.core.clients import WINRM_HTTP_PORT, WINRM_HTTPS_PORT, os_label, os_version_label
from netbox_sync.ui import widgets
from netbox_sync.ui.client_dialogs import ClientSoftwareDialog
from netbox_sync.ui.client_help import ClientHelpDialog
from netbox_sync.ui.icons import icon
from netbox_sync.ui.theme import theme
from netbox_sync.ui.credentials import ask_credentials
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
from netbox_sync.ui.pages import Page
from netbox_sync.ui.widgets import Badge, Banner, Card, EmptyState, SearchField, Table, button, checkbox, label
from netbox_sync.ui.widgets import (
Badge,
Banner,
Card,
EmptyState,
PasswordField,
SearchField,
Table,
button,
checkbox,
label,
)
STATUS = {
"ok": ("OK", "success"),
@@ -55,6 +75,9 @@ def _tooltip(row):
("RAM", f"{row['memory'] / 1024 ** 3:.0f} GB" if row.get("memory") else ""),
("Angemeldet", row.get("user")),
("Letzter Start", (row.get("last_boot") or "").replace("T", " ")),
("Quelle", f"NetBox-Agent {row.get('agent_version', '')}".strip() if row.get("source") == "agent" else ""),
("Software", f"{row['software_count']} Programme (laut Agent)" if row.get("software_count") else ""),
("Datenträger", ", ".join(f"{disk['model']} ({disk['size'] / 1e9:.0f} GB)" for disk in row.get("disks") or [])),
("AD", (row.get("ad") or {}).get("dn")),
):
if value:
@@ -87,7 +110,8 @@ class ClientsPage(Page):
mode_row.addWidget(label("Ziele", object_name="CardTitle"))
self.mode_group = QButtonGroup(self)
self.mode_buttons = {}
for key, text in (("ad", "Active Directory"), ("hosts", "Hostnamen / IP-Bereiche")):
for key, text in (("ad", "Active Directory"), ("hosts", "Hostnamen / IP-Bereiche"),
("agent", "NetBox-Agent (Netzwerk-Scan)")):
radio = QRadioButton(text)
radio.setCursor(Qt.PointingHandCursor)
self.mode_group.addButton(radio)
@@ -136,12 +160,17 @@ class ClientsPage(Page):
"PC0815.firma.local 10.0.10.0/24 10.0.20.10-50")
self.hosts.setFixedHeight(76)
self.mode_stack.addWidget(self.hosts)
self.mode_stack.addWidget(self._build_agent_panel())
# QPlainTextEdit reports a tall size hint even with a fixed height.
self.mode_stack.setFixedHeight(max(ad_panel.sizeHint().height(), self.hosts.height()))
self.mode_stack.setFixedHeight(max(ad_panel.sizeHint().height(), self.hosts.height(),
self.agent_panel.sizeHint().height()))
targets.add(self.mode_stack)
targets.add(widgets.hline())
self.separator = widgets.hline()
targets.add(self.separator)
logon = QHBoxLayout()
self.logon_widget = QWidget()
logon = QHBoxLayout(self.logon_widget)
logon.setContentsMargins(0, 0, 0, 0)
logon.setSpacing(10)
logon.addWidget(label("Anmeldung", object_name="CardTitle"))
self.account_badge = Badge("", "neutral")
@@ -161,7 +190,7 @@ class ClientsPage(Page):
"verschlüsselt. HTTPS erfordert einen Zertifikats-Listener auf den Clients.")
logon.addWidget(self.current_user)
logon.addWidget(self.use_ssl)
targets.add(logon)
targets.add(self.logon_widget)
self.body.addWidget(targets)
self.help_banner = Banner("Die Clients müssen einmalig für WinRM vorbereitet werden (Gruppenrichtlinie, "
@@ -210,6 +239,10 @@ class ClientsPage(Page):
Column("chassis", "Bauform", 95),
Column("user", "Angemeldet", 140),
Column("ips", "IP-Adressen", 160, value=_ips),
Column("software", "Software", 90,
value=lambda row: f"{len(row['software'])} Programme" if row.get("software") else "",
sort=lambda row: len(row.get("software") or []), color=lambda row: "accent",
tooltip=lambda row: "Doppelklick: vollständige Liste" if row.get("software") else ""),
Column("last_logon", "AD-Anmeldung", 105, value=lambda row: _date((row.get("ad") or {}).get("last_logon")),
sort=lambda row: (row.get("ad") or {}).get("last_logon") or 0),
]
@@ -221,6 +254,8 @@ class ClientsPage(Page):
for index, column in enumerate(columns):
self.table.setColumnWidth(index, column.width)
self.table.doubleClicked.connect(self._toggle)
self.table.setContextMenuPolicy(Qt.CustomContextMenu)
self.table.customContextMenuRequested.connect(self._context_menu)
card.add(self.table, 1)
footer = QHBoxLayout()
@@ -250,6 +285,10 @@ class ClientsPage(Page):
self.hosts.textChanged.connect(lambda: self._save(hosts=self.hosts.toPlainText()))
self.current_user.toggled.connect(self._current_user_toggled)
self.use_ssl.toggled.connect(lambda value: self._save(use_ssl=value))
self.agent_targets.textChanged.connect(lambda: self._save(agent_targets=self.agent_targets.toPlainText()))
self.agent_port.valueChanged.connect(lambda value: self._save(agent_port=value))
self.agent_networks.editingFinished.connect(
lambda: self._save(agent_networks=self.agent_networks.text().strip()))
self.search.textChanged.connect(self.proxy.set_text)
self.status_filter.currentIndexChanged.connect(self._apply_filters)
self.netbox_filter.currentIndexChanged.connect(self._apply_filters)
@@ -272,7 +311,8 @@ class ClientsPage(Page):
def load_options(self):
options = self.state.client_options
controls = (self.ad_server, self.ad_base, self.only_enabled, self.include_servers, self.max_age, self.hosts,
self.current_user, self.use_ssl, *self.mode_buttons.values())
self.current_user, self.use_ssl, self.agent_targets, self.agent_port, self.agent_networks,
*self.mode_buttons.values())
for widget in controls:
widget.blockSignals(True)
self.ad_server.setText(options.get("ad_server", ""))
@@ -284,17 +324,125 @@ class ClientsPage(Page):
self.hosts.setPlainText(options.get("hosts", ""))
self.current_user.setChecked(bool(options.get("use_current_user")))
self.use_ssl.setChecked(bool(options.get("use_ssl")))
if self.agent_targets.toPlainText() != options.get("agent_targets", ""):
self.agent_targets.setPlainText(options.get("agent_targets", ""))
self.agent_port.setValue(int(options.get("agent_port") or agent_client.DEFAULT_PORT))
self.agent_networks.setText(options.get("agent_networks", ""))
mode = options.get("mode", "ad")
self.mode_buttons.get(mode, self.mode_buttons["ad"]).setChecked(True)
self.mode_stack.setCurrentIndex(0 if mode == "ad" else 1)
for widget in controls:
widget.blockSignals(False)
self._show_mode(mode)
self._update_account()
self._update_agent_key()
def _set_mode(self, mode):
self.mode_stack.setCurrentIndex(0 if mode == "ad" else 1)
self._show_mode(mode)
self._save(mode=mode)
def _show_mode(self, mode):
self.mode_stack.setCurrentIndex({"ad": 0, "hosts": 1, "agent": 2}.get(mode, 0))
agent = mode == "agent"
# The agent needs no Windows logon – its shared key replaces it.
self.logon_widget.setVisible(not agent)
self.separator.setVisible(not agent)
self.help_banner.set(
"Der NetBox-Agent wird per Intune oder GPO verteilt und stellt sein Inventar verschlüsselt bereit – "
"ohne WinRM und ohne NetBox-Zugang auf den Clients. Die Einrichtungshilfe zeigt die Verteilung."
if agent else
"Die Clients müssen einmalig für WinRM vorbereitet werden (Gruppenrichtlinie, Firewall). Die "
"Einrichtungshilfe zeigt alle Schritte.")
# ------------------------------------------------------------------
# NetBox Windows Agent
# ------------------------------------------------------------------
def _build_agent_panel(self):
self.agent_panel = QWidget()
grid = QGridLayout(self.agent_panel)
grid.setContentsMargins(0, 0, 0, 0)
grid.setHorizontalSpacing(12)
grid.setVerticalSpacing(8)
self.agent_targets = QPlainTextEdit()
self.agent_targets.setPlaceholderText("IP-Bereiche oder Hostnamen, z. B. 10.0.10.0/24, 10.0.20.10-50")
self.agent_targets.setFixedHeight(52)
grid.addWidget(label("Ziele"), 0, 0)
grid.addWidget(self.agent_targets, 0, 1, 1, 5)
self.agent_key = PasswordField("noch kein Schlüssel")
self.agent_key.setReadOnly(True)
grid.addWidget(label("Agent-Schlüssel"), 1, 0)
grid.addWidget(self.agent_key, 1, 1)
self.agent_key_new = button("Neu erzeugen", "refresh", on_click=self.new_agent_key,
tooltip="Neuen Schlüssel für die Agenten dieses Kunden erzeugen")
self.agent_key_copy = button("Kopieren", "copy", variant="ghost", on_click=self.copy_agent_key)
self.agent_config = button("Agent-Konfiguration speichern …", "download", on_click=self.save_agent_config,
tooltip="config.json für die Verteilung per Intune oder GPO erzeugen")
grid.addWidget(self.agent_key_new, 1, 2)
grid.addWidget(self.agent_key_copy, 1, 3)
grid.addWidget(self.agent_config, 1, 4, 1, 2)
self.agent_port = QSpinBox()
self.agent_port.setRange(1, 65535)
self.agent_port.setFixedWidth(100)
self.agent_networks = QLineEdit()
self.agent_networks.setPlaceholderText("leer = jede Adresse, z. B. 10.0.0.0/24 (Netz dieses Rechners)")
grid.addWidget(label("Port"), 2, 0)
grid.addWidget(self.agent_port, 2, 1, Qt.AlignLeft)
grid.addWidget(label("Freigegebene Netze"), 2, 2)
grid.addWidget(self.agent_networks, 2, 3, 1, 3)
grid.setColumnStretch(1, 1)
grid.setColumnStretch(3, 1)
return self.agent_panel
def _update_agent_key(self):
key = (self.state.profile or {}).get("agent_key", "")
self.agent_key.setText(key)
self.agent_key_copy.setEnabled(bool(key))
self.agent_config.setEnabled(bool(key))
self.agent_key_new.setText("Neu erzeugen" if key else "Schlüssel erzeugen")
def new_agent_key(self):
if self.state.profile is None:
return
if self.state.profile.get("agent_key") and not widgets.confirm(
self.window, "Neuen Schlüssel erzeugen?",
"Bereits verteilte Agenten lassen sich danach erst wieder abfragen, wenn sie die neue "
"Konfiguration erhalten haben.", "Neu erzeugen", destructive=True):
return
self.state.edit_profile(agent_key=agent_client.new_scan_key())
self._update_agent_key()
self.window.toast("Neuer Agent-Schlüssel erzeugt – Konfiguration neu verteilen.", "info")
def copy_agent_key(self):
QGuiApplication.clipboard().setText(self.agent_key.text())
self.window.toast("Agent-Schlüssel kopiert.", "info")
def save_agent_config(self):
key = (self.state.profile or {}).get("agent_key", "")
if not key:
return
networks = [part.strip() for part in self.agent_networks.text().replace(";", ",").split(",") if part.strip()]
for network in networks:
try:
ipaddress.ip_network(network, strict=False)
except ValueError:
widgets.message(self.window, "Freigegebene Netze prüfen",
f"„{network}“ ist kein Netz in CIDR-Schreibweise (z. B. 10.0.0.0/24).", "warning")
return
path, _filter = QFileDialog.getSaveFileName(self.window, "Agent-Konfiguration speichern", "config.json",
"JSON (*.json)")
if not path:
return
data = agent_client.agent_config(key, self.agent_port.value(),
[str(ipaddress.ip_network(n, strict=False)) for n in networks])
try:
with open(path, "w", encoding="utf-8") as stream:
json.dump(data, stream, indent=2)
except OSError as error:
widgets.error(self.window, "Speichern fehlgeschlagen", str(error))
return
self.window.toast("config.json gespeichert – zusammen mit agent.exe per Intune oder GPO verteilen.",
"success")
def _current_user_toggled(self, value):
self._save(use_current_user=value)
self._update_account()
@@ -368,8 +516,28 @@ class ClientsPage(Page):
def _toggle(self, index):
row = self.proxy.row_at(index)
if self.model.columns[index.column()].key == "software" and row.get("software"):
self.show_software(row)
return
self.model.set_checked({row["id"]}, row["id"] not in self.model.checked)
def show_software(self, row):
ClientSoftwareDialog(self.window, dict(row, scanned_text=time.strftime(
"%d.%m.%Y %H:%M", time.localtime(row["scanned_at"])) if row.get("scanned_at") else "")).exec()
def _context_menu(self, position):
index = self.table.indexAt(position)
if not index.isValid():
return
row = self.proxy.row_at(index)
menu = QMenu(self)
action = menu.addAction(icon("list", theme.color("text_muted")), "Software anzeigen …",
lambda: self.show_software(row))
action.setEnabled(bool(row.get("software")))
if not row.get("software"):
action.setText("Software anzeigen … (nur mit NetBox-Agent)")
menu.exec(self.table.viewport().mapToGlobal(position))
def select_visible(self):
self.model.set_checked({row["id"] for row in self.proxy.visible_rows()})
@@ -416,12 +584,14 @@ class ClientsPage(Page):
return
self.ad_server.editingFinished.emit()
self.ad_base.editingFinished.emit()
if self._ensure_logon():
if self.state.client_options.get("mode") == "agent":
self.actions.scan_clients()
elif self._ensure_logon():
self.actions.scan_clients()
def rescan(self):
rows = self.model.checked_rows()
if rows and self._ensure_logon():
if rows and (self.state.client_options.get("mode") == "agent" or self._ensure_logon()):
self.actions.scan_clients(rows)
def load_file(self):
@@ -436,5 +606,7 @@ class ClientsPage(Page):
else:
self.actions.sync_clients(rows)
def show_help(self, tab=0):
ClientHelpDialog(self.window, self.state, tab if isinstance(tab, int) else 0).exec()
def show_help(self, tab=None):
if tab is None or isinstance(tab, bool): # button signals pass "checked"
tab = 3 if self.state.client_options.get("mode") == "agent" else 0
ClientHelpDialog(self.window, self.state, tab).exec()
+698
View File
@@ -0,0 +1,698 @@
"""Printers: SNMP network scan, comparison with NetBox and transfer (reuses the access point workflow)."""
import uuid
from PySide6.QtCore import Qt, QTimer
from PySide6.QtWidgets import (
QComboBox,
QFormLayout,
QHBoxLayout,
QLineEdit,
QMenu,
QStackedWidget,
QTableWidget,
QTableWidgetItem,
)
from netbox_sync.core import netscan, printers, snmp
from netbox_sync.ui import widgets
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.pages.access_points import STATE_DOT, STATE_TEXT, AccessPointsPage
from netbox_sync.ui.tasks import logger
from netbox_sync.ui.widgets import (
Card,
EmptyState,
PasswordField,
SearchableComboBox,
SearchField,
Table,
button,
checkbox,
form_dialog_buttons,
label,
)
MODEL_ACTIONS = (("create", "Gerätetyp neu anlegen"), ("map", "Vorhandenen Gerätetyp verwenden"),
("skip", "Diesmal überspringen"), ("ignore", "Dauerhaft ignorieren"))
AUTH_CHOICES = ["", *snmp.AUTH_PROTOCOLS]
PRIV_CHOICES = ["", *snmp.PRIV_PROTOCOLS]
def _supplies_short(row):
parts = []
for item in row.get("supplies") or []:
if item["percent"] is None:
continue
name = item.get("colour") or item.get("type") or item["name"]
parts.append(f"{name} {item['percent']} %")
return " · ".join(parts)
def _supplies_low(row):
return any(item["percent"] is not None and item["percent"] <= 10 for item in row.get("supplies") or [])
def _supplies_tooltip(row):
lines = [printers.supplies_text(row.get("supplies") or [])]
trays = row.get("trays") or []
if trays:
lines.append("\nPapierfächer:")
lines += [f"{tray['name']}: {tray['level'] or '–'}" + (f" ({tray['media']})" if tray["media"] else "")
for tray in trays]
return "\n".join(line for line in lines if line)
def _status(row):
return ", ".join(filter(None, [row.get("status", ""), *(row.get("errors") or [])]))
def _status_tooltip(row):
lines = []
if row.get("display"):
lines.append("Display: " + " | ".join(row["display"]))
if row.get("alerts"):
lines += ["Meldungen:"] + [f"• {alert}" for alert in row["alerts"]]
if row.get("sys_descr"):
lines.append(f"\n{row['sys_descr']}")
return "\n".join(lines)
class SnmpCredentialsDialog(_Dialog):
"""SNMPv2c communities and SNMPv3 users of a profile, tried in this order."""
COLUMNS = ("Version", "Community", "Benutzer (v3)", "Auth", "Auth-Passwort", "Privacy", "Privacy-Passwort")
def __init__(self, parent, credentials):
super().__init__(parent, "SNMP-Zugangsdaten",
"Jede Adresse wird mit diesen Zugangsdaten in dieser Reihenfolge abgefragt – erst die "
"funktionierenden des letzten Scans. SNMPv2c-Communities und SNMPv3-Benutzer lassen sich "
"mischen. Passwörter werden mit Windows DPAPI verschlüsselt im Profil gespeichert.",
width=980)
self.resize(1080, 460)
self.table = QTableWidget(0, len(self.COLUMNS))
self.table.setHorizontalHeaderLabels(self.COLUMNS)
self.table.verticalHeader().hide()
self.table.verticalHeader().setDefaultSectionSize(42)
self.table.setSelectionBehavior(QTableWidget.SelectRows)
self.table.setEditTriggers(QTableWidget.NoEditTriggers)
for column, width in enumerate((80, 160, 150, 100, 170, 100, 170)):
self.table.setColumnWidth(column, width)
self.table.horizontalHeader().setStretchLastSection(True)
self.rows = []
for record in credentials:
self._add(record)
actions = QHBoxLayout()
actions.addWidget(button("SNMPv2c-Community", "plus", on_click=lambda: self._add({"version": "2c"})))
actions.addWidget(button("SNMPv3-Benutzer", "plus", on_click=lambda: self._add(
{"version": "3", "auth_protocol": "SHA", "priv_protocol": "AES"})))
actions.addWidget(button("Entfernen", "trash", on_click=self._remove))
actions.addStretch(1)
self.root.addWidget(self.table, 1)
self.root.addLayout(actions)
self.root.addWidget(self.error_banner)
buttons, _ok = form_dialog_buttons(self, "Übernehmen")
self.root.addWidget(buttons)
self.result = []
def _add(self, record):
row = self.table.rowCount()
self.table.insertRow(row)
version = QComboBox()
version.addItems(["2c", "3"])
version.setCurrentText(str(record.get("version") or "2c"))
community = PasswordField("public")
community.setText(record.get("community", "public" if not self.rows else ""))
username = QLineEdit(record.get("username", ""))
auth = QComboBox()
auth.addItems(AUTH_CHOICES)
auth.setCurrentText(record.get("auth_protocol", ""))
auth_password = PasswordField()
auth_password.setText(record.get("auth_password", ""))
priv = QComboBox()
priv.addItems(PRIV_CHOICES)
priv.setCurrentText(record.get("priv_protocol", ""))
priv_password = PasswordField()
priv_password.setText(record.get("priv_password", ""))
cells = (version, community, username, auth, auth_password, priv, priv_password)
for column, widget in enumerate(cells):
self.table.setCellWidget(row, column, widget)
entry = {"id": record.get("id") or uuid.uuid4().hex[:8], "cells": cells}
self.rows.append(entry)
def update(*_args):
v3 = version.currentText() == "3"
community.setEnabled(not v3)
for widget in (username, auth, priv):
widget.setEnabled(v3)
auth_password.setEnabled(v3 and bool(auth.currentText()))
priv_password.setEnabled(v3 and bool(priv.currentText()))
for widget in (version, auth, priv):
widget.currentIndexChanged.connect(update)
update()
def _remove(self):
row = self.table.currentRow()
if row < 0:
return
self.table.removeRow(row)
del self.rows[row]
def accept(self):
result = []
for number, entry in enumerate(self.rows, 1):
version, community, username, auth, auth_password, priv, priv_password = entry["cells"]
if version.currentText() == "3":
record = {"id": entry["id"], "version": "3", "username": username.text().strip(),
"auth_protocol": auth.currentText(), "auth_password": auth_password.text(),
"priv_protocol": priv.currentText(), "priv_password": priv_password.text()}
problem = ("Benutzername fehlt" if not record["username"] else
"Privacy braucht Authentifizierung" if record["priv_protocol"] and not record["auth_protocol"]
else "Auth-Passwort mit mindestens 8 Zeichen nötig"
if record["auth_protocol"] and len(record["auth_password"]) < 8
else "Privacy-Passwort mit mindestens 8 Zeichen nötig"
if record["priv_protocol"] and len(record["priv_password"]) < 8 else "")
if not record["auth_protocol"]:
record["auth_password"] = ""
if not record["priv_protocol"]:
record["priv_password"] = ""
else:
record = {"id": entry["id"], "version": "2c", "community": community.text()}
problem = "Community fehlt" if not record["community"] else ""
if problem:
self.show_error(f"Zeile {number}: {problem}.")
return
result.append(record)
if not result:
self.show_error("Bitte mindestens eine Community oder einen SNMPv3-Benutzer anlegen.")
return
self.result = result
super().accept()
class ModelMappingDialog(_Dialog):
"""Decide per printer model that is missing in NetBox: create, map to an existing type, skip or ignore."""
def __init__(self, parent, rows, device_types):
super().__init__(parent, "Modelle zuordnen",
"Diese Modelle gibt es in NetBox noch nicht als Gerätetyp. Pro Modell: neu anlegen, einen "
"vorhandenen Gerätetyp verwenden, die Drucker dieses Modells diesmal überspringen oder dauerhaft "
"ignorieren (gespeichert im Profil).", width=900)
self.resize(1040, 520)
type_items = [(f"{row['manufacturer']} {row['model']}".strip(), row["id"]) for row in device_types]
self.table = QTableWidget(0, 4)
self.table.setHorizontalHeaderLabels(["Hersteller / Modell (SNMP)", "Drucker", "Aktion", "Gerätetyp in NetBox"])
self.rows = []
for text, count, key, decision, suggestion 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)))
action = QComboBox()
for value, caption in MODEL_ACTIONS:
action.addItem(caption, value)
device_type = SearchableComboBox("Gerätetyp suchen …")
device_type.set_items(type_items, decision.get("device_type") or suggestion)
chosen = decision.get("action") or ("map" if suggestion else "create")
action.setCurrentIndex(next(index for index, (value, _c) in enumerate(MODEL_ACTIONS) if value == chosen))
action.currentIndexChanged.connect(lambda _i, a=action, d=device_type: d.setEnabled(a.currentData() == "map"))
device_type.setEnabled(chosen == "map")
self.table.setCellWidget(row, 2, action)
self.table.setCellWidget(row, 3, device_type)
self.rows.append((key, text, action, device_type))
self.table.verticalHeader().hide()
self.table.verticalHeader().setDefaultSectionSize(42)
self.table.setEditTriggers(QTableWidget.NoEditTriggers)
self.table.setSelectionMode(QTableWidget.NoSelection)
self.table.horizontalHeader().setStretchLastSection(True)
for column, width in enumerate((330, 60, 250, 300)):
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, text, action, device_type in self.rows:
value = action.currentData()
if value == "map" and device_type.valid_data() is None:
self.show_error(f"Bitte für „{text}“ einen vorhandenen Gerätetyp wählen.")
return
result[key] = {"action": value, "device_type": device_type.valid_data() if value == "map" else None}
self.result = result
super().accept()
class PrintersPage(AccessPointsPage):
title = "Drucker"
subtitle = ("Drucker per SNMP (v2c und v3) im Netzwerk finden – herstellerübergreifend über die Printer-MIB – "
"mit NetBox abgleichen und mit Seitenzähler und Verbrauchsmaterial dokumentieren.")
settings_key = "printers"
noun = "Drucker"
source_name = "Scan"
role_hints = printers.ROLE_HINTS
key_func = staticmethod(printers.printer_key)
mapping_header = "Drucker (IP, Modell, SNMP-Standort)"
mapping_noun = "Drucker"
def __init__(self, window): # noqa: PLR0915 - builds the page
Page.__init__(self, window)
self.aps = []
self.only_netbox = []
self.engine = None
self.roles = []
self.file_name = ""
self.scan_task = None
self.others = []
self._engine_args = {}
self._compare_after_scan = False
self._skipped = set() # printer keys left out for this session
self._skipped_models = set() # model keys left out for this session
source = Card("Scan", "Erreichbare Adressen werden per SNMP abgefragt; Geräte nur mit offenem Druckerport "
"(9100/IPP/LPD) erscheinen als „ohne SNMP“.")
self.credentials_button = source.add_action(button("SNMP-Zugangsdaten …", "shield",
on_click=self.edit_credentials))
self.load_button = source.add_action(button("Scannen", "play", "primary", on_click=self.scan))
self.sync_button = source.add_action(button("Nach NetBox übertragen …", "upload", "primary",
on_click=self.sync))
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")
targets.addWidget(self.targets, 1)
self.own_network = button("Eigenes Netz", "network", tooltip="Netze dieses Rechners übernehmen",
on_click=self._own_network_menu)
targets.addWidget(self.own_network)
form.addRow("IP-Bereiche", targets)
self.credentials_label = label("", muted=True)
form.addRow("SNMP", self.credentials_label)
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 Drucker ohne zugeordneten Standort – NetBox verlangt für jedes Gerät "
"einen.", muted=True), 1)
form.addRow("Standard-Standort", site_row)
options = QHBoxLayout()
self.counters = checkbox("Seitenzähler && Verbrauchsmaterial in NetBox speichern", True,
tooltip="Benutzerdefinierte Felder am Gerät (werden bei Bedarf angelegt): "
"Seitenzähler, Verbrauchsmaterial, Farbdrucker, letzter Scan")
self.rename = checkbox("Namen vorhandener Geräte aus SNMP übernehmen", False,
tooltip="sysName des Druckers – oft ein Werksname wie NPI1A2B3C")
options.addWidget(self.counters)
options.addWidget(self.rename)
options.addStretch(1)
form.addRow("", options)
source.add(form)
self.body.addWidget(source)
result = Card("Abgleich")
self.models_button = result.add_action(button("Modelle …", "server", on_click=self.edit_models))
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, Modell, 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", 190),
Column("ip", "IP-Adresse", 110),
Column("manufacturer", "Hersteller", 100),
Column("model", "Modell", 190),
Column("serial", "Seriennummer", 130),
Column("mac", "MAC-Adresse", 135),
Column("page_count", "Seiten", 80,
value=lambda row: f"{row['page_count']:,}".replace(",", ".") if row.get("page_count") is not None
else "", sort=lambda row: row.get("page_count") or 0),
Column("supplies", "Verbrauchsmaterial", 220, value=_supplies_short, tooltip=_supplies_tooltip,
color=lambda row: "warning" if _supplies_low(row) else None),
Column("printer_status", "Zustand", 150, value=_status, tooltip=_status_tooltip,
color=lambda row: "warning" if row.get("errors") else "text_muted"),
Column("site_hint", "Standort (SNMP)", 150),
Column("netbox_site", "NetBox-Standort", 180,
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", 140),
Column("netbox_device", "NetBox-Gerät", 160),
Column("method", "Gefunden über", 110, color=lambda row: "text_muted"),
Column("snmp", "SNMP", 150, value=lambda row: row.get("snmp") or ("ohne SNMP" if row.get("ip") else ""),
color=lambda row: "text_muted" if row.get("snmp") else "warning"),
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.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, SNMP-Zugangsdaten prüfen und „Scannen“ wählen. "
"Danach wird automatisch mit NetBox abgeglichen – geschrieben wird erst nach "
"der Vorschau."))
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(self._role_changed)
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.counters.toggled.connect(lambda value: self._store(counters=value))
self.targets.editingFinished.connect(lambda: self._store(targets=self.targets.text().strip()))
self.targets.returnPressed.connect(self.scan)
self.state.profile_switched.connect(self._profile_switched)
self._profile_switched()
# ------------------------------------------------------------------
# Profile settings
# ------------------------------------------------------------------
def _credentials(self):
if not self.state.profile:
return []
return self.state.profile.setdefault("snmp_credentials", [])
def _profile_switched(self):
self.aps, self.only_netbox, self.engine, self.roles, self.others = [], [], None, [], []
self._skipped, self._skipped_models = set(), set()
self.role.set_items([])
self.default_site.set_items([])
settings = self._settings()
for box, key, default in ((self.rename, "rename", False), (self.counters, "counters", True)):
box.blockSignals(True)
box.setChecked(settings.get(key, default))
box.blockSignals(False)
self.targets.setText(settings.get("targets", ""))
self._update_credentials_label()
self._refresh()
def _update_credentials_label(self):
credentials = self._credentials()
if not credentials:
self.credentials_label.setText("Keine Zugangsdaten – es wird die Community „public“ (v2c) versucht.")
return
v2 = sum(1 for item in credentials if item.get("version") != "3")
v3 = [item.get("username", "") for item in credentials if item.get("version") == "3"]
parts = [f"{v2} SNMPv2c-Communit{'y' if v2 == 1 else 'ies'}"] if v2 else []
if v3:
parts.append("SNMPv3: " + ", ".join(v3))
self.credentials_label.setText(" · ".join(parts))
def edit_credentials(self):
if self.state.profile is None:
return
dialog = SnmpCredentialsDialog(self.window, self._credentials())
if dialog.exec():
self.state.profile["snmp_credentials"] = dialog.result
self.state.touch()
self._update_credentials_label()
def on_show(self):
if not self.targets.text().strip():
networks = netscan.local_networks()
if networks:
self.targets.setText(networks[0])
super().on_show()
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 set_busy(self, busy):
scanning = busy and self.scan_task is not None and self.tasks.current is self.scan_task
self.load_button.setText("Stopp" if scanning else "Scannen")
widgets.set_enabled(self.load_button, scanning or not busy, "Bitte warten …")
for widget in (self.sites_button, self.refresh_button, self.credentials_button):
widget.setEnabled(not busy)
self._update_buttons()
def _update_buttons(self):
super()._update_buttons()
widgets.set_enabled(self.models_button, bool(self.engine) and not self.tasks.busy, "Erst mit NetBox abgleichen.")
widgets.set_enabled(self.refresh_button, bool(self.aps) and not self.tasks.busy, "Erst scannen.")
widgets.set_enabled(self.sync_button, bool(self.engine) and not self.tasks.busy,
"Erst scannen." if not self.engine else "Bitte warten …")
# ------------------------------------------------------------------
# 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 or self.state.profile is None:
return
try:
ips = netscan.expand_ips(self.targets.text())
except netscan.ScanError as error:
widgets.message(self.window, "Eingabe prüfen", str(error), "warning")
return
self._store(targets=self.targets.text().strip())
credentials = [dict(item) for item in self._credentials()] or [{"id": "public", "version": "2c",
"community": "public"}]
preferred = dict(self._settings().get("snmp_hosts") or {})
def work(ctx):
ctx.log(f"Scanne {len(ips)} Adressen per SNMP ({len(credentials)} Zugangsdaten) …")
found, done = [], [0]
def on_result(host):
done[0] += 1
ctx.progress(done[0], len(ips), host["ip"])
if host.get("alive"):
found.append(host)
printers.scan(ips, credentials, on_result, lambda: ctx.cancelled, preferred)
ctx.check_cancelled()
return found
def finished(hosts):
items = [printers.to_import(host) for host in hosts if host.get("printer")]
printers.mark_duplicates(items)
self.others = [host for host in hosts if not host.get("printer") and host.get("notes")]
remembered = dict(self._settings().get("snmp_hosts") or {})
remembered.update({host["ip"]: host["credential_id"] for host in hosts if host.get("credential_id")})
self._store(snmp_hosts=remembered)
for host in self.others:
logger("app").warning("%s: %s", host["ip"], "; ".join(host["notes"]))
self.aps, self.only_netbox, self.engine = items, [], None
self.file_name = ""
without = sum(1 for item in items if not item.get("snmp"))
text = f"{len(items)} Drucker gefunden" + (f", {without} ohne SNMP" if without else "") + (
f", {len(self.others)} Gerät{'e' if len(self.others) != 1 else ''} mit SNMP-Problemen (siehe Protokoll)" if self.others else "")
logger("app").log(25, "Drucker-Scan: %s", text)
self.window.toast(text, "warning" if self.others or without else "success")
self._refresh()
# The scan task is still current here; the comparison starts once it has ended.
self._compare_after_scan = self._netbox_ready() and bool(items)
self.scan_task = self.tasks.run(work, title=f"{len(ips)} Adressen nach Druckern 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.set_busy(self.tasks.busy)
if self._compare_after_scan:
self._compare_after_scan = False
self._load_lists(then_compare=True)
# ------------------------------------------------------------------
# NetBox
# ------------------------------------------------------------------
def _mapping_rows(self, new):
"""One row per printer – preset with the choice for its SNMP location, if any."""
return [(" · ".join(filter(None, (printer["name"], printer["ip"], printer.get("model"))))
+ (f" (SNMP-Standort: {printer['site_hint']})" if printer["site_hint"] else ""), 1,
("ap", self.key_func(printer)), self._placement(printer))
for printer in sorted(new, key=lambda item: tuple(int(part) for part in item["ip"].split(".")))]
def _suggest_role(self, roles):
return next((role_id for name, role_id in roles
if any(hint in name.casefold() for hint in self.role_hints)), None)
def _role_changed(self, _index):
self._store(role_id=self.role.valid_data())
if self.engine and not self.tasks.busy:
QTimer.singleShot(0, self.compare) # "only in NetBox" depends on the role
def compare(self):
self._engine_args = {"role_id": self.role.valid_data() or self._settings().get("role_id"),
"counters": self.counters.isChecked()}
super().compare()
def _make_engine(self, nb, log):
return printers.PrinterSyncEngine(nb, log, **self._engine_args)
def _prepare_sync(self):
self.engine.counters = self.counters.isChecked()
self.engine.type_map = {key: value["device_type"] for key, value in self._model_decisions().items()
if value.get("action") == "map" and value.get("device_type")}
return self.engine
# ------------------------------------------------------------------
# Ignoring printers and models
# ------------------------------------------------------------------
def _ignored(self):
return set(self._settings().get("ignored") or [])
def _model_decisions(self):
return dict(self._settings().get("models") or {})
def _model_action(self, printer):
key = printers.model_key(printer)
if key in self._skipped_models:
return "skip"
return self._model_decisions().get(key, {}).get("action")
def _excluded(self, printer):
key = self.key_func(printer)
if key in self._skipped or key in self._ignored():
return True
# a skipped or ignored model only matters for printers that would be created
return not printer.get("device") and self._model_action(printer) in ("skip", "ignore")
def _missing_models(self):
"""``{model key: [printers]}`` of new printers whose device type is not in NetBox."""
if not self.engine:
return {}
missing = {}
for printer in self.aps:
if printer.get("device") or self.key_func(printer) in self._skipped | self._ignored():
continue
if not self.engine.type_exists(printer):
missing.setdefault(printers.model_key(printer), []).append(printer)
return missing
def edit_models(self):
missing = self._missing_models()
if not missing:
self.window.toast("Alle Modelle der neuen Drucker gibt es bereits in NetBox.", "info")
return True
decisions = self._model_decisions()
rows = []
for key, members in sorted(missing.items()):
first = members[0]
decision = dict(decisions.get(key) or {})
if key in self._skipped_models:
decision["action"] = "skip"
text = f"{first.get('manufacturer') or 'Unbekannt'} · {first.get('model') or '(kein Modell – nur Ports)'}"
rows.append((text, len(members), key, decision, self.engine.suggest_type(first)))
dialog = ModelMappingDialog(self.window, rows, self.engine.device_types)
if not dialog.exec():
return False
for key, value in dialog.result.items():
if value["action"] == "skip":
self._skipped_models.add(key)
decisions.pop(key, None)
else:
self._skipped_models.discard(key)
decisions[key] = value
self._store(models=decisions)
self._refresh()
return True
def _set_ignored(self, rows, mode):
keys = {row["key"] for row in rows if not str(row["key"]).startswith("netbox-")}
ignored = self._ignored()
if mode == "skip":
self._skipped |= keys
elif mode == "ignore":
ignored |= keys
self._skipped -= keys
else:
ignored -= keys
self._skipped -= keys
# also release the model of these printers
models = {printers.model_key(row) for row in rows}
self._skipped_models -= models
decisions = self._model_decisions()
for key in models:
if decisions.get(key, {}).get("action") == "ignore":
decisions.pop(key)
self._store(models=decisions)
self._store(ignored=sorted(ignored))
self._refresh()
def _context_menu(self, position):
rows = [self.proxy.row_at(index) for index in self.table.selectionModel().selectedRows()]
rows = [row for row in rows if row and not str(row["key"]).startswith("netbox-")]
if not rows:
return
count = f" ({len(rows)})" if len(rows) > 1 else ""
menu = QMenu(self)
menu.addAction(f"Diesmal ignorieren{count}", lambda: self._set_ignored(rows, "skip"))
menu.addAction(f"Dauerhaft ignorieren{count}", lambda: self._set_ignored(rows, "ignore"))
if any(row["state"] == "ignored" for row in rows):
menu.addAction(f"Nicht mehr ignorieren{count}", lambda: self._set_ignored(rows, "release"))
if self.engine and any(not row.get("device") for row in rows):
menu.addSeparator()
menu.addAction("Modell zuordnen …", self.edit_models)
menu.exec(self.table.viewport().mapToGlobal(position))
def sync(self):
if not self.engine or self.tasks.busy:
return
undecided = [key for key in self._missing_models()
if key not in self._skipped_models and key not in self._model_decisions()]
if undecided and not self.edit_models():
return
super().sync()
def _refresh(self):
if self.engine:
decisions = self._model_decisions()
for printer in self.aps:
printer["issues"] = [issue for issue in printer.get("issues", [])
if not issue.startswith("Modell nicht in NetBox")]
if printer.get("device") or self._excluded(printer) or self.engine.type_exists(printer):
continue
decision = decisions.get(printers.model_key(printer), {})
if decision.get("action") == "map":
name = next((f"{row['manufacturer']} {row['model']}" for row in self.engine.device_types
if row["id"] == decision.get("device_type")), "?")
printer["issues"].append(f"Modell nicht in NetBox – wird als „{name}“ angelegt")
elif decision.get("action") == "create":
printer["issues"].append("Modell nicht in NetBox – Gerätetyp wird neu angelegt")
else:
printer["issues"].append("Modell nicht in NetBox – bitte unter „Modelle …“ entscheiden")
super()._refresh()
if self.others and self.summary.text():
count = len(self.others)
self.summary.setText(self.summary.text() + f" · {count} Gerät{'e' if count != 1 else ''} mit SNMP-Problemen")
+338
View File
@@ -0,0 +1,338 @@
import os
import subprocess
import webbrowser
from PySide6.QtCore import QObject, Qt, QTimer, Signal
from PySide6.QtGui import QGuiApplication
from PySide6.QtWidgets import QFormLayout, QHBoxLayout, QLineEdit, QMenu, QStackedWidget
from netbox_sync.core import netscan
from netbox_sync.ui import widgets
from netbox_sync.ui.icons import icon
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
from netbox_sync.ui.pages import Page
from netbox_sync.ui.tasks import logger
from netbox_sync.ui.theme import theme
from netbox_sync.ui.widgets import Card, EmptyState, SearchField, Table, button, checkbox, label
COMPARE_DOT = {"match": "success", "differs": "warning", "missing": "danger", "offline": "text_faint"}
class _Results(QObject):
"""Carries hosts from the scan threads to the UI thread."""
host = Signal(object)
def _name(row):
return row.get("dns_name") or row.get("netbios_name") or ""
def _netbox(row, key):
return ", ".join(dict.fromkeys(entry[key] for entry in row.get("netbox", []) if entry[key]))
def _services(row):
return ", ".join(f"{item['service'] or 'TCP'} ({item['port']})" for item in row.get("ports", []))
class ScannerPage(Page):
title = "Netzwerk-Scanner"
subtitle = ("IP-Bereiche nach erreichbaren Geräten, Namen, MAC-Adressen und offenen Diensten durchsuchen. "
"Jede Adresse wird automatisch mit NetBox abgeglichen – es wird nichts geschrieben.")
def __init__(self, window):
super().__init__(window)
self.rows = {}
self.netbox = {}
self.netbox_note = ""
self.scan_task = None
self.results = _Results()
self.results.host.connect(self._host_found)
self.refresh_timer = QTimer(self)
self.refresh_timer.setSingleShot(True)
self.refresh_timer.setInterval(250)
self.refresh_timer.timeout.connect(self._refresh)
target_card = Card("Scan")
form = QFormLayout()
form.setHorizontalSpacing(18)
targets = QHBoxLayout()
self.targets = QLineEdit()
self.targets.setPlaceholderText("z. B. 192.168.1.1-254, 10.0.0.0/24, server01")
targets.addWidget(self.targets, 1)
self.own_network = button("Eigenes Netz", "network", tooltip="Netze dieses Rechners übernehmen")
self.own_network.clicked.connect(self._own_network_menu)
targets.addWidget(self.own_network)
form.addRow("IP-Bereiche", targets)
self.ports = QLineEdit()
self.ports.setPlaceholderText(netscan.DEFAULT_PORTS)
form.addRow("Ports", self.ports)
target_card.add(form)
self.scan_button = target_card.add_action(button("Scannen", "play", "primary", on_click=self.scan))
self.body.addWidget(target_card)
result_card = Card("Ergebnisse", "Name aus DNS bzw. NetBIOS; NetBox-Spalten aus den IP-Adressen in NetBox.")
filters = QHBoxLayout()
self.search = SearchField("IP, Name, MAC, Dienst, NetBox-Objekt …")
self.only_alive = checkbox("Nur erreichbare", True)
self.only_issues = checkbox("Nur Abweichungen",
tooltip="Nicht in NetBox, abweichender Name oder in NetBox, aber nicht erreichbar")
filters.addWidget(self.search, 2)
filters.addWidget(self.only_alive)
filters.addWidget(self.only_issues)
filters.addStretch(1)
result_card.add(filters)
columns = [
Column("ip", "IP-Adresse", 130, dot=lambda row: "success" if row.get("alive") else "text_faint"),
Column("name", "Name", 210, value=_name,
tooltip=lambda row: "\n".join(filter(None, (
f"DNS: {row['dns_name']}" if row.get("dns_name") else "",
f"NetBIOS: {row['netbios_name']}" if row.get("netbios_name") else "",
f"Arbeitsgruppe/Domäne: {row['workgroup']}" if row.get("workgroup") else "")))),
Column("mac", "MAC-Adresse", 140),
Column("services", "Dienste", 230, value=_services, tooltip=_services),
Column("rtt", "Antwort", 70, value=lambda row: "" if row.get("rtt") is None else f"{row['rtt']} ms",
sort=lambda row: row.get("rtt") if row.get("rtt") is not None else 99999,
color=lambda row: "text_muted"),
Column("nb_object", "NetBox-Objekt", 190, value=lambda row: _netbox(row, "object"),
tooltip=lambda row: "\n".join(
f"{entry['object_kind'] or 'IP'} {entry['object']} · {entry['vrf'] or 'global'} · "
f"{entry['tenant'] or 'ohne Mandant'} · {entry['status']}"
+ (f"\n{entry['description']}" if entry["description"] else "")
for entry in row.get("netbox", []))),
Column("nb_dns", "NetBox-DNS-Name", 190, value=lambda row: _netbox(row, "dns_name")),
Column("compare", "Abgleich", 170, value=lambda row: netscan.COMPARE_TEXT.get(row.get("compare"), ""),
dot=lambda row: COMPARE_DOT.get(row.get("compare"))),
]
self.model = RowTableModel(columns, row_id=lambda row: row["ip"])
self.proxy = FilterProxy(self.model)
self.table = Table()
self.table.setModel(self.proxy)
for index, column in enumerate(columns):
self.table.setColumnWidth(index, column.width)
self.table.sortByColumn(0, Qt.AscendingOrder)
self.table.doubleClicked.connect(lambda _index: self._open_default())
self.table.setContextMenuPolicy(Qt.CustomContextMenu)
self.table.customContextMenuRequested.connect(self._context_menu)
self.stack = QStackedWidget()
self.stack.addWidget(EmptyState("search", "Noch nicht gescannt",
"IP-Bereiche eintragen und „Scannen“ wählen. Ist ein NetBox-Zugang "
"eingerichtet, erscheinen Objekt und DNS-Name aus NetBox automatisch."))
self.stack.addWidget(self.table)
result_card.add(self.stack, 1)
self.summary = label("", muted=True)
result_card.add(self.summary)
self.body.addWidget(result_card, 1)
self.search.textChanged.connect(self.proxy.set_text)
self.only_alive.toggled.connect(self._apply_filters)
self.only_issues.toggled.connect(self._apply_filters)
self.targets.editingFinished.connect(
lambda: self.state.update_settings(scanner_targets=self.targets.text().strip()))
self.ports.editingFinished.connect(lambda: self.state.update_settings(scanner_ports=self.ports.text().strip()))
self.targets.returnPressed.connect(self.scan)
self.targets.setText(self.state.settings.get("scanner_targets", ""))
self.ports.setText(self.state.settings.get("scanner_ports", ""))
self._apply_filters()
# ------------------------------------------------------------------
def on_show(self):
if not self.targets.text().strip():
networks = netscan.local_networks()
if networks:
self.targets.setText(networks[0])
def set_busy(self, busy):
scanning = busy and self.scan_task is not None and self.tasks.current is self.scan_task
self.scan_button.setText("Stopp" if scanning else "Scannen")
widgets.set_enabled(self.scan_button, scanning or not busy, "Bitte warten …")
def _own_network_menu(self):
networks = netscan.local_networks()
if not networks:
self.window.toast("Kein eigenes IPv4-Netz gefunden.", "info")
return
menu = QMenu(self)
for network in networks:
menu.addAction(network, lambda n=network: self.targets.setText(n))
if len(networks) > 1:
menu.addSeparator()
menu.addAction("Alle", lambda: self.targets.setText(", ".join(networks)))
menu.exec(self.own_network.mapToGlobal(self.own_network.rect().bottomLeft()))
def _apply_filters(self, *_args):
self.proxy.set_predicate("alive", (lambda row: row.get("alive") or row.get("compare") == "offline")
if self.only_alive.isChecked() else None)
self.proxy.set_predicate("issues", (lambda row: row.get("compare") in ("differs", "missing", "offline"))
if self.only_issues.isChecked() else None)
self._update_summary()
def _update_summary(self):
rows = list(self.rows.values())
alive = sum(1 for row in rows if row.get("alive"))
counts = {key: sum(1 for row in rows if row.get("compare") == key) for key in COMPARE_DOT}
parts = [f"{alive} erreichbar"]
if self.netbox_note:
parts.append(self.netbox_note)
else:
parts += [f"{counts['match']} stimmen mit NetBox überein", f"{counts['differs']} abweichend",
f"{counts['missing']} nicht in NetBox", f"{counts['offline']} in NetBox, nicht erreichbar"]
self.summary.setText(" · ".join(parts))
# ------------------------------------------------------------------
# Scan
# ------------------------------------------------------------------
def scan(self):
if self.scan_task is not None and self.tasks.current is self.scan_task:
self.tasks.cancel()
return
if self.tasks.busy:
return
try:
ips = netscan.expand_ips(self.targets.text())
ports = netscan.parse_ports(self.ports.text().strip() or netscan.DEFAULT_PORTS)
except netscan.ScanError as error:
widgets.message(self.window, "Eingabe prüfen", str(error), "warning")
return
self.state.update_settings(scanner_targets=self.targets.text().strip(), scanner_ports=self.ports.text().strip())
compare = bool(self.state.profile) and not self.state.offline and self.state.netbox_configured()
connect = self.actions._connector() if compare else None
self.rows, self.netbox = {}, {}
self.netbox_note = "" if compare else "kein NetBox-Abgleich (kein Zugang im Profil oder Offline-Modus)"
self.model.set_rows([])
self.stack.setCurrentIndex(1)
results = self.results
def work(ctx):
netbox_map, note = {}, ""
if connect:
try:
ctx.progress(0, len(ips), "NetBox-Abgleich …")
netbox_map = netscan.netbox_lookup(connect(ctx), ips)
ctx.log(f"NetBox: {sum(len(items) for items in netbox_map.values())} IP-Adressen in den "
"gescannten Bereichen")
except Exception as error: # noqa: BLE001 - the scan works without NetBox
note = f"NetBox-Abgleich nicht möglich: {error}"
ctx.log(note, "warning")
results.host.emit({"__netbox__": netbox_map, "__note__": note})
ctx.log(f"Scanne {len(ips)} Adressen, {len(ports)} Ports …")
done = [0]
def found(host):
done[0] += 1
ctx.progress(done[0], len(ips), host["ip"])
results.host.emit(host)
netscan.scan(ips, ports, found, lambda: ctx.cancelled)
ctx.check_cancelled()
return len(ips)
def finished(count):
self._finish()
alive = sum(1 for row in self.rows.values() if row.get("alive"))
logger("app").log(25, "Scan abgeschlossen: %s von %s Adressen erreichbar", alive, count)
self.window.toast(f"{alive} von {count} Adressen erreichbar")
self.scan_task = self.tasks.run(work, title=f"{len(ips)} Adressen scannen", area="app",
on_success=finished, on_error=lambda error: widgets.error(
self.window, "Scan fehlgeschlagen", str(error)),
on_finished=self._scan_ended)
self.set_busy(True)
def _scan_ended(self):
self.scan_task = None
self._finish()
self.set_busy(self.tasks.busy)
def _host_found(self, host):
if "__netbox__" in host:
self.netbox = host["__netbox__"]
if host["__note__"]:
self.netbox_note = host["__note__"]
return
row = dict(host, netbox=self.netbox.get(host["ip"], []))
row["compare"] = netscan.compare(row, row["netbox"]) if not self.netbox_note else ""
if row["alive"] or row["netbox"]:
self.rows[row["ip"]] = row
if not self.refresh_timer.isActive():
self.refresh_timer.start()
def _finish(self):
# Documented addresses that never answered are listed as "not reachable".
for ip, entries in self.netbox.items():
if ip not in self.rows:
self.rows[ip] = {"ip": ip, "alive": False, "netbox": entries, "compare": "offline"}
self._refresh()
def _refresh(self):
self.model.set_rows(list(self.rows.values()))
self._update_summary()
# ------------------------------------------------------------------
# Actions on hosts
# ------------------------------------------------------------------
def _selected(self):
rows = self.table.selectionModel().selectedRows()
return [self.proxy.row_at(index) for index in rows]
def _netbox_url(self, entry):
base = (self.state.profile or {}).get("netbox_url", "").rstrip("/")
return f"{base}/ipam/ip-addresses/{entry['id']}/" if base else entry.get("url")
def _open_default(self):
selected = self._selected()
if not selected:
return
row = selected[0]
ports = {item["port"] for item in row.get("ports", [])}
if ports & {443, 8443, 8006}:
port = min(ports & {443, 8443, 8006})
webbrowser.open(f"https://{row['ip']}" + ("" if port == 443 else f":{port}"))
elif ports & {80, 8080}:
port = min(ports & {80, 8080})
webbrowser.open(f"http://{row['ip']}" + ("" if port == 80 else f":{port}"))
elif 3389 in ports:
self._rdp(row)
elif 445 in ports:
os.startfile(f"\\\\{row['ip']}") # noqa: S606 - Windows Explorer
elif row.get("netbox"):
webbrowser.open(self._netbox_url(row["netbox"][0]))
@staticmethod
def _rdp(row):
subprocess.Popen(["mstsc", f"/v:{row['ip']}"]) # noqa: S603, S607 - user action
def _context_menu(self, position):
selected = self._selected()
if not selected:
return
row = selected[0]
ports = {item["port"] for item in row.get("ports", [])}
muted = theme.color("text_muted")
menu = QMenu(self)
for port, scheme in ((443, "https"), (8443, "https"), (8006, "https"), (80, "http"), (8080, "http")):
if port in ports:
suffix = "" if port in (80, 443) else f":{port}"
url = f"{scheme}://{row['ip']}{suffix}"
menu.addAction(icon("globe", muted), f"Im Browser öffnen ({url})", lambda u=url: webbrowser.open(u))
if 3389 in ports:
menu.addAction(icon("monitor", muted), "Remotedesktop verbinden", lambda: self._rdp(row))
if 445 in ports or 139 in ports:
menu.addAction(icon("folder", muted), "Freigaben öffnen",
lambda: os.startfile(f"\\\\{row['ip']}")) # noqa: S606
for entry in row.get("netbox", []):
menu.addAction(icon("upload", muted), f"In NetBox öffnen ({entry['object'] or entry['dns_name'] or 'IP'})",
lambda e=entry: webbrowser.open(self._netbox_url(e)))
if not menu.isEmpty():
menu.addSeparator()
clipboard = QGuiApplication.clipboard()
menu.addAction(icon("copy", muted), "IP-Adresse kopieren",
lambda: clipboard.setText("\n".join(item["ip"] for item in selected)))
if _name(row):
menu.addAction(icon("copy", muted), "Name kopieren", lambda: clipboard.setText(_name(row)))
if row.get("mac"):
menu.addAction(icon("copy", muted), "MAC-Adresse kopieren", lambda: clipboard.setText(row["mac"]))
menu.exec(self.table.viewport().mapToGlobal(position))
+17 -2
View File
@@ -81,6 +81,18 @@ class SettingsPage(Page):
"nicht auf einem anderen Rechner entschlüsselt werden.", muted=True, wrap=True))
self.body.addWidget(data)
updates = Card("Updates", "Neue Versionen kommen aus den Releases von Netbox-Import-Desktop (Gitea).")
line = QHBoxLayout()
self.auto_update = checkbox("Beim Start nach Updates suchen")
line.addWidget(self.auto_update)
line.addStretch(1)
line.addWidget(button("Jetzt nach Updates suchen", "refresh", on_click=lambda: window.updates.check()))
updates.add(line)
updates.add(label("Vor der Installation wird immer gefragt. Die installierte Version aktualisiert sich über "
"das Setup, die portable EXE tauscht sich selbst aus; danach startet die Anwendung neu.",
muted=True, wrap=True))
self.body.addWidget(updates)
about = Card("Über")
about.add(label(f"<b>{APP_NAME}</b> Version {APP_VERSION}"))
about.add(label(f"© {APP_PUBLISHER}", muted=True))
@@ -90,18 +102,21 @@ class SettingsPage(Page):
self.parallel.valueChanged.connect(lambda value: self.state.update_settings(parallel_ssh=value))
self.enable_lldp.toggled.connect(lambda value: self.state.update_settings(enable_lldp=value))
self.parallel_wmi.valueChanged.connect(lambda value: self.state.update_settings(parallel_wmi=value))
self.auto_update.toggled.connect(lambda value: self.state.update_settings(auto_update_check=value))
self.state.settings_changed.connect(self.load)
self.load()
def load(self):
settings = self.state.settings
for widget in (self.parallel, self.parallel_wmi, self.enable_lldp, *self.theme_buttons.values()):
widgets_ = (self.parallel, self.parallel_wmi, self.enable_lldp, self.auto_update, *self.theme_buttons.values())
for widget in widgets_:
widget.blockSignals(True)
self.parallel.setValue(int(settings.get("parallel_ssh", 4)))
self.parallel_wmi.setValue(int(settings.get("parallel_wmi", 8)))
self.enable_lldp.setChecked(bool(settings.get("enable_lldp")))
self.auto_update.setChecked(bool(settings.get("auto_update_check", True)))
self.theme_buttons.get(settings.get("theme", "system"), self.theme_buttons["system"]).setChecked(True)
for widget in (self.parallel, self.parallel_wmi, self.enable_lldp, *self.theme_buttons.values()):
for widget in widgets_:
widget.blockSignals(False)
def _set_theme(self, mode):
+62 -10
View File
@@ -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, vlan_label
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,7 +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(row.get("vlans"))),
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", "")),
@@ -143,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)
@@ -154,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"])
@@ -247,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()
@@ -305,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()
@@ -322,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()
@@ -351,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()
@@ -364,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)
+2
View File
@@ -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
+106
View File
@@ -0,0 +1,106 @@
"""Update check on start and on demand, download and installation."""
import tempfile
import webbrowser
from pathlib import Path
from PySide6.QtCore import QObject, QThreadPool, QTimer
from netbox_sync import APP_VERSION
from netbox_sync.core import updater
from netbox_sync.ui import widgets
from netbox_sync.ui.tasks import Task, logger
class UpdateManager(QObject):
def __init__(self, window):
super().__init__(window)
self.window = window
self.state = window.state
self.tasks = window.tasks
self._check = None
def check_on_start(self):
updater.remove_leftovers()
if self.state.settings.get("auto_update_check", True):
# A moment after start, so the window is usable right away.
QTimer.singleShot(4000, lambda: self.check(silent=True))
def check(self, silent=False):
"""Ask Gitea for a newer release without blocking other tasks."""
if self._check is not None:
return
task = Task(lambda _ctx: updater.check_for_update(), "app", "Nach Updates suchen")
self._check = task
def done(release):
if release is None:
logger("app").info("Keine neuere Version gefunden (installiert: %s)", APP_VERSION)
if not silent:
self.window.toast(f"{APP_VERSION} ist die aktuelle Version.", "info")
return
if silent and self.state.settings.get("skipped_version") == release["version"]:
return
self._offer(release)
def failed(error):
logger("app").warning("Update-Prüfung fehlgeschlagen: %s", error)
if not silent:
widgets.message(self.window, "Update-Prüfung fehlgeschlagen", str(error), "warning")
task.signals.succeeded.connect(done)
task.signals.failed.connect(failed)
task.signals.finished.connect(lambda: setattr(self, "_check", None))
QThreadPool.globalInstance().start(task)
def _offer(self, release):
kind = updater.install_kind()
asset = updater.pick_asset(release, kind) if kind else None
text = (f"Version {release['version']} ist verfügbar (installiert: {APP_VERSION}).\n\n"
+ ("Das Update wird heruntergeladen und installiert; die Anwendung startet danach neu."
if asset else "Für diese Installation gibt es keine passende Datei – bitte die Release-Seite "
"öffnen."))
buttons = ("Später", "Diese Version überspringen", "Jetzt aktualisieren" if asset else "Release-Seite öffnen")
choice = widgets.message(self.window, "Update verfügbar", text, "info", release["notes"] or None,
buttons=buttons, default=2)
if choice == 1:
self.state.update_settings(skipped_version=release["version"])
elif choice == 2 and asset:
self._install(release, kind, *asset)
elif choice == 2 and release["page"]:
webbrowser.open(release["page"])
def _install(self, release, kind, name, asset):
if self.tasks.busy:
widgets.message(self.window, "Bitte warten", f"„{self.tasks.current.title}“ läuft noch. Das Update "
"kann danach über Einstellungen › Updates gestartet werden.", "info")
return
if kind == "portable":
target = updater.portable_download_path()
else:
target = Path(tempfile.mkdtemp(prefix="netbox-sync-update-")) / name
def work(ctx):
ctx.log(f"Lade {name} ({release['version']}) herunter …")
def progress(done, total):
ctx.progress(done // 1024, max(total // 1024, 1), f"{done / 1_048_576:.1f} MB")
return updater.download(asset, target, progress, lambda: ctx.cancelled)
def downloaded(path):
try:
if kind == "portable":
updater.apply_portable(path)
else:
updater.apply_installer(path)
except OSError as error:
widgets.error(self.window, "Update fehlgeschlagen", f"Das Update konnte nicht gestartet werden: "
f"{error}")
return
logger("app").log(25, "Update auf %s wird installiert – Anwendung wird beendet", release["version"])
# After the task has finished, so closing does not ask about a running task.
QTimer.singleShot(0, self.window.close)
self.tasks.run(work, title=f"Update {release['version']} herunterladen", area="app",
on_success=downloaded,
on_error=lambda error: widgets.error(self.window, "Update fehlgeschlagen", str(error)))
+22
View File
@@ -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
View File
@@ -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"
+7
View File
@@ -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"):
@@ -29,6 +31,10 @@ def _matches(record, key, value):
vrf = getattr(record, "vrf", None)
vrf_id = vrf if isinstance(vrf, int) else getattr(vrf, "id", None)
return (vrf_id is None) if value == "null" else vrf_id == value
if key == "contains":
import ipaddress
prefix = getattr(record, "prefix", None)
return prefix is not None and ipaddress.ip_address(value) in ipaddress.ip_network(str(prefix), strict=False)
if key == "address":
return str(getattr(record, "address", "")).split("/")[0] == str(value).split("/")[0]
if key.endswith("_id") and not hasattr(record, key):
@@ -78,3 +84,4 @@ class FakeNetBox:
self.virtualization = SimpleNamespace(clusters=Endpoint(), cluster_types=Endpoint(), virtual_machines=Endpoint(),
interfaces=Endpoint())
self.tenancy = SimpleNamespace(tenants=Endpoint())
self.extras = SimpleNamespace(custom_fields=Endpoint())
+201
View File
@@ -0,0 +1,201 @@
"""Minimal SNMP agent on localhost for tests (v2c and v3 USM)."""
import hmac
import socket
import struct
import threading
from netbox_sync.core import snmp
from netbox_sync.core.snmp import (
AUTH_PROTOCOLS,
GET,
GET_BULK,
GET_NEXT,
INTEGER,
OCTET_STRING,
PRIV_PROTOCOLS,
REPORT,
RESPONSE,
TripleDES,
children,
dec_oid,
dec_value,
decode,
enc_int,
enc_oid,
enc_str,
localize,
oid_key,
password_to_key,
priv_key,
seq,
tlv,
)
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
ENGINE_ID = bytes.fromhex("80001f8880c71100000000000000000001")
def encode_value(value):
if isinstance(value, bool):
return enc_int(int(value))
if isinstance(value, int):
return enc_int(value)
if isinstance(value, tuple) and value[0] == "oid":
return enc_oid(value[1])
if isinstance(value, tuple) and value[0] == "ip":
return tlv(snmp.IP_ADDRESS, bytes(int(part) for part in value[1].split(".")))
if isinstance(value, tuple) and value[0] == "counter":
return enc_int(value[1], snmp.COUNTER32)
return enc_str(value)
class Agent:
def __init__(self, mib, community="public", users=None):
self.mib = {oid.strip("."): value for oid, value in mib.items()}
self.order = sorted(self.mib, key=oid_key)
self.community = community.encode()
self.users = users or {} # name -> credential record
self.boots, self.time = 3, 1000
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind(("127.0.0.1", 0))
self.port = self.sock.getsockname()[1]
self.requests = 0
self._thread = threading.Thread(target=self._serve, daemon=True)
self._thread.start()
def close(self):
self.sock.close()
# MIB --------------------------------------------------------------
def _next(self, oid):
key = oid_key(oid)
return next((item for item in self.order if oid_key(item) > key), None)
def _bindings(self, pdu_type, oids, non_repeaters, repetitions):
result = []
if pdu_type == GET:
for oid in oids:
value = self.mib.get(oid)
result.append(seq(enc_oid(oid), encode_value(value) if value is not None
else tlv(snmp.NO_SUCH_OBJECT, b"")))
else:
count = repetitions if pdu_type == GET_BULK else 1
for oid in oids:
current = oid
for _ in range(max(1, count)):
nxt = self._next(current)
if nxt is None:
result.append(seq(enc_oid(current), tlv(snmp.END_OF_MIB_VIEW, b"")))
break
result.append(seq(enc_oid(nxt), encode_value(self.mib[nxt])))
current = nxt
return seq(*result)
def _response(self, request_id, bindings, kind=RESPONSE):
return tlv(kind, enc_int(request_id) + enc_int(0) + enc_int(0) + bindings)
@staticmethod
def _read_pdu(tag, content):
request_id, a, b, varbinds = children(content)
oids = [dec_oid(children(binding)[0][1]) for _t, binding in children(varbinds[1])]
return tag, dec_value(INTEGER, request_id[1]), dec_value(INTEGER, a[1]), dec_value(INTEGER, b[1]), oids
# serving ----------------------------------------------------------
def _serve(self):
while True:
try:
data, addr = self.sock.recvfrom(65535)
except OSError:
return
self.requests += 1
try:
answer = self._handle(data)
except Exception: # noqa: BLE001 - ignore garbage like a real agent
answer = None
if answer:
self.sock.sendto(answer, addr)
def _handle(self, data):
_tag, content, _pos = decode(data)
items = children(content)
version = dec_value(INTEGER, items[0][1])
if version == 1:
if items[1][1] != self.community:
return None
tag, request_id, a, b, oids = self._read_pdu(*items[2])
bindings = self._bindings(tag, oids, a, b)
return seq(enc_int(1), enc_str(self.community), self._response(request_id, bindings))
return self._handle_v3(data, items)
def _handle_v3(self, data, items):
_v, header, (_t, usm_raw), (data_tag, data_raw) = items
header_items = children(header[1])
msg_id = dec_value(INTEGER, header_items[0][1])
flags = header_items[2][1][0]
_t, usm_content, _p = decode(usm_raw)
engine_id, _boots, _time, user, auth_params, priv_params = (item[1] for item in children(usm_content))
user = bytes(user).decode()
def report(oid):
body = seq(enc_str(ENGINE_ID), enc_str(b""), self._response(
msg_id, seq(seq(enc_oid(oid), enc_int(1, snmp.COUNTER32))), REPORT))
usm = seq(enc_str(ENGINE_ID), enc_int(self.boots), enc_int(self.time), enc_str(user), enc_str(b""),
enc_str(b""))
return seq(enc_int(3), seq(enc_int(msg_id), enc_int(65507), enc_str(b"\x00"), enc_int(3)),
enc_str(usm), body)
if not engine_id:
return report("1.3.6.1.6.3.15.1.1.4.0")
record = self.users.get(user)
if record is None:
return report("1.3.6.1.6.3.15.1.1.3.0")
hash_func, size = AUTH_PROTOCOLS[record["auth_protocol"]]
auth_key = localize(password_to_key(record["auth_password"], hash_func), ENGINE_ID, hash_func)
position = data.find(auth_params)
zeroed = data[:position] + b"\x00" * len(auth_params) + data[position + len(auth_params):]
if not flags & 1 or hmac.new(auth_key, zeroed, hash_func).digest()[:size] != auth_params:
return report("1.3.6.1.6.3.15.1.1.5.0")
protocol = record.get("priv_protocol")
key = priv_key(record["priv_password"], ENGINE_ID, hash_func, PRIV_PROTOCOLS[protocol]) if protocol else None
if data_tag == OCTET_STRING:
plain = self._crypt(protocol, key, bytes(data_raw), bytes(priv_params), _boots, _time, decrypt=True)
_t, scoped, _p = decode(plain)
else:
scoped = data_raw
_ce, _cn, pdu = children(scoped)
tag, request_id, a, b, oids = self._read_pdu(*pdu)
scoped_out = seq(enc_str(ENGINE_ID), enc_str(b""), self._response(request_id, self._bindings(tag, oids, a, b)))
salt = b""
if protocol:
salt = struct.pack(">Q", 99) if protocol != "DES" else struct.pack(">II", self.boots, 77)
encrypted = self._crypt(protocol, key, scoped_out, salt, dec_value(INTEGER, enc_int(self.boots)[2:]),
self.time, decrypt=False)
body = enc_str(encrypted)
else:
body = scoped_out
out_flags = flags & 0x03
def build(params):
usm = seq(enc_str(ENGINE_ID), enc_int(self.boots), enc_int(self.time), enc_str(user), enc_str(params),
enc_str(salt))
return seq(enc_int(3), seq(enc_int(msg_id), enc_int(65507), enc_str(bytes([out_flags])), enc_int(3)),
enc_str(usm), body)
packet = build(b"\x00" * size)
return build(hmac.new(auth_key, packet, hash_func).digest()[:size])
@staticmethod
def _crypt(protocol, key, data, salt, boots, engine_time, decrypt):
if protocol == "DES":
iv = bytes(a ^ b for a, b in zip(key[8:16], salt))
cipher = Cipher(TripleDES(key[:8] * 3), modes.CBC(iv))
if not decrypt:
data += b"\x00" * (-len(data) % 8)
else:
boots = boots if isinstance(boots, int) else dec_value(INTEGER, boots)
engine_time = engine_time if isinstance(engine_time, int) else dec_value(INTEGER, engine_time)
return snmp.aes_cfb(key, struct.pack(">II", boots, engine_time) + salt, data, decrypt)
worker = cipher.decryptor() if decrypt else cipher.encryptor()
return worker.update(data) + worker.finalize()
+118
View File
@@ -0,0 +1,118 @@
"""NetBox Windows Agent protocol v1 against a small in-process agent (same rules as the C# agent)."""
import base64
import hashlib
import hmac
import json
import os
import threading
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, urlparse
import pytest
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from netbox_sync.core import agent_client
from netbox_sync.core.clients import apply_scan, new_row, scan_clients
KEY = "test-key-0123456789abcdef"
INVENTORY = {
"ok": True, "source": "agent", "agent_version": "0.2.0", "name": "pc0815", "domain": "firma.local",
"part_of_domain": True, "manufacturer": "LENOVO", "model": "21MW", "product_name": "21MW",
"product_version": "ThinkBook 16 G7 ARP", "serial": "PW0K84A9", "bios_version": "N3BET", "chassis": [10],
"user": "FIRMA\\anna", "memory": 16 * 1024 ** 3, "cpu": "AMD Ryzen 5", "cores": 6,
"os": "Microsoft Windows 11 Pro", "os_version": "10.0.26100", "os_build": "26100", "os_display_version": "24H2",
"os_architecture": "64-Bit", "installed": "2025-01-01T10:00:00", "last_boot": "2026-11-18T08:00:00",
"nics": [{"name": "Ethernet", "description": "Realtek PCIe GbE", "mac": "84:BA:59:60:C8:B7",
"ips": ["192.168.65.43", "fe80::1"], "masks": ["255.255.255.0", "64"], "gateway": ["192.168.65.1"],
"dhcp": True, "physical": True, "speed": 1000000000},
{"name": "", "description": "OpenVPN", "mac": "", "ips": ["10.8.0.2"], "masks": ["255.255.255.0"],
"gateway": [], "dhcp": False, "physical": False, "speed": 0}],
"disks": [{"device_id": "\\\\.\\PHYSICALDRIVE0", "model": "Samsung SSD", "serial": "S1", "size": 512110190592}],
"memory_modules": [], "software": [{"name": "7-Zip", "version": "24.08", "publisher": "Igor Pavlov"}],
}
class _Handler(BaseHTTPRequestHandler):
seen = set()
def log_message(self, *_args):
pass
def _send(self, status, data):
body = json.dumps(data).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self): # noqa: N802 - http.server API
url = urlparse(self.path)
if url.path == "/v1/info":
return self._send(200, {"agent": "netbox-windows-agent", "version": "0.2.0", "protocol": 1})
query = {key: values[0] for key, values in parse_qs(url.query).items()}
nonce, ts = query.get("nonce", ""), query.get("ts", "0")
if abs(time.time() - int(ts)) > 300:
return self._send(401, {"error": "clock skew too large"})
expected = hmac.new(agent_client.derive_key(KEY, "netbox-agent auth v1"),
f"GET\n/v1/inventory\n{nonce}\n{ts}".encode(), hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, self.headers.get("X-Agent-Signature", "")):
return self._send(401, {"error": "wrong key"})
if nonce in self.seen:
return self._send(401, {"error": "nonce reused"})
self.seen.add(nonce)
iv = os.urandom(12)
data = AESGCM(agent_client.derive_key(KEY, "netbox-agent enc v1")).encrypt(
iv, json.dumps(INVENTORY).encode(), nonce.encode())
self._send(200, {"protocol": 1, "iv": base64.b64encode(iv).decode(), "data": base64.b64encode(data).decode()})
@pytest.fixture
def agent():
server = HTTPServer(("127.0.0.1", 0), _Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
yield server.server_address[1]
server.shutdown()
def test_info_and_encrypted_inventory(agent):
assert agent_client.info("127.0.0.1", agent)["version"] == "0.2.0"
raw = agent_client.query("127.0.0.1", KEY, agent)
assert raw["ok"] and raw["host"] == "127.0.0.1" and raw["serial"] == "PW0K84A9"
def test_wrong_key_is_explained(agent):
raw = agent_client.query("127.0.0.1", "another-key-0123456789", agent)
assert raw == {"host": "127.0.0.1", "ok": False, "error": "Agent-Schlüssel stimmt nicht"}
def test_unreachable_agent_is_reported_not_raised():
raw = agent_client.query("127.0.0.1", KEY, 1, timeout=1)
assert not raw["ok"] and raw["error"].startswith("Agent nicht erreichbar")
def test_agent_inventory_runs_through_the_client_scan(agent):
rows = scan_clients([new_row("127.0.0.1")], query=lambda host: agent_client.query(host, KEY, agent),
port=agent, service="Agent")
row = rows[0]
assert row["status"] == "ok" and row["name"] == "PC0815" and row["source"] == "agent"
# Lenovo: marketing name from the product version, VPN adapter (not physical) left out
assert row["model"] == "ThinkBook 16 G7 ARP" and row["machine_type"] == "21MW"
assert [(item["name"], item["ips"]) for item in row["interfaces"]] == [("Ethernet", ["192.168.65.43/24"])]
assert row["software_count"] == 1 and row["disks"][0]["model"] == "Samsung SSD"
def test_offline_host_names_the_agent_port():
row = scan_clients([new_row("127.0.0.1")], query=lambda host: {}, port=1, service="Agent")[0]
assert row["status"] == "offline" and "Agent-Port 1" in row["message"]
def test_generated_configuration_is_valid_for_the_agent():
key = agent_client.new_scan_key()
config = agent_client.agent_config(key, 8731, ["10.0.0.0/24"])
assert len(key) >= 16 and config["mode"] == "listen" and config["scan_key"] == key
assert config["allowed_networks"] == ["10.0.0.0/24"] and config["listen_port"] == 8731
assert apply_scan(new_row("x"), dict(INVENTORY, host="x"))["os_display_version"] == "24H2"
+152
View File
@@ -0,0 +1,152 @@
import ipaddress
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
def test_ip_goes_into_the_vrf_of_the_tenant_prefix():
nb = _netbox()
vrf = nb.ipam.vrfs.create({"name": "Kunde", "tenant": 7})
nb.ipam.vrfs.create({"name": "Fremd", "tenant": 999})
nb.ipam.prefixes.create({"prefix": "10.0.0.0/8", "vrf": None})
nb.ipam.prefixes.create({"prefix": "0.0.0.0/0", "vrf": None})
for ap in parse_csv(CSV):
if ap["ip"]:
network = ipaddress.ip_network(f"{ap['ip']}/24", strict=False)
if not nb.ipam.prefixes.filter(prefix=str(network)):
nb.ipam.prefixes.create({"prefix": str(network), "vrf": SimpleNamespace(id=vrf.id, name="Kunde")})
engine = APSyncEngine(nb)
engine.load_context(7)
aps = parse_csv(CSV)
engine.match(aps)
report = engine.sync(aps, {ap_key(aps[2]): {"site": 21}}, role_id=30, dry_run=False)
assert report["errors"] == []
created = nb.ipam.ip_addresses.created
assert created and all(payload["vrf"] == vrf.id and payload["address"].endswith("/24") for payload in created)
+151
View File
@@ -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"])
+94
View File
@@ -222,3 +222,97 @@ def test_scan_runs_in_process(monkeypatch):
status = {row["host"]: row["status"] for row in results}
assert status == {"pc01.firma.local": "ok", "off": "offline", "unknown": "offline"}
assert len(seen) == 3
def test_agent_software_goes_into_a_managed_comment_block():
nb, client = _setup()
raw = dict(RAW, source="agent", agent_version="0.2.0",
software=[{"name": "7-Zip", "version": "24.08", "publisher": "Igor Pavlov"},
{"name": "A | B", "version": "", "publisher": ""}],
disks=[{"model": "Micron SSD", "size": 512105932800, "serial": "M1"}],
memory_modules=[{"bank": "DIMM 0", "manufacturer": "Samsung", "part_number": "M425", "capacity": 2 ** 34}])
agent_client = apply_scan(new_row("pc01.firma.local"), raw)
engine = ClientSyncEngine(nb)
engine.load_targets()
preview = engine.sync([agent_client], 1, 2, dry_run=True)
assert "Inventarbericht in den Kommentaren (2 Programme)" in preview["items"][0][1]
engine.sync([agent_client], 1, 2, dry_run=False)
device = nb.dcim.devices.records[0]
assert "| 7-Zip | 24.08 | Igor Pavlov |" in device.comments and "| A / B |" in device.comments
assert "Micron SSD – 512 GB – S/N M1" in device.comments and "DIMM 0: 16 GB Samsung M425" in device.comments
# Hand-written notes survive, an unchanged inventory (only a new scan time) is no update.
device.comments = "Notiz vom Admin\n\n" + device.comments
again = ClientSyncEngine(nb)
again.load_targets()
rescanned = dict(agent_client, scanned_at=agent_client["scanned_at"] + 3600)
assert again.sync([rescanned], 1, 2, dry_run=True)["devices_updated"] == 0
changed = dict(rescanned, software=rescanned["software"] + [{"name": "Firefox", "version": "140", "publisher": ""}])
report = again.sync([changed], 1, 2, dry_run=False)
assert "Inventarbericht aktualisieren (3 Programme)" in report["items"][0][1]
assert device.comments.startswith("Notiz vom Admin") and device.comments.count("<!-- netbox-sync:inventory -->") == 1
assert "| Firefox | 140 | |" in device.comments
def test_winrm_scan_leaves_comments_alone():
nb, client = _setup()
engine = ClientSyncEngine(nb)
engine.load_targets()
engine.sync([client], 1, 2, dry_run=False)
assert "comments" not in nb.dcim.devices.created[0]
def _with_inventory_plugin(nb):
from types import SimpleNamespace
from fake_netbox import Endpoint
nb.plugins = SimpleNamespace(inventory=SimpleNamespace(assets=Endpoint()))
return nb.plugins.inventory.assets
def test_new_client_gets_an_asset_linked_to_the_device():
nb, client = _setup()
assets = _with_inventory_plugin(nb)
agent_row = apply_scan(new_row("pc01.firma.local"), dict(RAW, source="agent", uuid="4C4C-1234",
software=[{"name": "7-Zip", "version": "24", "publisher": ""}]))
engine = ClientSyncEngine(nb)
engine.load_targets()
preview = engine.sync([agent_row], 1, 2, dry_run=True)
assert preview["assets_created"] == 1 and "Asset im Inventory-Plugin anlegen" in preview["items"][0][1]
assert assets.created == []
engine.sync([agent_row], 1, 2, dry_run=False)
device = nb.dcim.devices.records[0]
asset = assets.created[0]
assert asset["serial"] == "PW0K84A9" and asset["device"] == device.id and asset["status"] == "used"
assert asset["device_type"] == device.device_type and asset["description"] == "Windows-Client; UUID 4C4C-1234"
assert "| 7-Zip | 24 | |" in asset["comments"]
again = ClientSyncEngine(nb)
again.load_targets()
report = again.sync([agent_row], 1, 2, dry_run=True)
assert report["assets_created"] == 0 and report["assets_updated"] == 0 and report["items"][0][1] == []
def test_existing_asset_is_linked_and_updated_by_serial():
nb, client = _setup()
assets = _with_inventory_plugin(nb)
assets.records.append(Record(assets, id=500, name="Lager-Notebook", serial="PW0K84A9", status="stored",
device=None, device_type=None, description="", comments="Kaufbeleg 4711"))
engine = ClientSyncEngine(nb)
engine.load_targets()
report = engine.sync([client], 1, 2, dry_run=False)
asset = assets.records[0]
device = nb.dcim.devices.records[0]
assert report["assets_updated"] == 1 and report["assets_created"] == 0
assert asset.device == device.id and asset.status == "used" and asset.name == "PC01"
assert asset.comments == "Kaufbeleg 4711" # WinRM scan: no inventory report, comments untouched
assert any(change.startswith("Asset aktualisieren: Name, Status, Gerätetyp, Gerät") for change in report["items"][0][1])
def test_without_inventory_plugin_no_asset_is_touched():
nb, client = _setup()
engine = ClientSyncEngine(nb)
engine.load_targets()
report = engine.sync([client], 1, 2, dry_run=False)
assert report["errors"] == [] and report["assets_created"] == 0 and engine.asset_endpoint() is None
+341
View File
@@ -0,0 +1,341 @@
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": {}}
# Real "show info" layout: lower-case "Local port", empty values and lines indented after a paging prompt.
REAL_NEIGHBORS = """show info 1-26
Local port : Port 2
Chassis ID : 00-A0-57-00-00-01
Port ID : LAN1
Port Description : LAN1
System Name : AP-005
Management Address : 10.0.0.22 (IPv4)
Management Address : fe80::1 (IPv6)
Local port : Port 12
Chassis ID : PC-020
Port ID : C4-EF-BB-00-00-01
Port Description :
System Name :
System Description :
Local port : Port 25
Chassis ID : MikroTik
Port ID : bridge/ether1
Port Description :
System Name :
System Description : 6.49.17 (stable) MikroTik
Management Address : 192.168.88.3 (IPv4)
SW-08(lldp)# """
def test_real_neighbor_layout():
neighbors = lancom.parse_neighbors(REAL_NEIGHBORS)
assert [(item["local_port"], item["system_name"], item["remote_port"]) for item in neighbors] == [
("2", "AP-005", "LAN1"), ("12", "PC-020", "C4-EF-BB-00-00-01"), ("25", "MikroTik", "bridge/ether1")]
assert neighbors[0]["management_ip"] == "10.0.0.22" and neighbors[1]["port_description"] == ""
def test_prompt_is_no_port_description():
config = PORT_CONFIG.replace("25 Enabled SFP_Auto_AMS Disabled 9600 Discard Disabled\n\n",
"25 Enabled SFP_Auto_AMS Disabled 9600 Discard Disabled\n")
ports = lancom.parse_port_config(config.replace("\nSW-08(port)#", "\n\nSW-08(port)#"))
assert ports[25]["description"] == "" and ports[1]["description"] == "Uplink"
ports = lancom.parse_port_config("26 Enabled Auto Disabled 9600 Discard Disabled\n\n\nSW-08(port)# ")
assert ports[26]["description"] == ""
+87
View File
@@ -0,0 +1,87 @@
import ipaddress
import struct
from types import SimpleNamespace
import pytest
from fake_netbox import FakeNetBox, Record
from netbox_sync.core import netscan
def test_ports_and_ranges_are_parsed():
assert netscan.parse_ports("21-23, 80;443 80") == [21, 22, 23, 80, 443]
with pytest.raises(netscan.ScanError):
netscan.parse_ports("70000")
assert netscan.expand_ips("192.0.2.1-3, 192.0.2.2") == ["192.0.2.1", "192.0.2.2", "192.0.2.3"]
assert len(netscan.expand_ips("192.0.2.0/24")) == 254
with pytest.raises(netscan.ScanError):
netscan.expand_ips("10.0.0.0/16")
def _nbstat_answer(names, mac):
header = b"\x13\x37\x84\x00\x00\x00\x00\x01\x00\x00\x00\x00"
question = b"\x20" + b"CK" + b"A" * 30 + b"\x00" + b"\x00\x21\x00\x01"
entries = b"".join(name.ljust(15).encode() + bytes([suffix]) + struct.pack(">H", flags)
for name, suffix, flags in names)
body = bytes([len(names)]) + entries + mac
return header + question + b"\x00\x00\x00\x00" + struct.pack(">H", len(body)) + body
def test_netbios_answer_gives_name_workgroup_and_mac():
data = _nbstat_answer([("PC-042", 0x00, 0x0400), ("KDS", 0x00, 0x8400), ("PC-042", 0x20, 0x0400)],
bytes.fromhex("001122aabbcc"))
assert netscan.parse_nbstat(data) == ("PC-042", "KDS", "00:11:22:AA:BB:CC")
assert netscan.parse_nbstat(b"\x00" * 10) == ("", "", None)
def test_netbox_entries_are_found_per_block_and_compared():
nb = FakeNetBox()
nb.ipam.ip_addresses.records += [
Record(nb.ipam.ip_addresses, id=1, address="192.0.2.10/24", dns_name="srv01.example.local",
vrf=None, tenant=SimpleNamespace(id=7, name="Muster"), status=SimpleNamespace(label="Aktiv"),
description="", assigned_object=SimpleNamespace(virtual_machine=SimpleNamespace(name="SRV01"))),
Record(nb.ipam.ip_addresses, id=2, address="192.0.2.20/24", dns_name="", vrf=None, tenant=None,
status=SimpleNamespace(label="Aktiv"), description="",
assigned_object=SimpleNamespace(device=SimpleNamespace(name="drucker-3og"))),
Record(nb.ipam.ip_addresses, id=3, address="198.51.100.1/24", dns_name="", vrf=None, tenant=None,
status=None, description="", assigned_object=None),
]
queried = []
def by_parent(parent):
queried.append(parent)
network = ipaddress.ip_network(parent)
return [record for record in nb.ipam.ip_addresses.records
if ipaddress.ip_interface(record.address).ip in network]
nb.ipam.ip_addresses.filter = by_parent
found = netscan.netbox_lookup(nb, ["192.0.2.10", "192.0.2.20", "192.0.2.30"])
assert queried == ["192.0.2.0/24"], "one request per /24"
assert found["192.0.2.10"][0]["object"] == "SRV01" and found["192.0.2.10"][0]["object_kind"] == "VM"
assert found["192.0.2.20"][0]["object"] == "drucker-3og"
assert "192.0.2.30" not in found
alive = {"alive": True, "dns_name": "SRV01.example.local", "netbios_name": "SRV01"}
assert netscan.compare(alive, found["192.0.2.10"]) == "match"
assert netscan.compare(dict(alive, dns_name="pc99", netbios_name=""), found["192.0.2.20"]) == "differs"
assert netscan.compare(alive, []) == "missing"
assert netscan.compare({"alive": False}, found["192.0.2.20"]) == "offline"
assert netscan.compare({"alive": False}, []) == "unknown"
def test_unreachable_host_is_reported_without_details(monkeypatch):
monkeypatch.setattr(netscan, "ping", lambda *_args: None)
monkeypatch.setattr(netscan, "arp_mac", lambda _ip: None)
monkeypatch.setattr(netscan, "tcp_open", lambda *_args: False)
assert netscan.scan_host("192.0.2.1", [80]) == {"ip": "192.0.2.1", "alive": False}
def test_host_behind_firewall_is_found_by_port(monkeypatch):
monkeypatch.setattr(netscan, "ping", lambda *_args: None)
monkeypatch.setattr(netscan, "arp_mac", lambda _ip: None)
monkeypatch.setattr(netscan, "tcp_open", lambda _ip, port, _timeout=0: port in (445, 3389))
monkeypatch.setattr(netscan, "netbios", lambda _ip: ("PC-1", "KDS", "00:11:22:33:44:55"))
monkeypatch.setattr(netscan, "reverse_dns", lambda _ip: "pc-1.kds.local")
host = netscan.scan_host("192.0.2.5", [80, 445, 3389])
assert host["alive"] and [item["port"] for item in host["ports"]] == [445, 3389]
assert host["mac"] == "00:11:22:33:44:55" and host["netbios_name"] == "PC-1"
+183
View File
@@ -0,0 +1,183 @@
from types import SimpleNamespace
import pytest
from fake_netbox import FakeNetBox, Record
from snmp_agent import Agent
from netbox_sync.core import printers, snmp
from netbox_sync.core.printers import PrinterSyncEngine, printer_key, read_printer, supplies_text, to_import
IP = "10.20.0.50"
MIB = {
printers.SYS_DESCR: "HP ETHERNET MULTI-ENVIRONMENT,ROM none,JETDIRECT,JD153,EEPROM JSI24090012",
printers.SYS_OBJECT_ID: ("oid", "1.3.6.1.4.1.11.2.3.9.1"),
printers.SYS_NAME: "NPI1A2B3C",
printers.SYS_LOCATION: "Geschäftsstelle 1. OG",
printers.SYS_CONTACT: "IT",
f"{printers.HR_DEVICE_TYPE}.1": ("oid", printers.HR_PRINTER),
f"{printers.HR_DEVICE_TYPE}.2": ("oid", "1.3.6.1.2.1.25.3.1.4"),
f"{printers.HR_DEVICE_DESCR}.1": "HP Color LaserJet Pro M454dw",
f"{printers.HR_PRINTER_STATUS}.1": 3,
f"{printers.HR_PRINTER_ERRORS}.1": b"\x20\x00", # low toner
f"{printers.PRT_SERIAL}.1": "vnb3k12345",
f"{printers.PRT_LIFE_COUNT}.1.1": ("counter", 48211),
f"{printers.PRT_SUPPLIES}.3.1.1": 1, f"{printers.PRT_SUPPLIES}.3.1.2": 2,
f"{printers.PRT_SUPPLIES}.5.1.1": 21, f"{printers.PRT_SUPPLIES}.5.1.2": 21,
f"{printers.PRT_SUPPLIES}.6.1.1": "Black Cartridge HP W2030A",
f"{printers.PRT_SUPPLIES}.6.1.2": "Cyan Cartridge HP W2031A",
f"{printers.PRT_SUPPLIES}.8.1.1": 2400, f"{printers.PRT_SUPPLIES}.8.1.2": 100,
f"{printers.PRT_SUPPLIES}.9.1.1": 600, f"{printers.PRT_SUPPLIES}.9.1.2": -3,
f"{printers.PRT_COLORANT}.1.1": "black", f"{printers.PRT_COLORANT}.1.2": "cyan",
f"{printers.PRT_INPUT}.9.1.2": 250, f"{printers.PRT_INPUT}.10.1.2": 120,
f"{printers.PRT_INPUT}.13.1.2": "Fach 2",
f"{printers.PRT_DISPLAY}.1.1": "Bereit",
f"{printers.IF_TABLE}.2.2": "eth0", f"{printers.IF_TABLE}.3.2": 6,
f"{printers.IF_TABLE}.6.2": bytes.fromhex("a0b1c2d3e4f5"),
f"{printers.IP_ADDR_IFINDEX}.{IP}": 2,
f"{printers.IP_ADDR_MASK}.{IP}": ("ip", "255.255.255.0"),
"1.3.6.1.2.1.47.1.1.1.1.10.1": "20240115",
}
USER = {"version": "3", "username": "scan", "auth_protocol": "SHA", "auth_password": "authpass123",
"priv_protocol": "AES", "priv_password": "privpass123"}
@pytest.fixture
def agent():
instance = Agent(MIB, community="geheim", users={"scan": USER})
yield instance
instance.close()
def _client(agent, record):
return snmp.SnmpClient("127.0.0.1", record, timeout=0.5, retries=0, port=agent.port)
def test_v2c_get_and_walk(agent):
client = _client(agent, {"version": "2c", "community": "geheim"})
assert client.get([printers.SYS_NAME])[printers.SYS_NAME] == b"NPI1A2B3C"
walked = client.walk(printers.PRT_SUPPLIES)
assert len(walked) == 10 and all(snmp.in_subtree(oid, printers.PRT_SUPPLIES) for oid in walked)
with pytest.raises(snmp.SnmpTimeout):
_client(agent, {"version": "2c", "community": "public"}).get([printers.SYS_NAME])
@pytest.mark.parametrize("auth, priv", [("SHA", "AES"), ("MD5", "DES"), ("SHA-256", "AES-256"), ("SHA-512", ""),
("SHA-224", "AES-192")])
def test_v3_auth_and_privacy(auth, priv):
record = dict(USER, auth_protocol=auth, priv_protocol=priv)
agent = Agent(MIB, users={"scan": record})
try:
client = _client(agent, record)
assert client.get([printers.SYS_NAME])[printers.SYS_NAME] == b"NPI1A2B3C"
assert len(client.walk(printers.PRT_SUPPLIES)) == 10
finally:
agent.close()
def test_connect_tries_all_credentials_and_explains_v3_errors(agent):
wrong_v3 = dict(USER, id="b", auth_password="falsch-falsch")
client, notes = snmp.connect("127.0.0.1", [{"id": "a", "version": "2c", "community": "public"}, wrong_v3,
dict(USER, id="c")], timeout=0.3, retries=0, port=agent.port)
assert client.credential.record["id"] == "c"
assert notes == ["SNMPv3 scan: falsches Authentifizierungs-Passwort oder -Protokoll"]
with pytest.raises(snmp.SnmpAuthError, match="unbekannter Benutzer"):
snmp.connect("127.0.0.1", [dict(USER, username="nobody")], timeout=0.3, retries=0, port=agent.port)
def test_printer_data_is_read_from_standard_mibs(agent):
info = read_printer(_client(agent, {"version": "2c", "community": "geheim"}), IP)
assert info["manufacturer"] == "HP" and info["model"] == "Color LaserJet Pro M454dw"
assert info["serial"] == "VNB3K12345" and info["mac"] == "A0:B1:C2:D3:E4:F5" and info["prefix_length"] == 24
assert info["page_count"] == 48211 and info["color"] is True and info["firmware"] == "20240115"
assert info["site_hint"] == "Geschäftsstelle 1. OG" and info["status"] == "bereit"
assert info["errors"] == ["wenig Toner"] and info["display"] == ["Bereit"]
assert info["trays"] == [{"name": "Fach 2", "media": "", "capacity": 250, "level": "120/250 Blatt"}]
assert supplies_text(info["supplies"]) == "Black Cartridge HP W2030A: 25 %\nCyan Cartridge HP W2031A: vorhanden"
def test_non_printer_is_ignored():
agent = Agent({printers.SYS_NAME: "switch", printers.SYS_OBJECT_ID: ("oid", "1.3.6.1.4.1.9.1.1")})
try:
assert read_printer(_client(agent, {"version": "2c", "community": "public"}), IP) is None
finally:
agent.close()
def _netbox():
nb = FakeNetBox()
nb.tenancy.tenants.records.append(Record(nb.tenancy.tenants, id=7, name="Kunde", group=None))
nb.dcim.sites.records.append(Record(nb.dcim.sites, id=21, name="Geschäftsstelle", tenant=SimpleNamespace(id=7)))
nb.dcim.device_roles.records.append(Record(nb.dcim.device_roles, id=31, name="Drucker"))
old = Record(nb.dcim.devices, id=201, name="Drucker EG", serial="", tenant=SimpleNamespace(id=7),
role=SimpleNamespace(id=31), site=SimpleNamespace(id=21), description="", primary_ip4=None,
custom_fields={"printer_page_count": 100})
nb.dcim.devices.records.append(old)
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=301, name="eth0", device=old, mac_address=None))
nb.ipam.ip_addresses.records.append(Record(nb.ipam.ip_addresses, id=401, address="10.20.0.60/24", vrf=None,
assigned_object_type="dcim.interface",
assigned_object=SimpleNamespace(id=301, device=SimpleNamespace(id=201)),
assigned_object_id=301, tenant=None))
return nb
def test_sync_creates_fields_and_printers_and_updates_counters(agent):
info = read_printer(_client(agent, {"version": "2c", "community": "geheim"}), IP)
new = to_import(dict(info, ip=IP, snmp="SNMPv2c", notes=[]))
known = to_import(dict(info, ip="10.20.0.60", snmp="SNMPv2c", notes=[], serial="", mac="",
name="Drucker EG", page_count=200))
nb = _netbox()
engine = PrinterSyncEngine(nb, role_id=31)
engine.load_context(7)
items = [new, known]
engine.match(items)
assert known["method"] in ("Name", "IP-Adresse") and new.get("device") is None
preview = engine.sync(items, {printer_key(new): {"site": 21, "tenant": 7}}, role_id=31, dry_run=True)
assert preview["errors"] == [] and nb.extras.custom_fields.created == []
assert any("Seitenzähler" in change for change in preview["changes"])
report = engine.sync(items, {printer_key(new): {"site": 21, "tenant": 7}}, role_id=31, dry_run=False)
assert report["errors"] == []
assert {field["name"] for field in nb.extras.custom_fields.created} == {name for name, *_ in printers.CUSTOM_FIELDS}
created = nb.dcim.devices.created[-1]
assert created["name"] == "NPI1A2B3C" and created["serial"] == "VNB3K12345" and "platform" not in created
assert created["custom_fields"]["printer_page_count"] == 48211 and created["custom_fields"]["printer_color"]
assert nb.dcim.manufacturers.created[0]["name"] == "HP"
assert nb.dcim.device_types.created[0]["model"] == "Color LaserJet Pro M454dw"
assert nb.ipam.ip_addresses.created[-1]["address"] == f"{IP}/24"
assert nb.dcim.devices.get(201).custom_fields["printer_page_count"] == 200
def test_hp_jetdirect_model_comes_from_printer_name_not_generic_sysdescr():
mib = {key: value for key, value in MIB.items() if not key.startswith(printers.HR_DEVICE_DESCR)}
mib[printers.HP_DEVICE_ID] = "MFG:Hewlett-Packard;CMD:PJL,PCL;MDL:HP LaserJet M402dn;CLS:PRINTER;"
agent = Agent(mib)
try:
info = read_printer(_client(agent, {"version": "2c", "community": "public"}), IP)
assert info["model"] == "LaserJet M402dn" and info["manufacturer"] == "HP"
mib[f"{printers.PRT_PRINTER_NAME}.1"] = "HP LaserJet Pro M404dn"
finally:
agent.close()
agent = Agent(mib)
try:
assert read_printer(_client(agent, {"version": "2c", "community": "public"}), IP)["model"] == \
"LaserJet Pro M404dn"
finally:
agent.close()
def test_missing_model_can_be_mapped_to_an_existing_device_type():
nb = _netbox()
nb.dcim.manufacturers.records.append(Record(nb.dcim.manufacturers, id=50, name="HP", slug="hp"))
nb.dcim.device_types.records.append(Record(nb.dcim.device_types, id=60, model="LaserJet Pro M404",
manufacturer=SimpleNamespace(id=50, name="HP")))
printer = to_import({"ip": "10.20.0.70", "name": "Drucker24", "manufacturer": "HP", "model": "LaserJet Pro M404dn",
"serial": "PHCLJ40175", "mac": "", "snmp": "SNMPv2c", "notes": []})
engine = PrinterSyncEngine(nb, role_id=31, counters=False)
engine.load_context(7)
engine.match([printer])
assert not engine.type_exists(printer) and engine.suggest_type(printer) == 60
engine.type_map = {printers.model_key(printer): 60}
report = engine.sync([printer], {printer_key(printer): {"site": 21, "tenant": 7}}, role_id=31, dry_run=False)
assert report["errors"] == [] and nb.dcim.device_types.created == []
assert nb.dcim.devices.created[-1]["device_type"] == 60
+516 -7
View File
@@ -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
@@ -134,9 +144,10 @@ def test_missing_vlans_prefixes_and_vrfs_are_only_created_when_approved():
snapshot["vlan_names"] = {20: "Clients"}
plan = plan_switch_sync(nb, switch, snapshot)
assert [(item["vid"], item["netbox_name"], item["name"]) for item in plan["vlans"]] == [
(1, None, "VLAN1"), (10, "Server", "VLAN10"), (20, None, "Clients")]
assert plan["networks"] == [{"network": "10.1.0.0/24", "vrf": "", "existing_vrfs": [], "create": True}]
assert [(item["vid"], item["netbox_id"], item["method"], item["new_name"]) for item in plan["vlans"]] == [
(1, None, "new", "VLAN1"), (10, 110, "vid", "VLAN10"), (20, None, "new", "Clients")]
assert plan["networks"] == [{"network": "10.1.0.0/24", "vrf_id": 0, "vrf_name": "", "existing": [],
"create": True, "stored": False}]
# Not approved: nothing is created, only the existing VLAN 10 is assigned.
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
@@ -146,8 +157,7 @@ def test_missing_vlans_prefixes_and_vrfs_are_only_created_when_approved():
assert nb.dcim.interfaces.get(1).untagged_vlan == 110 and nb.dcim.interfaces.get(1).mode == "access"
assert nb.ipam.ip_addresses.created[0]["tenant"] == 7 and nb.ipam.ip_addresses.created[0]["vrf"] is None
switch.update({"create_vlans": [20], "create_prefixes": ["10.1.0.0/24"],
"network_vrfs": {"10.1.0.0/24": "Kunde-Mgmt"}})
switch.update({"vlan_map": {"20": {"action": "new", "name": "Clients"}}, "network_map": {"10.1.0.0/24": {"vrf_id": None, "vrf_name": "Kunde-Mgmt", "create": True}}})
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert report["errors"] == []
assert nb.ipam.vrfs.created == [{"name": "Kunde-Mgmt", "tenant": 7}]
@@ -170,3 +180,502 @@ def test_vlan_names_are_parsed():
from netbox_sync.core.switches import parse_vlan_names
assert parse_vlan_names('vlan 10\n name "Server"\n exit\nvlan 20\n name Clients\n#\n') == {
10: "Server", 20: "Clients"}
def test_vlans_of_sibling_tenants_are_matched_by_vid_and_name():
nb, switch, snapshot = _numbered_setup()
group = SimpleNamespace(id=3, name="Kunde")
leo = SimpleNamespace(id=8, name="Leo")
nb.ipam.vlans.records += [
Record(nb.ipam.vlans, id=201, vid=2, name="Leo Server", tenant=leo, tenant_group=group),
Record(nb.ipam.vlans, id=202, vid=2, name="Gast", tenant=SimpleNamespace(id=9), tenant_group=group),
Record(nb.ipam.vlans, id=230, vid=30, name="Fremd", tenant=SimpleNamespace(id=99), tenant_group=None),
]
snapshot["interfaces"][0]["vlans"] = {"untagged": [2], "tagged": [], "tagged_all": False}
snapshot["vlan_names"] = {2: "Server_LEO", 30: "Drucker"}
plan = plan_switch_sync(nb, switch, snapshot)
by_vid = {item["vid"]: item for item in plan["vlans"]}
assert (by_vid[2]["netbox_id"], by_vid[2]["method"]) == (201, "name")
assert [candidate["id"] for candidate in by_vid[2]["candidates"]] == [202, 201]
assert by_vid[30]["method"] == "new", "VLANs outside the tenant group are never used"
switch["vlan_map"] = {"30": {"action": "new", "name": "Drucker-Netz"}, "20": {"action": "skip"}}
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert report["errors"] == []
assert nb.ipam.vlans.created == [{"vid": 30, "name": "Drucker-Netz", "status": "active", "tenant": 7}]
assert nb.dcim.interfaces.get(1).untagged_vlan == 201
assert getattr(nb.dcim.interfaces.get(2), "mode", None) is None, "skipped VLAN leaves the port alone"
def test_new_vlan_can_get_another_tenant_of_the_group():
nb, switch, snapshot = _numbered_setup()
group = SimpleNamespace(id=3, name="Kunde")
nb.tenancy.tenants.records.append(Record(nb.tenancy.tenants, id=8, name="Leo", group=group))
nb.tenancy.tenants.records.append(Record(nb.tenancy.tenants, id=9, name="Fremd", group=None))
plan = plan_switch_sync(nb, switch, snapshot)
assert [row["name"] for row in plan["tenants"]] == ["Leo", "Muster"]
assert {item["new_tenant"] for item in plan["vlans"]} == {7}
switch["vlan_map"] = {"10": {"action": "new", "name": "Leo Server", "tenant": 8}}
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert nb.ipam.vlans.created == [{"vid": 10, "name": "Leo Server", "status": "active", "tenant": 8}]
# NetBox resolves the tenant group through the tenant; the fake needs it set.
nb.ipam.vlans.records[-1].tenant_group = group
again = plan_switch_sync(nb, switch, snapshot)["vlans"][0]
assert (again["netbox_id"], again["method"]) == (nb.ipam.vlans.records[-1].id, "manual"), "never created twice"
def test_ignored_vlans_are_left_out_everywhere():
nb, switch, snapshot = _numbered_setup()
nb.ipam.vlans.records.append(Record(nb.ipam.vlans, id=110, vid=10, name="Server", tenant=SimpleNamespace(id=7)))
snapshot["interfaces"][0]["vlans"] = {"untagged": [10], "tagged": [20, 30], "tagged_all": False}
switch["vlan_map"] = {"20": {"action": "ignore"}, "30": {"action": "new", "name": "Drucker"}}
plan = plan_switch_sync(nb, switch, snapshot)
by_vid = {item["vid"]: item for item in plan["vlans"]}
assert (by_vid[20]["method"], by_vid[20]["stored"]) == ("ignore", True)
assert by_vid[10]["stored"] is False
assert {item["name"]: item["vlan_label"] for item in plan["interfaces"]}["1/1/1"] == "10,30"
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert report["errors"] == []
assert [payload["vid"] for payload in nb.ipam.vlans.created] == [30]
port = nb.dcim.interfaces.get(1)
assert port.label == "10,30" and port.tagged_vlans == [nb.ipam.vlans.records[-1].id]
def test_vlan_decisions_move_from_switches_to_the_profile(tmp_path):
from netbox_sync.core.config import ProfileStore
store = ProfileStore(tmp_path / "config.json")
profile = {"name": "Kunde", "switches": [{"id": "s", "name": "sw", "password": "x",
"vlan_map": {"5": {"action": "ignore"}}, "create_vlans": [6]}]}
store.save({"Kunde": profile}, "Kunde")
loaded = store.load()[0]["Kunde"]
assert loaded["vlan_map"] == {"5": {"action": "ignore"}}
assert "vlan_map" not in loaded["switches"][0] and "create_vlans" not in loaded["switches"][0]
def test_vrfs_of_the_tenant_group_are_offered_and_found():
nb, switch, snapshot = _numbered_setup()
group = SimpleNamespace(id=3, name="Kunde")
rz = SimpleNamespace(id=8, name="RZ")
nb.ipam.vrfs.records += [
Record(nb.ipam.vrfs, id=60, name="Mgmt", tenant=rz, tenant_group=group),
Record(nb.ipam.vrfs, id=61, name="Fremd", tenant=SimpleNamespace(id=99), tenant_group=None),
]
nb.ipam.prefixes.records.append(Record(nb.ipam.prefixes, id=70, prefix="10.10.167.0/24", vrf=SimpleNamespace(id=60)))
snapshot["interfaces"][0]["ip_addresses"] = ["10.10.167.5/24"]
plan = plan_switch_sync(nb, switch, snapshot)
assert plan["vrfs"] == [{"id": 60, "label": "Mgmt (RZ)"}], "group VRFs only"
assert plan["networks"][0] == {"network": "10.10.167.0/24", "vrf_id": 60, "vrf_name": "", "existing": [60],
"create": True, "stored": False}
switch["network_map"] = {"10.10.167.0/24": {"vrf_id": 60, "vrf_name": "", "create": False}}
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert report["errors"] == [] and report["prefixes_created"] == 0 and nb.ipam.vrfs.created == []
assert nb.ipam.ip_addresses.created[0]["vrf"] == 60
assert plan_switch_sync(nb, switch, snapshot)["networks"][0]["stored"] is True
def test_legacy_network_choices_still_work_and_migrate(tmp_path):
nb, switch, snapshot = _numbered_setup()
snapshot["interfaces"][0]["ip_addresses"] = ["10.1.0.1/24"]
switch.update({"network_vrfs": {"10.1.0.0/24": ""}, "create_prefixes": ["10.1.0.0/24"]})
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
assert report["prefixes_created"] == 1
from netbox_sync.core.config import ProfileStore
store = ProfileStore(tmp_path / "config.json")
store.save({"Kunde": {"name": "Kunde", "switches": [dict(switch, password="x")]}}, "Kunde")
loaded = store.load()[0]["Kunde"]
assert loaded["network_map"] == {"10.1.0.0/24": {"vrf_id": None, "vrf_name": "", "create": True}}
assert "network_vrfs" not in loaded["switches"][0]
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)"]
def test_skipped_cables_are_explained():
nb, switch, snapshot = _numbered_setup()
report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True)
assert report["cables_created"] == 0
assert any("nicht in NetBox gefunden" in note for note in report["notes"])
switch["neighbor_devices"] = {"1/1/2": 0} # "no cable" is chosen deliberately: no note
report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True)
assert not any("übersprungen" in note for note in report["notes"])
def test_wireless_interfaces_are_no_cable_targets():
"""LANCOM LW-600: eth1 plus wlan0/wlan1; LLDP reports "LAN1" – wlan1 must not make it ambiguous."""
nb, switch, snapshot = _numbered_setup()
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=5, name="AP-005", tenant=SimpleNamespace(id=7)))
nb.dcim.interfaces.records += [
Record(nb.dcim.interfaces, id=50, name="eth1", device=SimpleNamespace(id=5), mac_address=None,
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None),
Record(nb.dcim.interfaces, id=51, name="wlan0", device=SimpleNamespace(id=5), mac_address=None,
type=SimpleNamespace(value="ieee802.11ax"), enabled=True, cable=None),
Record(nb.dcim.interfaces, id=52, name="wlan1", device=SimpleNamespace(id=5), mac_address=None,
type=SimpleNamespace(value="ieee802.11ax"), enabled=True, cable=None),
]
snapshot["neighbors"][0].update(system_name="AP-005", remote_port="LAN1", port_description="LAN1")
report = sync_snapshot_to_netbox(nb, switch, snapshot)
assert report["errors"] == []
assert nb.dcim.cables.created[0]["b_terminations"] == [{"object_type": "dcim.interface", "object_id": 50}]
def _ap_with_two_ports():
nb, switch, snapshot = _numbered_setup()
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=5, name="AP-005", tenant=SimpleNamespace(id=7)))
nb.dcim.interfaces.records += [
Record(nb.dcim.interfaces, id=50, name="eth1", device=SimpleNamespace(id=5), mac_address=None,
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None),
Record(nb.dcim.interfaces, id=51, name="eth2", device=SimpleNamespace(id=5), mac_address=None,
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None),
Record(nb.dcim.interfaces, id=52, name="wlan0", device=SimpleNamespace(id=5), mac_address=None,
type=SimpleNamespace(value="ieee802.11ax"), enabled=True, cable=None),
]
snapshot["neighbors"][0].update(system_name="AP-005", remote_port="Uplink", port_description="")
return nb, switch, snapshot
def test_far_end_interface_can_be_chosen():
nb, switch, snapshot = _ap_with_two_ports()
plan = plan_switch_sync(nb, switch, snapshot)
neighbor = plan["neighbors"][0]
assert [item["name"] for item in neighbor["interfaces"]] == ["eth1", "eth2"] # no Wi-Fi
assert neighbor["suggested_interface"] is None and neighbor["interface_id"] is None
report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True)
assert report["cables_created"] == 0 and any("keine passende Schnittstelle" in n for n in report["notes"])
switch["neighbor_interfaces"] = {"1/1/2": 51}
assert plan_switch_sync(nb, switch, snapshot)["neighbors"][0]["interface_id"] == 51
sync_snapshot_to_netbox(nb, switch, snapshot)
assert nb.dcim.cables.created[0]["b_terminations"] == [{"object_type": "dcim.interface", "object_id": 51}]
def test_chosen_interface_of_another_device_is_ignored():
nb, switch, snapshot = _ap_with_two_ports()
switch["neighbor_interfaces"] = {"1/1/2": 20} # belongs to server-01, not AP-005
assert plan_switch_sync(nb, switch, snapshot)["neighbors"][0]["interface_id"] is None
report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True)
assert report["cables_created"] == 0
+75
View File
@@ -0,0 +1,75 @@
import sys
import pytest
from netbox_sync.core import updater
RELEASE = {
"tag_name": "v4.7.0", "name": "Netbox-Import-Desktop v4.7.0", "body": "- neu", "draft": False,
"prerelease": False, "html_url": "https://example.invalid/releases/tag/v4.7.0",
"assets": [
{"name": "NetBox VM Import.exe", "size": 4, "browser_download_url": "https://example.invalid/portable"},
{"name": "NetBoxSynchronizer-Setup-4.7.0.exe", "size": 4, "browser_download_url": "https://example.invalid/setup"},
],
}
class _Response:
def __init__(self, payload=None, chunks=(), length=None):
self.payload, self.chunks = payload, chunks
self.headers = {"Content-Length": str(length)} if length else {}
def raise_for_status(self):
return None
def json(self):
return self.payload
def iter_content(self, _size):
return iter(self.chunks)
def __enter__(self):
return self
def __exit__(self, *_args):
return False
def test_versions_are_compared_numerically():
assert updater.parse_version("v4.10.0") > updater.parse_version("4.9.3")
assert updater.parse_version("v5") == (5, 0, 0)
def test_newer_release_is_offered_with_matching_assets(monkeypatch):
monkeypatch.setattr(updater.requests, "get", lambda *_a, **_k: _Response(RELEASE))
release = updater.check_for_update("4.6.0")
assert release["version"] == "4.7.0" and release["notes"] == "- neu"
assert updater.pick_asset(release, "portable")[0] == "NetBox VM Import.exe"
assert updater.pick_asset(release, "installer")[0] == "NetBoxSynchronizer-Setup-4.7.0.exe"
assert updater.check_for_update("4.7.0") is None
monkeypatch.setattr(updater.requests, "get", lambda *_a, **_k: _Response(dict(RELEASE, prerelease=True)))
assert updater.check_for_update("4.6.0") is None
def test_incomplete_download_is_discarded(monkeypatch, tmp_path):
monkeypatch.setattr(updater.requests, "get", lambda *_a, **_k: _Response(chunks=[b"ab"]))
with pytest.raises(updater.UpdateError):
updater.download({"url": "x", "size": 4}, tmp_path / "setup.exe")
assert list(tmp_path.iterdir()) == []
monkeypatch.setattr(updater.requests, "get", lambda *_a, **_k: _Response(chunks=[b"ab", b"cd"]))
target = updater.download({"url": "x", "size": 4}, tmp_path / "setup.exe")
assert target.read_bytes() == b"abcd"
def test_portable_exe_is_swapped_and_restarted(monkeypatch, tmp_path):
exe = tmp_path / "NetBox VM Import.exe"
exe.write_bytes(b"old")
new = tmp_path / "NetBox VM Import.new.exe"
new.write_bytes(b"new")
started = []
monkeypatch.setattr(sys, "executable", str(exe))
monkeypatch.setattr(updater.subprocess, "Popen", lambda args, **_kwargs: started.append(args))
updater.apply_portable(new)
assert exe.read_bytes() == b"new" and not new.exists()
assert (tmp_path / "NetBox VM Import.old.exe").read_bytes() == b"old"
assert started == [[str(exe)]]