feat: UniFi switch, access point and Network controller drivers, read paths (NetOrk/netork#2787) #1
No files matched your search
@@ -0,0 +1,26 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to these drivers. The format follows
|
||||
[Keep a Changelog](https://keepachangelog.com/), versions follow
|
||||
[Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- `unifi_switch` and `unifi_ap` drivers for UniFi switches and access points.
|
||||
They read through the controller that manages them (a UniFi OS console with an
|
||||
API key or a local login, or a standalone Network application) or over SSH
|
||||
without one: facts, ports, the management address, LLDP, the MAC table (over
|
||||
SSH), PoE and VLANs with their ports (switch), SSIDs, radios and wireless
|
||||
clients (access point).
|
||||
- `unifi_network` driver for the UniFi Network application. It names the devices
|
||||
it manages in every site or one, including devices waiting for adoption
|
||||
(Network 10 and later), through the Integration API or, without it, the classic
|
||||
API. Each adopted switch and access point names its driver (`unifi_switch`,
|
||||
`unifi_ap`) and the args that reach it through the controller.
|
||||
- The controller's certificate and the device's SSH host key are trusted on first
|
||||
use, and a changed one is refused before any login.
|
||||
- Discovery by Ubiquiti's OUIs (switch, access point) and the controller's web page.
|
||||
- A simulator (`sim/unifi_sim`, not part of the package): a controller on HTTPS
|
||||
(UniFi OS or standalone, by version) and a switch on SSH. The drivers are
|
||||
tested against it end to end.
|
||||
@@ -0,0 +1,122 @@
|
||||
# napalm-ubiquiti
|
||||
|
||||
NAPALM drivers for Ubiquiti UniFi, built on
|
||||
[napalm-device-types](https://git.netork.io/NAPALM/napalm-device-types).
|
||||
|
||||
| Driver | Class | Role |
|
||||
|---|---|---|
|
||||
| `unifi_switch` | `UnifiSwitchDriver` | `SwitchDriver`: a UniFi switch (USW) |
|
||||
| `unifi_ap` | `UnifiAccessPointDriver` | `AccessPointDriver`: a UniFi access point (UAP, U6, U7) |
|
||||
| `unifi_network` | `UnifiNetworkDriver` | `NetworkControllerDriver`: the UniFi Network application itself |
|
||||
|
||||
Each switch and access point is a device of its own. It is read through the
|
||||
controller that manages it, or over SSH when there is none (or none to be
|
||||
trusted with the key). The controller is a device too: it names what it
|
||||
manages, so the layer above can link or add those devices.
|
||||
|
||||
## Tested against
|
||||
|
||||
| What | Versions |
|
||||
|---|---|
|
||||
| Classic API answers | US-16-150W, US-8 and UAP-AC-Pro on 4.0.x, USW Flex Mini 1.8.4: recorded answers from aiounifi's test data |
|
||||
| Device over SSH | US-24 (Gen1) on 7.1.26: recorded output from abates/napalm-unifi's test data |
|
||||
| Integration API | Network 10.6.106: answer shapes from Ubiquiti's published OpenAPI description |
|
||||
|
||||
Not yet against a device or a controller of our own (see
|
||||
`tests/fixtures/README.md`). Every driver runs against the simulator in `sim/`
|
||||
(a controller on HTTPS, a switch on SSH, both from these fixtures) in the test
|
||||
suite, over real TLS and SSH. The versions it plays are 9.1, 10.x and a
|
||||
standalone controller.
|
||||
|
||||
## Connection
|
||||
|
||||
### A switch or access point through its controller
|
||||
|
||||
```python
|
||||
from napalm import get_network_driver
|
||||
|
||||
driver = get_network_driver("unifi_switch")
|
||||
args = {"controller_url": "https://192.0.2.1", "token_value": "<API key>"}
|
||||
with driver("192.0.2.20", "", "", optional_args=args) as switch:
|
||||
print(switch.get_vlans_detail())
|
||||
```
|
||||
|
||||
The hostname is the device's management address; it finds the device on the
|
||||
controller, or `mac` names it.
|
||||
|
||||
| Controller | URL | Credential |
|
||||
|---|---|---|
|
||||
| UniFi OS console (UDM, UCG, Cloud Key Gen2+, UniFi OS Server), Network 9.0.108 and later | `https://<console>` | an API key (Settings → Control Plane → Integrations), as `token_value` or `api_secret` |
|
||||
| Same, older | `https://<console>` | a local admin's username and password |
|
||||
| Standalone Network application | `https://<host>:8443` | a local admin's username and password |
|
||||
|
||||
A cloud account with multi-factor authentication cannot log in through the API.
|
||||
Use a local admin or an API key. Logins are rate-limited by the controller. After
|
||||
too many, the driver raises `RateLimited` with the wait and does not retry.
|
||||
|
||||
### A switch or access point over SSH
|
||||
|
||||
Without `controller_url`, the driver reads the device over SSH with the device
|
||||
SSH credentials its controller gave it (the controller's *Device SSH
|
||||
Authentication* setting), or the factory login of a device never adopted. Over
|
||||
SSH it only reads. A switch over SSH reports each port's
|
||||
untagged VLAN, but not the VLANs a port carries tagged.
|
||||
|
||||
### The controller
|
||||
|
||||
```python
|
||||
driver = get_network_driver("unifi_network")
|
||||
with driver("192.0.2.1", "", "", optional_args={"token_value": "<API key>"}) as controller:
|
||||
print(controller.get_managed_devices())
|
||||
```
|
||||
|
||||
### Optional args
|
||||
|
||||
| Arg | Drivers | |
|
||||
|---|---|---|
|
||||
| `controller_url` | switch, AP | the controller; without it the device is read over SSH |
|
||||
| `transport` | switch, AP | `controller` or `ssh`, to override that default |
|
||||
| `token_value` / `api_secret` | all | the controller's API key |
|
||||
| `controller_username` / `controller_password` | switch, AP | a controller login separate from the device's own |
|
||||
| `site` | all | the site's short name (`default`). For a device: the site it is in. For the controller: only that site's devices |
|
||||
| `mac` | switch, AP | the device's MAC on the controller, instead of finding it by its address |
|
||||
| `port` | controller | 443 (UniFi OS, default) or 8443 (standalone) |
|
||||
| `ssh_username`, `ssh_password`, `ssh_private_key_str`, `ssh_port`, `key_file` | switch, AP | the SSH login, when it is not the driver's username and password |
|
||||
| `tls_fingerprints`, `tls_certificate_observer`, `ssl_verify` | all | the controller's certificate: trusted on first use and pinned, or checked against a CA too |
|
||||
| `ssh_host_keys`, `ssh_host_key_observer` | switch, AP | the device's SSH host key: trusted on first use, a changed one refused before any login |
|
||||
|
||||
## Supported
|
||||
|
||||
| Getter | Switch | AP | Controller |
|
||||
|---|---|---|---|
|
||||
| `get_facts` | ✓ | ✓ | the Network application's version |
|
||||
| `get_interfaces`, `get_interfaces_ip` | ports as `Port <n>`, plus `Management` | same | none: its ports are its devices' |
|
||||
| `get_lldp_neighbors`, `get_lldp_neighbors_detail` | ✓ | ✓ | – |
|
||||
| `get_mac_address_table` | over SSH (a controller does not report the tables) | – | – |
|
||||
| `get_poe_status` | ✓ | – | – |
|
||||
| `get_vlans_detail`, `get_vlans` | through the controller: port overrides, port profiles, defaults; over SSH: untagged only | – | – |
|
||||
| `get_ssids` | – | ✓, with security from the controller | – |
|
||||
| `get_radio_status`, `get_wireless_clients` | – | ✓ | – |
|
||||
| `get_managed_devices` | – | – | Integration API (with devices waiting for adoption on 10.x), else the classic API. Each adopted switch and AP names its driver and the args that reach it through this controller |
|
||||
| Discovery | Ubiquiti OUIs | Ubiquiti OUIs | the web page on 443/8443 |
|
||||
|
||||
## Not supported (yet)
|
||||
|
||||
Writes (VLANs, WLANs, port VLANs) are not supported. Also missing: gateways
|
||||
(UDM/UCG/USG as routers), UniFi Protect, Access and Talk, adoption, firmware
|
||||
upgrades, and devices without SSH (USW Flex Mini, USW Ultra), which can only be
|
||||
read through a controller.
|
||||
|
||||
## Development
|
||||
|
||||
The rules are in [STANDARDS.md](https://git.netork.io/NAPALM/driver-standard/src/branch/main/STANDARDS.md).
|
||||
How UniFi stores a port's VLANs is in [docs/PORT_VLANS.md](docs/PORT_VLANS.md).
|
||||
|
||||
```bash
|
||||
python -m venv .venv && .venv/bin/pip install -e ".[dev]"
|
||||
.venv/bin/pytest --cov
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0
|
||||
@@ -0,0 +1,61 @@
|
||||
# How a UniFi switch port's VLANs are stored
|
||||
|
||||
What the driver relies on when it reads a port's VLANs from the controller and,
|
||||
later, writes them. Sources: go-unifi's generated structs per controller version
|
||||
(`unifi/device.generated.go`, `unifi/port_profile.generated.go`, read at
|
||||
`01866ea`, 10.6.109), terraform-provider-unifi `unifi/device_tagged_networks.go`
|
||||
(`ad90c73`), sirkirby/unifi-mcp `switch_manager.py` (`ab0d5fe`). MPL-2.0 sources
|
||||
were read, not copied.
|
||||
|
||||
## Networks (`rest/networkconf`)
|
||||
|
||||
- A network can be tagged on a switch port when its `purpose` is `corporate`,
|
||||
`guest` or `vlan-only`. `wan`, `remote-user-vpn`, `site-vpn` and `vpn-client`
|
||||
are not switch VLANs.
|
||||
- Its VLAN ID is `vlan` when `vlan_enabled` is true. The Default LAN carries no
|
||||
`vlan`: it is VLAN 1 (the controller refuses `vlan: 1`).
|
||||
|
||||
## Where a port's VLANs live, by controller version
|
||||
|
||||
| Controller | Port profile (`rest/portconf`) | Per port (`device.port_overrides[]`) |
|
||||
|---|---|---|
|
||||
| 7.2–7.3 | `forward` (`all`, `native`, `customize`, `disabled`), `native_networkconf_id`, `tagged_networkconf_ids` | `portconf_id` only: VLANs come from a profile |
|
||||
| 7.4 | `excluded_networkconf_ids` replaces `tagged_networkconf_ids` | `native_networkconf_id`, `excluded_networkconf_ids`, `forward` |
|
||||
| 8.2 – 10.x | adds `tagged_vlan_mgmt` (`auto`, `block_all`, `custom`) | adds `tagged_vlan_mgmt` |
|
||||
|
||||
## The effective VLANs of a port
|
||||
|
||||
1. The port's entry in `port_overrides` (by `port_idx`), if any.
|
||||
2. Otherwise, or for a field the override leaves out, the port profile named by
|
||||
`portconf_id` (the override's, else the port's in `port_table`).
|
||||
3. Otherwise the default: the Default LAN untagged, every taggable network tagged.
|
||||
|
||||
Native (untagged): `native_networkconf_id`, else the Default LAN.
|
||||
|
||||
Tagged:
|
||||
|
||||
| `tagged_vlan_mgmt` | `forward` (older) | Tagged networks |
|
||||
|---|---|---|
|
||||
| `auto` | `all` | every taggable network but the native one |
|
||||
| `block_all` | `native` | none |
|
||||
| `custom` | `customize` | every taggable network but the native one and `excluded_networkconf_ids` (older: exactly `tagged_networkconf_ids`) |
|
||||
| — | `disabled` | none, and no native either |
|
||||
|
||||
## Writing (later stage)
|
||||
|
||||
- `PUT /api/s/<site>/rest/device/<_id>` with `{"port_overrides": [...]}`
|
||||
**replaces the whole array**: a port left out returns to its defaults. Read the
|
||||
device right before, change one entry, write all, read again. Serialise writes
|
||||
per device.
|
||||
- A tagged list is not stored on a port override (checked by the terraform
|
||||
provider on 9.5.21, 10.0.162, 11.0.103): write `tagged_vlan_mgmt: custom` plus
|
||||
the complement as `excluded_networkconf_ids`. The native network cannot be
|
||||
excluded (`api.err.NativeVlanCannotBeExcluded`).
|
||||
- Keep `forward` in step: `block_all` → `native`, `custom` → `customize`, `auto`
|
||||
→ `all`.
|
||||
- Manual VLAN fields and a profile are exclusive in practice: a manual port has no
|
||||
`portconf_id`.
|
||||
- `setting_preference` is not a profile-vs-manual switch; round-trip the
|
||||
controller's value.
|
||||
- The Integration API has no port VLAN write (its only port action is
|
||||
`POWER_CYCLE`), so port VLANs go through the classic API on every version.
|
||||
@@ -0,0 +1,7 @@
|
||||
"""NAPALM drivers for Ubiquiti UniFi: switches, access points and the Network controller."""
|
||||
|
||||
from napalm_ubiquiti.access_point import UnifiAccessPointDriver
|
||||
from napalm_ubiquiti.controller import UnifiNetworkDriver
|
||||
from napalm_ubiquiti.switch import UnifiSwitchDriver
|
||||
|
||||
__all__ = ["UnifiAccessPointDriver", "UnifiNetworkDriver", "UnifiSwitchDriver"]
|
||||
@@ -0,0 +1,33 @@
|
||||
"""A UniFi access point (UAP/U6/U7), through its controller or over SSH."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from napalm_device_types import AccessPointDriver
|
||||
from napalm_device_types.access_point_models import (
|
||||
RadioStatusDict,
|
||||
SSIDDict,
|
||||
WirelessClientDict,
|
||||
)
|
||||
|
||||
from napalm_ubiquiti.device import UnifiDevice
|
||||
from napalm_ubiquiti.identity import OUI_PREFIXES
|
||||
from napalm_ubiquiti.parsers.wireless import parse_radios, parse_ssids
|
||||
|
||||
|
||||
class UnifiAccessPointDriver(UnifiDevice, AccessPointDriver):
|
||||
"""A UniFi access point. Its WLANs' settings come from its controller only."""
|
||||
|
||||
DRIVER_NAME = "unifi_ap"
|
||||
OUI_PREFIXES = OUI_PREFIXES
|
||||
REBOOT_SETTLE_SECONDS = 90
|
||||
|
||||
def get_ssids(self) -> dict[str, SSIDDict]:
|
||||
source = self._source()
|
||||
return parse_ssids(source.record(), source.wlans() or None)
|
||||
|
||||
def get_radio_status(self) -> dict[str, RadioStatusDict]:
|
||||
return parse_radios(self._record())
|
||||
|
||||
def get_wireless_clients(self) -> list[WirelessClientDict]:
|
||||
source = self._source()
|
||||
return source.wireless_clients(source.record())
|
||||
@@ -0,0 +1,227 @@
|
||||
"""One HTTP session with a UniFi Network controller.
|
||||
|
||||
A UniFi OS console (UDM, UCG, Cloud Key Gen2+, UniFi OS Server) serves the
|
||||
Network application under ``/proxy/network``: the documented Integration API at
|
||||
``/proxy/network/integration/v1`` and the classic API at
|
||||
``/proxy/network/api/s/<site>/...``. An API key (``X-API-KEY``, Network 9.0.108
|
||||
and later) opens both. A standalone Network application (no UniFi OS) has only the
|
||||
classic API at ``/api/s/<site>/...`` and only a local login.
|
||||
|
||||
Redirects are never followed: a key must not travel to wherever a 302 points.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
from napalm.base.exceptions import ConnectionException
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
|
||||
UNIFI_OS_LOGIN = "/api/auth/login"
|
||||
STANDALONE_LOGIN = "/api/login"
|
||||
UNIFI_OS_CLASSIC = "/proxy/network/api"
|
||||
STANDALONE_CLASSIC = "/api"
|
||||
INTEGRATION = "/proxy/network/integration/v1"
|
||||
CSRF_HEADER = "X-CSRF-Token"
|
||||
CSRF_UPDATED = "X-Updated-Csrf-Token"
|
||||
KEY_HEADER = "X-API-KEY"
|
||||
PAGE_LIMIT = 200
|
||||
DEFAULT_TIMEOUT = 30.0
|
||||
DEFAULT_RETRY_AFTER = 300
|
||||
MFA_STATUS = 499
|
||||
NO_SITE = "api.err.NoSiteContext"
|
||||
|
||||
|
||||
class UnifiError(Exception):
|
||||
"""The controller answered, but not with what was asked for."""
|
||||
|
||||
|
||||
class NotFound(UnifiError):
|
||||
"""The endpoint does not exist here: an older controller, or no Integration API."""
|
||||
|
||||
|
||||
class SiteNotFound(UnifiError):
|
||||
"""The controller has no site by that name (``api.err.NoSiteContext``)."""
|
||||
|
||||
|
||||
class RateLimited(ConnectionException):
|
||||
"""The controller refuses logins for a while; retrying at once prolongs that."""
|
||||
|
||||
def __init__(self, message: str, retry_after: int) -> None:
|
||||
super().__init__(message)
|
||||
self.retry_after = retry_after
|
||||
|
||||
|
||||
def _error_text(response: Any) -> str:
|
||||
try:
|
||||
body = response.json()
|
||||
except ValueError:
|
||||
return str(response.text or "")[:200]
|
||||
if isinstance(body, dict):
|
||||
meta = body.get("meta") or {}
|
||||
return str(meta.get("msg") or body.get("code") or body.get("message") or body)
|
||||
return str(body)[:200]
|
||||
|
||||
|
||||
class UnifiClient:
|
||||
"""A session with the controller at *base_url* (``https://host[:port]``)."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str,
|
||||
*,
|
||||
api_key: str = "",
|
||||
username: str = "",
|
||||
password: str = "",
|
||||
session: Any = None,
|
||||
timeout: float = DEFAULT_TIMEOUT,
|
||||
) -> None:
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.api_key = api_key
|
||||
self.username = username
|
||||
self.password = password
|
||||
self.timeout = timeout
|
||||
self.session = session if session is not None else requests.Session()
|
||||
#: A key exists only on UniFi OS; a login tells the two apart.
|
||||
self.unifi_os = bool(api_key)
|
||||
if api_key:
|
||||
self.session.headers[KEY_HEADER] = api_key
|
||||
|
||||
# -- transport ---------------------------------------------------------
|
||||
|
||||
def _send(self, method: str, path: str, **kwargs: Any) -> Any:
|
||||
try:
|
||||
response = self.session.request(
|
||||
method,
|
||||
f"{self.base_url}{path}",
|
||||
timeout=self.timeout,
|
||||
allow_redirects=False,
|
||||
**kwargs,
|
||||
)
|
||||
except requests.RequestException as exc:
|
||||
raise ConnectionException(f"{self.base_url}: {exc}") from exc
|
||||
token = response.headers.get(CSRF_UPDATED) or response.headers.get(CSRF_HEADER)
|
||||
if token:
|
||||
self.session.headers[CSRF_HEADER] = token
|
||||
return response
|
||||
|
||||
def _check(self, response: Any, path: str) -> Any:
|
||||
status = response.status_code
|
||||
if 300 <= status < 400:
|
||||
raise UnifiError(f"{self.base_url}{path}: answered with a redirect; not followed")
|
||||
if status == 404:
|
||||
raise NotFound(f"{self.base_url}{path}: not found")
|
||||
text = _error_text(response)
|
||||
if NO_SITE in text:
|
||||
raise SiteNotFound(f"{self.base_url}: no site by that name ({path})")
|
||||
if status in (401, 403):
|
||||
what = "the API key" if self.api_key else "the session"
|
||||
raise ConnectionException(f"{self.base_url}: refused {what} ({status} {text})")
|
||||
if status >= 400:
|
||||
raise UnifiError(f"{self.base_url}{path}: {status} {text}")
|
||||
return response.json()
|
||||
|
||||
def _request(self, method: str, path: str, **kwargs: Any) -> Any:
|
||||
return self._check(self._send(method, path, **kwargs), path)
|
||||
|
||||
# -- login -------------------------------------------------------------
|
||||
|
||||
def login(self) -> None:
|
||||
"""Log in with the username and password; with an API key there is nothing to do."""
|
||||
if self.api_key:
|
||||
return
|
||||
if not (self.username and self.password):
|
||||
raise ConnectionException(
|
||||
f"{self.base_url}: give an API key or a local admin's username and password"
|
||||
)
|
||||
self.unifi_os = self._is_unifi_os()
|
||||
body = {"username": self.username, "password": self.password}
|
||||
if self.unifi_os:
|
||||
self._check_login(self._send("POST", UNIFI_OS_LOGIN, json={**body, "remember": True}))
|
||||
return
|
||||
self._check_login(self._send("POST", STANDALONE_LOGIN, json=body))
|
||||
csrf = getattr(self.session, "cookies", {}).get("csrf_token")
|
||||
if csrf:
|
||||
self.session.headers[CSRF_HEADER] = csrf
|
||||
|
||||
def _is_unifi_os(self) -> bool:
|
||||
"""UniFi OS serves its own page at ``/``; a standalone Network application
|
||||
redirects to ``/manage``. (aiounifi tells them apart the same way.)"""
|
||||
status = self._send("GET", "/").status_code
|
||||
if status == 200:
|
||||
return True
|
||||
if 300 <= status < 400:
|
||||
return False
|
||||
raise ConnectionException(f"{self.base_url}: answers {status} at /; no UniFi controller")
|
||||
|
||||
def _check_login(self, response: Any) -> None:
|
||||
status = response.status_code
|
||||
if 300 <= status < 400:
|
||||
raise ConnectionException(f"{self.base_url}: the login answered with a redirect")
|
||||
if status == 429:
|
||||
wait = int(response.headers.get("Retry-After") or DEFAULT_RETRY_AFTER)
|
||||
raise RateLimited(f"{self.base_url}: too many logins; wait {wait} s", wait)
|
||||
if status == MFA_STATUS:
|
||||
raise ConnectionException(
|
||||
f"{self.base_url}: this account needs multi-factor authentication; "
|
||||
"use a local admin account or an API key"
|
||||
)
|
||||
if status >= 400:
|
||||
raise ConnectionException(
|
||||
f"{self.base_url}: login refused ({status} {_error_text(response)})"
|
||||
)
|
||||
|
||||
# -- classic API -------------------------------------------------------
|
||||
|
||||
def _classic(self, path: str) -> str:
|
||||
return f"{UNIFI_OS_CLASSIC if self.unifi_os else STANDALONE_CLASSIC}{path}"
|
||||
|
||||
def _classic_data(self, body: Any, path: str) -> list[Any]:
|
||||
meta = (body.get("meta") or {}) if isinstance(body, dict) else {}
|
||||
if meta.get("rc") == "error": # a wrong site never gets here: _check saw it
|
||||
raise UnifiError(f"{self.base_url}{path}: {meta.get('msg') or ''}")
|
||||
return list(body.get("data") or []) if isinstance(body, dict) else []
|
||||
|
||||
def classic_get(self, site: str, endpoint: str) -> list[Any]:
|
||||
"""``GET /api/s/<site>/<endpoint>``: the ``data`` list."""
|
||||
path = self._classic(f"/s/{site}/{endpoint}")
|
||||
return self._classic_data(self._request("GET", path), path)
|
||||
|
||||
def classic_write(self, method: str, site: str, endpoint: str, body: Any) -> list[Any]:
|
||||
"""``POST``/``PUT``/``DELETE`` on the classic API: the ``data`` list it returns."""
|
||||
path = self._classic(f"/s/{site}/{endpoint}")
|
||||
return self._classic_data(self._request(method, path, json=body), path)
|
||||
|
||||
def classic_sites(self) -> list[Any]:
|
||||
"""The sites the account can see (``/api/self/sites``)."""
|
||||
path = self._classic("/self/sites")
|
||||
return self._classic_data(self._request("GET", path), path)
|
||||
|
||||
# -- Integration API ---------------------------------------------------
|
||||
|
||||
def _integration(self, endpoint: str) -> str:
|
||||
if not self.unifi_os:
|
||||
raise NotFound(f"{self.base_url}: a standalone controller has no Integration API")
|
||||
return f"{INTEGRATION}/{endpoint}"
|
||||
|
||||
def integration_get(self, endpoint: str, params: dict[str, Any] | None = None) -> Any:
|
||||
"""``GET /v1/<endpoint>`` of the Integration API."""
|
||||
return self._request("GET", self._integration(endpoint), params=params)
|
||||
|
||||
def integration_list(self, endpoint: str) -> list[Any]:
|
||||
"""Every item of a paged Integration API list."""
|
||||
items: list[Any] = []
|
||||
while True:
|
||||
page = self.integration_get(endpoint, {"offset": len(items), "limit": PAGE_LIMIT})
|
||||
data = list(page.get("data") or [])
|
||||
items.extend(data)
|
||||
if not data or len(items) >= int(page.get("totalCount") or 0):
|
||||
return items
|
||||
|
||||
def application_version(self) -> tuple[int, ...]:
|
||||
"""The Network application's version, e.g. ``(10, 6, 106)``."""
|
||||
version = str(self.integration_get("info").get("applicationVersion") or "")
|
||||
return tuple(int(part) for part in version.split(".") if part.isdigit())
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Reaching a UniFi Network controller from the arguments a driver is given.
|
||||
|
||||
Credentials, as netOrk hands them over:
|
||||
|
||||
* an ``api_token`` profile: the key's secret in ``token_value`` or ``api_secret``
|
||||
(its name, in ``token_name``/``api_key``, is not used);
|
||||
* otherwise a local admin's login: ``controller_username``/``controller_password``,
|
||||
else the driver's own username and password.
|
||||
|
||||
The controller's certificate is trusted on first use and pinned for the session
|
||||
(:class:`napalm_device_types.tls_certificates.CertificateCheck`): a console's
|
||||
certificate is self-signed, so no CA is asked unless ``ssl_verify`` is set.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import requests
|
||||
from napalm.base.exceptions import ConnectionException
|
||||
from napalm_device_types.tls_certificates import CertificateCheck
|
||||
|
||||
from napalm_ubiquiti.client import UnifiClient
|
||||
|
||||
HTTPS_PORT = 443
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ControllerLogin:
|
||||
api_key: str
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
def controller_login(username: str, password: str, args: Mapping[str, Any]) -> ControllerLogin:
|
||||
"""The credentials for the controller, from the driver's login and *args*."""
|
||||
key = str(args.get("token_value") or args.get("api_secret") or "")
|
||||
if key:
|
||||
return ControllerLogin(key, "", "")
|
||||
user = str(args.get("controller_username") or "")
|
||||
if user:
|
||||
return ControllerLogin("", user, str(args.get("controller_password") or ""))
|
||||
return ControllerLogin("", username, password)
|
||||
|
||||
|
||||
def host_and_port(base_url: str) -> tuple[str, int]:
|
||||
parts = urlsplit(base_url)
|
||||
return parts.hostname or "", parts.port or HTTPS_PORT
|
||||
|
||||
|
||||
def open_controller(
|
||||
base_url: str,
|
||||
login: ControllerLogin,
|
||||
args: Mapping[str, Any],
|
||||
timeout: float,
|
||||
session: Any = None,
|
||||
) -> UnifiClient:
|
||||
"""A logged-in client for the controller at *base_url*, its certificate verified."""
|
||||
if urlsplit(base_url).scheme != "https":
|
||||
raise ConnectionException(f"{base_url}: a controller is reached over https only")
|
||||
host, port = host_and_port(base_url)
|
||||
check = CertificateCheck(args, host, port)
|
||||
check.verify_server(timeout)
|
||||
session = session if session is not None else requests.Session()
|
||||
session.verify = bool(args.get("ssl_verify", False))
|
||||
check.pin(session)
|
||||
client = UnifiClient(
|
||||
base_url,
|
||||
api_key=login.api_key,
|
||||
username=login.username,
|
||||
password=login.password,
|
||||
session=session,
|
||||
timeout=timeout,
|
||||
)
|
||||
with check.refusing():
|
||||
client.login()
|
||||
check.observe()
|
||||
return client
|
||||
@@ -0,0 +1,192 @@
|
||||
"""The UniFi Network controller as a device of its own: what it is, and what it manages.
|
||||
|
||||
A UniFi OS console (UDM, UCG, Cloud Key Gen2+, UniFi OS Server) or a standalone
|
||||
Network application. Its switches and access points are devices of their own,
|
||||
each read by its own driver; this driver names them
|
||||
(:meth:`~UnifiNetworkDriver.get_managed_devices`) so netOrk can link or create
|
||||
them, and reads none of their ports.
|
||||
|
||||
Optional args
|
||||
-------------
|
||||
port : int
|
||||
The controller's HTTPS port: 443 (UniFi OS, the default) or 8443 (standalone).
|
||||
token_value / api_secret : str
|
||||
An API key (UniFi OS, Network 9.0.108 and later). Without one, the driver's
|
||||
username and password log in: a local admin, as a cloud account with MFA
|
||||
cannot log in here.
|
||||
site : str
|
||||
Only this site's devices (its short name, e.g. ``default``); default: all sites.
|
||||
tls_fingerprints, tls_certificate_observer, ssl_verify
|
||||
The certificate to expect, where to report the one seen, and whether a CA
|
||||
must vouch for it too (``napalm_device_types.tls_certificates``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from napalm.base.exceptions import ConnectionException
|
||||
from napalm.base.models import FactsDict, InterfaceDict, InterfacesIPDict
|
||||
from napalm_device_types import FingerprintRule, NetworkControllerDriver, PortSpec
|
||||
from napalm_device_types.lldp import LldpNeighborDict
|
||||
from napalm_device_types.network_controller_models import ManagedDeviceDict
|
||||
|
||||
from napalm_ubiquiti.client import NotFound, UnifiClient
|
||||
from napalm_ubiquiti.connection import HTTPS_PORT, controller_login, open_controller
|
||||
from napalm_ubiquiti.parsers.device import VENDOR
|
||||
from napalm_ubiquiti.parsers.managed import (
|
||||
managed_from_classic,
|
||||
managed_from_integration,
|
||||
managed_from_pending,
|
||||
)
|
||||
|
||||
MODEL = "UniFi Network"
|
||||
#: The driver that polls each role a controller reports; a gateway has none yet.
|
||||
DRIVERS = {"switch": "unifi_switch", "access_point": "unifi_ap"}
|
||||
STANDALONE_PORT = 8443
|
||||
DEFAULT_SITE = "default"
|
||||
|
||||
|
||||
class UnifiNetworkDriver(NetworkControllerDriver):
|
||||
"""A UniFi Network controller, through its API: no SSH."""
|
||||
|
||||
VENDOR = VENDOR
|
||||
DRIVER_NAME = "unifi_network"
|
||||
USES_SSH = False
|
||||
PORT_SPECS = [
|
||||
PortSpec("https", HTTPS_PORT, ("/",), weight=3.0),
|
||||
PortSpec("https", STANDALONE_PORT, ("/manage",), weight=3.0),
|
||||
]
|
||||
HTTP_FINGERPRINT = [FingerprintRule("unifi", weight=8.0, mandatory=True)]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hostname: str,
|
||||
username: str,
|
||||
password: str,
|
||||
timeout: int = 60,
|
||||
optional_args: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
self.hostname = hostname
|
||||
self.username = username
|
||||
self.password = password
|
||||
self.timeout = timeout
|
||||
self.optional_args = dict(optional_args or {})
|
||||
self.port = int(self.optional_args.get("port") or HTTPS_PORT)
|
||||
self.site = str(self.optional_args.get("site") or "")
|
||||
self.client: Any = None
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
host = f"[{self.hostname}]" if ":" in self.hostname else self.hostname
|
||||
return f"https://{host}:{self.port}"
|
||||
|
||||
# -- connection --------------------------------------------------------
|
||||
|
||||
def open(self) -> None:
|
||||
login = controller_login(self.username, self.password, self.optional_args)
|
||||
self.client = open_controller(self.url, login, self.optional_args, self.timeout)
|
||||
|
||||
def close(self) -> None:
|
||||
if self.client is not None:
|
||||
self.client.session.close()
|
||||
self.client = None
|
||||
|
||||
def is_alive(self) -> dict[str, bool]:
|
||||
return {"is_alive": self.client is not None}
|
||||
|
||||
def _client(self) -> UnifiClient:
|
||||
if self.client is None:
|
||||
raise ConnectionException(f"{self.hostname}: the connection is not open")
|
||||
return self.client # type: ignore[no-any-return]
|
||||
|
||||
# -- the controller itself ---------------------------------------------
|
||||
|
||||
def _version(self) -> str:
|
||||
client = self._client()
|
||||
try:
|
||||
return str(client.integration_get("info").get("applicationVersion") or "")
|
||||
except NotFound:
|
||||
info = client.classic_get(self.site or DEFAULT_SITE, "stat/sysinfo")
|
||||
return str(info[0].get("version") or "") if info else ""
|
||||
|
||||
def get_facts(self) -> FactsDict:
|
||||
return {
|
||||
"vendor": VENDOR,
|
||||
"model": MODEL,
|
||||
"hostname": self.hostname,
|
||||
"fqdn": self.hostname,
|
||||
"os_version": self._version(),
|
||||
"serial_number": "",
|
||||
"uptime": -1.0,
|
||||
"interface_list": [],
|
||||
}
|
||||
|
||||
def get_interfaces(self) -> dict[str, InterfaceDict]:
|
||||
"""None: a console's ports are a gateway's or a switch's, read by that driver."""
|
||||
return {}
|
||||
|
||||
def get_interfaces_ip(self) -> dict[str, InterfacesIPDict]:
|
||||
return {}
|
||||
|
||||
def get_lldp_neighbors(self) -> dict[str, list[LldpNeighborDict]]:
|
||||
return {}
|
||||
|
||||
# -- what it manages ---------------------------------------------------
|
||||
|
||||
def get_managed_devices(self) -> list[ManagedDeviceDict]:
|
||||
try:
|
||||
devices = self._integration_devices()
|
||||
except NotFound:
|
||||
devices = self._classic_devices()
|
||||
return [self._with_driver(device) for device in devices]
|
||||
|
||||
def _with_driver(self, device: ManagedDeviceDict) -> ManagedDeviceDict:
|
||||
"""An adopted device's driver, and the args that reach it through this controller."""
|
||||
driver = DRIVERS.get(device["role"])
|
||||
if driver and device["state"] != "pending":
|
||||
device["driver"] = driver
|
||||
device["driver_args"] = {
|
||||
"transport": "controller",
|
||||
"controller_url": self.url,
|
||||
"site": device["site"],
|
||||
"mac": device["mac"],
|
||||
}
|
||||
return device
|
||||
|
||||
def _integration_devices(self) -> list[ManagedDeviceDict]:
|
||||
client = self._client()
|
||||
sites = {
|
||||
str(site["id"]): str(site.get("internalReference") or "")
|
||||
for site in client.integration_list("sites")
|
||||
if not self.site or site.get("internalReference") == self.site
|
||||
}
|
||||
devices = [
|
||||
managed_from_integration(device, name)
|
||||
for site_id, name in sites.items()
|
||||
for device in client.integration_list(f"sites/{site_id}/devices")
|
||||
]
|
||||
return devices + self._pending_devices(sites)
|
||||
|
||||
def _pending_devices(self, sites: dict[str, str]) -> list[ManagedDeviceDict]:
|
||||
"""Devices waiting for adoption into one of *sites* (Network 10.0 and later)."""
|
||||
try:
|
||||
pending = self._client().integration_list("pending-devices")
|
||||
except NotFound:
|
||||
return []
|
||||
found = []
|
||||
for device in pending:
|
||||
targets = [sites[i] for i in device.get("adoptionTargetSiteIds") or [] if i in sites]
|
||||
if targets:
|
||||
found.append(managed_from_pending(device, targets[0]))
|
||||
return found
|
||||
|
||||
def _classic_devices(self) -> list[ManagedDeviceDict]:
|
||||
client = self._client()
|
||||
names = [str(site.get("name") or "") for site in client.classic_sites()]
|
||||
return [
|
||||
managed_from_classic(record, name)
|
||||
for name in names
|
||||
if name and (not self.site or name == self.site)
|
||||
for record in client.classic_get(name, "stat/device")
|
||||
]
|
||||
@@ -0,0 +1,184 @@
|
||||
"""What a UniFi switch and a UniFi access point share: how they are reached and read.
|
||||
|
||||
:class:`UnifiDevice` goes before the role base in a concrete driver
|
||||
(``UnifiSwitchDriver(UnifiDevice, SwitchDriver)``), so its getters win over
|
||||
NAPALM's ``NotImplementedError``.
|
||||
|
||||
Optional args
|
||||
-------------
|
||||
transport : "controller" | "ssh"
|
||||
Where the readings come from. Default: the controller when ``controller_url``
|
||||
is given, else the device over SSH.
|
||||
controller_url : str
|
||||
The controller, e.g. ``https://192.0.2.1`` (UniFi OS) or
|
||||
``https://unifi.lan:8443`` (a standalone Network application).
|
||||
token_value / api_secret : str
|
||||
An API key of the controller (UniFi OS, Network 9.0.108 and later).
|
||||
controller_username / controller_password : str
|
||||
A local admin of the controller, when there is no key. Without them the
|
||||
driver's own username and password log in.
|
||||
site : str
|
||||
The controller's short site name (default ``default``).
|
||||
mac : str
|
||||
The device's MAC on the controller; without it the device is found by its
|
||||
management address (the driver's hostname).
|
||||
ssh_username / ssh_password / ssh_private_key_str / ssh_port : str, int
|
||||
A separate SSH login; otherwise the driver's own, with ``key_file``.
|
||||
tls_fingerprints, tls_certificate_observer, ssh_host_keys, ssh_host_key_observer
|
||||
The controller's certificate and the device's host key to expect, and where
|
||||
to report what was seen (``napalm_device_types``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pathlib
|
||||
from typing import Any
|
||||
|
||||
from napalm.base.exceptions import ConnectionException
|
||||
from napalm.base.models import (
|
||||
FactsDict,
|
||||
InterfaceDict,
|
||||
InterfacesIPDict,
|
||||
LLDPNeighborDetailDict,
|
||||
MACAdressTable,
|
||||
)
|
||||
from napalm_device_types.lldp import LldpNeighborDict, lldp_neighbors, lldp_neighbors_detail
|
||||
|
||||
from napalm_ubiquiti.connection import controller_login, open_controller
|
||||
from napalm_ubiquiti.parsers.device import (
|
||||
VENDOR,
|
||||
parse_facts,
|
||||
parse_interfaces,
|
||||
parse_interfaces_ip,
|
||||
parse_lldp_rows,
|
||||
parse_mac_table,
|
||||
)
|
||||
from napalm_ubiquiti.sources import ControllerSource, Record, SshSource
|
||||
from napalm_ubiquiti.ssh import DEFAULT_PORT, SshShell
|
||||
|
||||
CONTROLLER = "controller"
|
||||
SSH = "ssh"
|
||||
DEFAULT_SITE = "default"
|
||||
|
||||
|
||||
class UnifiDevice:
|
||||
"""One UniFi switch or access point, through its controller or over SSH."""
|
||||
|
||||
VENDOR = VENDOR
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hostname: str,
|
||||
username: str,
|
||||
password: str,
|
||||
timeout: int = 60,
|
||||
optional_args: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
self.hostname = hostname
|
||||
self.username = username
|
||||
self.password = password
|
||||
self.timeout = timeout
|
||||
self.optional_args = dict(optional_args or {})
|
||||
self.controller_url = _https(str(self.optional_args.get("controller_url") or ""))
|
||||
self.transport = str(
|
||||
self.optional_args.get("transport") or (CONTROLLER if self.controller_url else SSH)
|
||||
)
|
||||
if self.transport not in (CONTROLLER, SSH):
|
||||
raise ConnectionException(f"transport {self.transport!r}: use controller or ssh")
|
||||
if self.transport == CONTROLLER and not self.controller_url:
|
||||
raise ConnectionException("the controller transport needs controller_url")
|
||||
self.source: ControllerSource | SshSource | None = None
|
||||
self._closable: Any = None
|
||||
|
||||
# -- connection --------------------------------------------------------
|
||||
|
||||
def open(self) -> None:
|
||||
"""Connect, and read the device once: a refused key or an unknown device fails here."""
|
||||
source = self._open_controller() if self.transport == CONTROLLER else self._open_ssh()
|
||||
try:
|
||||
source.record()
|
||||
except BaseException:
|
||||
self._close_transport()
|
||||
raise
|
||||
self.source = source
|
||||
|
||||
def _open_controller(self) -> ControllerSource:
|
||||
args = self.optional_args
|
||||
login = controller_login(self.username, self.password, args)
|
||||
client = open_controller(self.controller_url, login, args, self.timeout)
|
||||
self._closable = client.session
|
||||
site = str(args.get("site") or DEFAULT_SITE)
|
||||
if args.get("mac"):
|
||||
return ControllerSource(client, site, str(args["mac"]))
|
||||
return ControllerSource.find(client, site, self.hostname)
|
||||
|
||||
def _open_ssh(self) -> SshSource:
|
||||
args = self.optional_args
|
||||
shell = SshShell(
|
||||
self.hostname,
|
||||
username=str(args.get("ssh_username") or self.username),
|
||||
password=str(args.get("ssh_password") or self.password or ""),
|
||||
private_key=_private_key(args),
|
||||
port=int(args.get("ssh_port") or args.get("port") or DEFAULT_PORT),
|
||||
optional_args=args,
|
||||
timeout=self.timeout,
|
||||
)
|
||||
shell.open()
|
||||
self._closable = shell
|
||||
return SshSource(shell)
|
||||
|
||||
def close(self) -> None:
|
||||
self._close_transport()
|
||||
self.source = None
|
||||
|
||||
def _close_transport(self) -> None:
|
||||
if self._closable is not None:
|
||||
self._closable.close()
|
||||
self._closable = None
|
||||
|
||||
def is_alive(self) -> dict[str, bool]:
|
||||
return {"is_alive": self.source is not None}
|
||||
|
||||
def _source(self) -> ControllerSource | SshSource:
|
||||
if self.source is None:
|
||||
raise ConnectionException(f"{self.hostname}: the connection is not open")
|
||||
return self.source
|
||||
|
||||
def _record(self) -> Record:
|
||||
return self._source().record()
|
||||
|
||||
# -- readings ----------------------------------------------------------
|
||||
|
||||
def get_facts(self) -> FactsDict:
|
||||
return parse_facts(self._record())
|
||||
|
||||
def get_interfaces(self) -> dict[str, InterfaceDict]:
|
||||
return parse_interfaces(self._record())
|
||||
|
||||
def get_interfaces_ip(self) -> dict[str, InterfacesIPDict]:
|
||||
return parse_interfaces_ip(self._record())
|
||||
|
||||
def get_lldp_neighbors(self) -> dict[str, list[LldpNeighborDict]]:
|
||||
return lldp_neighbors(parse_lldp_rows(self._record()))
|
||||
|
||||
def get_lldp_neighbors_detail(
|
||||
self, interface: str = ""
|
||||
) -> dict[str, list[LLDPNeighborDetailDict]]:
|
||||
return lldp_neighbors_detail(parse_lldp_rows(self._record()), interface)
|
||||
|
||||
def get_mac_address_table(self) -> list[MACAdressTable]:
|
||||
return parse_mac_table(self._record())
|
||||
|
||||
|
||||
def _https(url: str) -> str:
|
||||
"""*url* with ``https://`` in front when it names no scheme."""
|
||||
return url if not url or "://" in url else f"https://{url}"
|
||||
|
||||
|
||||
def _private_key(args: dict[str, Any]) -> str:
|
||||
"""The SSH key as text: given as text, or read from ``key_file``."""
|
||||
if args.get("ssh_private_key_str"):
|
||||
return str(args["ssh_private_key_str"])
|
||||
if args.get("key_file"):
|
||||
return pathlib.Path(str(args["key_file"])).read_text()
|
||||
return ""
|
||||
@@ -0,0 +1,11 @@
|
||||
"""How discovery recognises UniFi gear."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
#: The MAC prefixes the IEEE registry assigns to Ubiquiti Inc. (oui.txt, 2025-10).
|
||||
OUI_PREFIXES: list[str] = [
|
||||
"00:15:6D", "00:27:22", "04:18:D6", "18:E8:29", "24:5A:4C", "24:A4:3C", "44:D9:E7",
|
||||
"60:22:32", "68:72:51", "68:D7:9A", "70:A7:41", "74:83:C2", "74:AC:B9", "78:45:58",
|
||||
"78:8A:20", "80:2A:A8", "94:2A:6F", "AC:8B:A9", "B4:FB:E4", "D0:21:F9", "DC:9F:DB",
|
||||
"E0:63:DA", "E4:38:83", "F0:9F:C2", "F4:92:BF", "F4:E2:C6", "FC:EC:DA",
|
||||
] # fmt: skip
|
||||
@@ -0,0 +1 @@
|
||||
"""Pure functions: UniFi output in, typed dicts out. No I/O."""
|
||||
@@ -0,0 +1,226 @@
|
||||
"""Facts, ports, LLDP, MAC table and PoE from one UniFi device record.
|
||||
|
||||
The record is the same whether a controller reports it (``stat/device``) or the
|
||||
device prints it itself (``mca-dump``): both are the device's inform payload. A
|
||||
port is named ``Port <index>`` on either path, so a port keeps its name when the
|
||||
device moves from one path to the other; the label someone gave it on the
|
||||
controller becomes its description.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from napalm.base.models import FactsDict, InterfaceDict, InterfacesIPDict, MACAdressTable
|
||||
from napalm_device_types.lldp import LldpNeighborRow
|
||||
from napalm_device_types.models import PoEPortDict, PoESummaryDict
|
||||
|
||||
VENDOR = "Ubiquiti"
|
||||
#: The device's own address and MAC, which no switch port carries.
|
||||
MANAGEMENT = "Management"
|
||||
MTU = 1500
|
||||
JUMBO_MTU = 9216
|
||||
_MAC = re.compile(r"^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$")
|
||||
|
||||
Record = dict[str, Any]
|
||||
|
||||
|
||||
def port_name(index: int) -> str:
|
||||
"""The interface name of the switch port with *index* (1-based)."""
|
||||
return f"Port {index}"
|
||||
|
||||
|
||||
def _ports(record: Record) -> list[Record]:
|
||||
return [p for p in record.get("port_table") or [] if isinstance(p.get("port_idx"), int)]
|
||||
|
||||
|
||||
def _number(value: Any) -> float:
|
||||
try:
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
||||
def parse_facts(record: Record) -> FactsDict:
|
||||
"""NAPALM facts. The product name (``model_display``) wins over the model code."""
|
||||
hostname = str(record.get("name") or record.get("hostname") or record.get("mac") or "")
|
||||
ports = [port_name(p["port_idx"]) for p in _ports(record)]
|
||||
return {
|
||||
"vendor": VENDOR,
|
||||
"model": str(record.get("model_display") or record.get("model") or ""),
|
||||
"hostname": hostname,
|
||||
"fqdn": hostname,
|
||||
"os_version": str(record.get("version") or ""),
|
||||
"serial_number": str(record.get("serial") or "").upper(),
|
||||
"uptime": _number(record.get("uptime")),
|
||||
"interface_list": [*ports, MANAGEMENT],
|
||||
}
|
||||
|
||||
|
||||
def _description(port: Record) -> str:
|
||||
label = str(port.get("name") or "")
|
||||
return "" if label == port_name(port["port_idx"]) else label
|
||||
|
||||
|
||||
def _port_interface(port: Record) -> InterfaceDict:
|
||||
return {
|
||||
"is_up": bool(port.get("up")),
|
||||
"is_enabled": bool(port.get("enable", True)),
|
||||
"description": _description(port),
|
||||
"last_flapped": -1.0,
|
||||
"mtu": JUMBO_MTU if port.get("jumbo") else MTU,
|
||||
"speed": _number(port.get("speed")),
|
||||
"mac_address": "",
|
||||
}
|
||||
|
||||
|
||||
def parse_interfaces(record: Record) -> dict[str, InterfaceDict]:
|
||||
"""Every switch port, plus :data:`MANAGEMENT` with the device's own MAC."""
|
||||
interfaces = {port_name(p["port_idx"]): _port_interface(p) for p in _ports(record)}
|
||||
interfaces[MANAGEMENT] = {
|
||||
"is_up": True,
|
||||
"is_enabled": True,
|
||||
"description": "",
|
||||
"last_flapped": -1.0,
|
||||
"mtu": MTU,
|
||||
"speed": 0.0,
|
||||
"mac_address": str(record.get("mac") or "").lower(),
|
||||
}
|
||||
return interfaces
|
||||
|
||||
|
||||
def _netmask(record: Record) -> str:
|
||||
uplink = record.get("uplink")
|
||||
if isinstance(uplink, dict) and uplink.get("netmask"):
|
||||
return str(uplink["netmask"])
|
||||
return str(record.get("netmask") or "")
|
||||
|
||||
|
||||
def _prefix_length(netmask: str) -> int:
|
||||
try:
|
||||
length = ipaddress.IPv4Network(f"0.0.0.0/{netmask}").prefixlen
|
||||
except ValueError:
|
||||
return 32
|
||||
return length or 32
|
||||
|
||||
|
||||
def parse_interfaces_ip(record: Record) -> dict[str, InterfacesIPDict]:
|
||||
"""The management address on :data:`MANAGEMENT`; ``{}`` while the device has none."""
|
||||
address = record.get("ip")
|
||||
if not address:
|
||||
return {}
|
||||
prefix = _prefix_length(_netmask(record))
|
||||
return {MANAGEMENT: {"ipv4": {str(address): {"prefix_length": prefix}}}}
|
||||
|
||||
|
||||
def _lldp_row(local_port: str, chassis: str, port_id: str, system_name: str) -> LldpNeighborRow:
|
||||
is_mac = bool(_MAC.match(chassis))
|
||||
return {
|
||||
"local_port": local_port,
|
||||
"chassis_id": chassis.lower() if is_mac else chassis,
|
||||
"chassis_id_type": "mac" if is_mac else ("local" if chassis else ""),
|
||||
"port_id": port_id,
|
||||
"port_id_type": "mac" if _MAC.match(port_id) else ("local" if port_id else ""),
|
||||
"port_description": "",
|
||||
"system_name": system_name,
|
||||
"system_description": "",
|
||||
"management_addresses": [],
|
||||
"capabilities": [],
|
||||
"enabled_capabilities": [],
|
||||
}
|
||||
|
||||
|
||||
def _per_port_rows(record: Record) -> list[LldpNeighborRow]:
|
||||
rows = []
|
||||
for port in sorted(_ports(record), key=lambda p: p["port_idx"]):
|
||||
for entry in port.get("lldp_table") or []:
|
||||
rows.append(
|
||||
_lldp_row(
|
||||
port_name(port["port_idx"]),
|
||||
str(entry.get("lldp_chassis_id") or ""),
|
||||
str(entry.get("lldp_port_id") or ""),
|
||||
str(entry.get("lldp_system_name") or ""),
|
||||
)
|
||||
)
|
||||
return rows
|
||||
|
||||
|
||||
def _top_level_rows(record: Record) -> list[LldpNeighborRow]:
|
||||
return [
|
||||
_lldp_row(
|
||||
port_name(int(entry["local_port_idx"])),
|
||||
str(entry.get("chassis_id") or ""),
|
||||
str(entry.get("port_id") or ""),
|
||||
str(entry.get("system_name") or ""),
|
||||
)
|
||||
for entry in record.get("lldp_table") or []
|
||||
if isinstance(entry.get("local_port_idx"), int)
|
||||
]
|
||||
|
||||
|
||||
def parse_lldp_rows(record: Record) -> list[LldpNeighborRow]:
|
||||
"""LLDP neighbours from both shapes firmware uses: per port (older) and at the top.
|
||||
|
||||
A neighbour reported in both counts once; the per-port entry, which carries the
|
||||
neighbour's system name, wins.
|
||||
"""
|
||||
rows: list[LldpNeighborRow] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
for row in [*_per_port_rows(record), *_top_level_rows(record)]:
|
||||
key = (row["local_port"], row["chassis_id"].lower())
|
||||
if key not in seen:
|
||||
seen.add(key)
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def parse_mac_table(record: Record) -> list[MACAdressTable]:
|
||||
"""What each port has learned. A controller's ``stat/device`` carries no tables."""
|
||||
return [
|
||||
{
|
||||
"mac": str(entry.get("mac") or "").lower(),
|
||||
"interface": port_name(port["port_idx"]),
|
||||
"vlan": int(entry.get("vlan") or 0),
|
||||
"static": bool(entry.get("static")),
|
||||
"active": True,
|
||||
"moves": 0,
|
||||
"last_move": -1.0,
|
||||
}
|
||||
for port in _ports(record)
|
||||
for entry in port.get("mac_table") or []
|
||||
]
|
||||
|
||||
|
||||
def _poe_status(port: Record) -> str:
|
||||
if port.get("poe_mode") == "off":
|
||||
return "disabled"
|
||||
return "delivering" if port.get("poe_good") else "searching"
|
||||
|
||||
|
||||
def _poe_class(port: Record) -> str:
|
||||
value = str(port.get("poe_class") or "")
|
||||
return value if value.lower().startswith("class") else "unknown"
|
||||
|
||||
|
||||
def _poe_port(port: Record) -> PoEPortDict:
|
||||
return {
|
||||
"enabled": port.get("poe_mode") != "off",
|
||||
"status": _poe_status(port),
|
||||
"poe_class": _poe_class(port),
|
||||
"power_draw": _number(port.get("poe_power")),
|
||||
"power_budget": 0.0,
|
||||
"voltage": _number(port.get("poe_voltage")),
|
||||
"current": _number(port.get("poe_current")),
|
||||
}
|
||||
|
||||
|
||||
def parse_poe(record: Record) -> PoESummaryDict:
|
||||
"""PoE per port that can deliver it, and the switch's budget and draw."""
|
||||
ports = {port_name(p["port_idx"]): _poe_port(p) for p in _ports(record) if p.get("port_poe")}
|
||||
return {
|
||||
"total_power_budget": _number(record.get("total_max_power")),
|
||||
"total_power_draw": sum(p["power_draw"] for p in ports.values()),
|
||||
"ports": ports,
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
"""The devices a UniFi controller manages, as :class:`ManagedDeviceDict`.
|
||||
|
||||
Two sources say the same thing in different words: the Integration API
|
||||
(``/v1/sites/{id}/devices``, ``/v1/pending-devices``) and the classic
|
||||
``stat/device``. ``site`` is always the classic site name (``default``) -- the
|
||||
Integration API's ``internalReference`` -- because that is the name a device's
|
||||
own driver addresses the controller by.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from napalm_device_types.network_controller_models import ManagedDeviceDict
|
||||
|
||||
Record = dict[str, Any]
|
||||
|
||||
_INTEGRATION_STATES = {
|
||||
"ONLINE": "online",
|
||||
"PENDING_ADOPTION": "pending",
|
||||
"UPDATING": "busy",
|
||||
"GETTING_READY": "busy",
|
||||
"ADOPTING": "busy",
|
||||
"DELETING": "busy",
|
||||
}
|
||||
#: The classic API's numeric states: 1 connected, 2 pending adoption, 4 upgrading,
|
||||
#: 5 provisioning, 7 adopting; the rest (0 disconnected, 6 heartbeat missed,
|
||||
#: 9/10 adoption failed, 11 isolated) cannot be reached.
|
||||
_CLASSIC_STATES = {1: "online", 2: "pending", 4: "busy", 5: "busy", 7: "busy"}
|
||||
_CLASSIC_ROLES = {
|
||||
"usw": "switch",
|
||||
"uap": "access_point",
|
||||
"ugw": "gateway",
|
||||
"udm": "gateway",
|
||||
"uxg": "gateway",
|
||||
}
|
||||
_OFFLINE = "offline"
|
||||
|
||||
|
||||
def _role_from_features(features: list[Any]) -> str:
|
||||
"""Gateway first: a gateway with switch ports is a gateway."""
|
||||
for feature, role in (("gateway", "gateway"), ("accessPoint", "access_point")):
|
||||
if feature in features:
|
||||
return role
|
||||
return "switch" if "switching" in features else "other"
|
||||
|
||||
|
||||
def _base(device: Record, site: str, state: str, role: str) -> ManagedDeviceDict:
|
||||
return {
|
||||
"mac": str(device.get("macAddress") or "").lower(),
|
||||
"name": str(device.get("name") or ""),
|
||||
"model": str(device.get("model") or ""),
|
||||
"role": role,
|
||||
"state": state,
|
||||
"site": site,
|
||||
"ip": device.get("ipAddress") or None,
|
||||
}
|
||||
|
||||
|
||||
def managed_from_integration(device: Record, site: str) -> ManagedDeviceDict:
|
||||
"""An adopted device of the Integration API (``/v1/sites/{id}/devices``)."""
|
||||
state = _INTEGRATION_STATES.get(str(device.get("state")), _OFFLINE)
|
||||
managed = _base(device, site, state, _role_from_features(device.get("features") or []))
|
||||
if device.get("id"):
|
||||
managed["id"] = str(device["id"])
|
||||
if device.get("firmwareVersion"):
|
||||
managed["firmware"] = str(device["firmwareVersion"])
|
||||
return managed
|
||||
|
||||
|
||||
def managed_from_pending(device: Record, site: str) -> ManagedDeviceDict:
|
||||
"""A device that waits to be adopted (``/v1/pending-devices``): it has no id yet."""
|
||||
managed = _base(device, site, "pending", _role_from_features(device.get("features") or []))
|
||||
if device.get("firmwareVersion"):
|
||||
managed["firmware"] = str(device["firmwareVersion"])
|
||||
return managed
|
||||
|
||||
|
||||
def managed_from_classic(record: Record, site: str) -> ManagedDeviceDict:
|
||||
"""A device of the classic ``stat/device``, adopted or pending."""
|
||||
managed: ManagedDeviceDict = {
|
||||
"mac": str(record.get("mac") or "").lower(),
|
||||
"name": str(record.get("name") or ""),
|
||||
"model": str(record.get("model") or ""),
|
||||
"role": _CLASSIC_ROLES.get(str(record.get("type")), "other"),
|
||||
"state": _CLASSIC_STATES.get(record.get("state"), _OFFLINE), # type: ignore[arg-type]
|
||||
"site": site,
|
||||
"ip": record.get("ip") or None,
|
||||
}
|
||||
optional = {
|
||||
"id": record.get("_id"),
|
||||
"serial": str(record.get("serial") or "").upper(),
|
||||
"model_name": record.get("model_display"),
|
||||
"firmware": record.get("version"),
|
||||
"firmware_available": record.get("upgrade_to_firmware")
|
||||
if record.get("upgradable")
|
||||
else None,
|
||||
}
|
||||
for key, value in optional.items():
|
||||
if value:
|
||||
managed[key] = str(value) # type: ignore[literal-required]
|
||||
return managed
|
||||
@@ -0,0 +1,145 @@
|
||||
"""A switch's VLANs with their ports.
|
||||
|
||||
Through the controller, a port's VLANs are what its override, its port profile and
|
||||
the defaults make of them, by the rules in ``docs/PORT_VLANS.md``. Over SSH the
|
||||
switch's own ``/tmp/running.cfg`` names its VLANs and each port's untagged VLAN
|
||||
(``pvid``), but not which VLANs a port carries tagged: that stays empty there
|
||||
rather than guessed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from napalm_device_types.switch_models import VlanDetailDict
|
||||
|
||||
from napalm_ubiquiti.parsers.device import port_name
|
||||
|
||||
Record = dict[str, Any]
|
||||
Membership = tuple[str | None, set[str]]
|
||||
|
||||
#: Network purposes a switch port can carry.
|
||||
SWITCHABLE = frozenset({"corporate", "guest", "vlan-only"})
|
||||
DEFAULT_VLAN = 1
|
||||
_FORWARD_TO_MGMT = {"all": "auto", "native": "block_all", "customize": "custom"}
|
||||
_VLAN_ID_KEY = re.compile(r"^switch\.vlan\.(\d+)\.id$")
|
||||
_PORT_KEY = "switch.port.{}.{}"
|
||||
|
||||
|
||||
def taggable_networks(networks: list[Record]) -> dict[str, tuple[int, str]]:
|
||||
"""The networks a port can carry: id -> (VLAN ID, name). No VLAN means VLAN 1."""
|
||||
taggable = {}
|
||||
for net in networks:
|
||||
if net.get("purpose") not in SWITCHABLE or not net.get("_id"):
|
||||
continue
|
||||
vlan = int(net["vlan"]) if net.get("vlan_enabled") and net.get("vlan") else DEFAULT_VLAN
|
||||
taggable[str(net["_id"])] = (vlan, str(net.get("name") or ""))
|
||||
return taggable
|
||||
|
||||
|
||||
def _default_network(networks: list[Record], taggable: dict[str, tuple[int, str]]) -> str | None:
|
||||
for net in networks:
|
||||
if net.get("attr_hidden_id") == "LAN" and str(net.get("_id")) in taggable:
|
||||
return str(net["_id"])
|
||||
return next((nid for nid, (vlan, _) in taggable.items() if vlan == DEFAULT_VLAN), None)
|
||||
|
||||
|
||||
def _setting(override: Record, profile: Record, key: str) -> Any:
|
||||
return override[key] if key in override else profile.get(key)
|
||||
|
||||
|
||||
def _tagged(mode: str, override: Record, profile: Record, everything: set[str]) -> set[str]:
|
||||
if mode == "block_all":
|
||||
return set()
|
||||
if mode != "custom":
|
||||
return set(everything)
|
||||
excluded = _setting(override, profile, "excluded_networkconf_ids")
|
||||
if excluded is not None:
|
||||
return everything - set(excluded)
|
||||
return everything & set(_setting(override, profile, "tagged_networkconf_ids") or [])
|
||||
|
||||
|
||||
def port_membership(
|
||||
port: Record,
|
||||
override: Record,
|
||||
profiles: dict[str, Record],
|
||||
taggable: set[str],
|
||||
default: str | None,
|
||||
) -> Membership:
|
||||
"""The port's native network and the networks it carries tagged."""
|
||||
profile = profiles.get(str(override.get("portconf_id") or port.get("portconf_id") or ""), {})
|
||||
forward = _setting(override, profile, "forward") or "all"
|
||||
if forward == "disabled":
|
||||
return None, set()
|
||||
native = _setting(override, profile, "native_networkconf_id")
|
||||
native = native if native in taggable else default
|
||||
mode = _setting(override, profile, "tagged_vlan_mgmt") or _FORWARD_TO_MGMT.get(forward, "auto")
|
||||
return native, _tagged(mode, override, profile, taggable) - {native}
|
||||
|
||||
|
||||
def _empty(taggable: dict[str, tuple[int, str]]) -> dict[str, VlanDetailDict]:
|
||||
vlans: dict[str, VlanDetailDict] = {}
|
||||
for vlan, name in taggable.values():
|
||||
vlans.setdefault(str(vlan), {"name": name, "tagged": [], "untagged": []})
|
||||
return vlans
|
||||
|
||||
|
||||
def parse_vlans_detail_classic(
|
||||
record: Record, networks: list[Record], profiles: list[Record]
|
||||
) -> dict[str, VlanDetailDict]:
|
||||
"""Every switchable VLAN of the site with this switch's ports, as the controller has them."""
|
||||
taggable = taggable_networks(networks)
|
||||
default = _default_network(networks, taggable)
|
||||
by_id = {str(p.get("_id")): p for p in profiles}
|
||||
overrides = {o.get("port_idx"): o for o in record.get("port_overrides") or []}
|
||||
vlans = _empty(taggable)
|
||||
ports = [p for p in record.get("port_table") or [] if isinstance(p.get("port_idx"), int)]
|
||||
for port in sorted(ports, key=lambda p: p["port_idx"]):
|
||||
override = overrides.get(port["port_idx"], {})
|
||||
membership = port_membership(port, override, by_id, set(taggable), default)
|
||||
_add_port(vlans, port_name(port["port_idx"]), membership, taggable)
|
||||
return vlans
|
||||
|
||||
|
||||
def _add_port(
|
||||
vlans: dict[str, VlanDetailDict],
|
||||
name: str,
|
||||
membership: Membership,
|
||||
taggable: dict[str, tuple[int, str]],
|
||||
) -> None:
|
||||
"""Put the port *name* into its untagged VLAN and its tagged ones; native is never tagged."""
|
||||
native, tagged = membership
|
||||
native_vid = taggable[native][0] if native is not None else None
|
||||
if native_vid is not None:
|
||||
vlans[str(native_vid)]["untagged"].append(name)
|
||||
for vid in sorted({taggable[nid][0] for nid in tagged} - {native_vid}):
|
||||
vlans[str(vid)]["tagged"].append(name)
|
||||
|
||||
|
||||
def parse_running_cfg(text: str) -> dict[str, str]:
|
||||
"""``key=value`` lines of a UniFi ``running.cfg``; comments and other lines dropped."""
|
||||
config = {}
|
||||
for line in text.splitlines():
|
||||
key, sep, value = line.partition("=")
|
||||
if sep and not key.startswith("#"):
|
||||
config[key.strip()] = value.strip()
|
||||
return config
|
||||
|
||||
|
||||
def parse_vlans_detail_running_cfg(
|
||||
config: dict[str, str], port_indexes: list[int]
|
||||
) -> dict[str, VlanDetailDict]:
|
||||
"""The switch's enabled VLANs and each enabled port's untagged one (``pvid``, else 1)."""
|
||||
vlans: dict[str, VlanDetailDict] = {}
|
||||
for key, value in config.items():
|
||||
match = _VLAN_ID_KEY.match(key)
|
||||
if match and config.get(f"switch.vlan.{match.group(1)}.status", "enabled") == "enabled":
|
||||
vlans[str(int(value))] = {"name": "", "tagged": [], "untagged": []}
|
||||
for index in sorted(port_indexes):
|
||||
if config.get(_PORT_KEY.format(index, "status"), "enabled") != "enabled":
|
||||
continue
|
||||
pvid = str(int(config.get(_PORT_KEY.format(index, "pvid"), DEFAULT_VLAN)))
|
||||
if pvid in vlans:
|
||||
vlans[pvid]["untagged"].append(port_name(index))
|
||||
return vlans
|
||||
@@ -0,0 +1,170 @@
|
||||
"""SSIDs, radios and wireless clients of a UniFi access point.
|
||||
|
||||
The AP's record (controller ``stat/device`` or the AP's own ``mca-dump``) names
|
||||
what each radio broadcasts (``vap_table``) and how the radios are set
|
||||
(``radio_table``, with the running channel in ``radio_table_stats``). How an SSID
|
||||
is secured is the controller's WLAN configuration (``rest/wlanconf``), not the AP's.
|
||||
|
||||
Rates in the records are in kbit/s; the contract wants Mbit/s.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from napalm_device_types.access_point_models import (
|
||||
RadioStatusDict,
|
||||
SSIDDict,
|
||||
WirelessClientDict,
|
||||
)
|
||||
|
||||
Record = dict[str, Any]
|
||||
|
||||
#: A radio's band, by UniFi's radio code.
|
||||
BANDS = {"ng": "2.4GHz", "na": "5GHz", "6e": "6GHz"}
|
||||
DEFAULT_WIDTH = 20
|
||||
_USER_VAP = "user"
|
||||
|
||||
|
||||
def _band(radio_code: Any) -> str:
|
||||
return BANDS.get(str(radio_code or ""), str(radio_code or ""))
|
||||
|
||||
|
||||
def _int(value: Any, default: int = 0) -> int:
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def _user_vaps(record: Record) -> list[Record]:
|
||||
"""The VAPs that broadcast an SSID: not mesh links (``downlink``), not scanners."""
|
||||
return [
|
||||
vap
|
||||
for vap in record.get("vap_table") or []
|
||||
if vap.get("essid") and vap.get("usage", _USER_VAP) == _USER_VAP
|
||||
]
|
||||
|
||||
|
||||
def _psk(wlan: Record, mode: str) -> str:
|
||||
if wlan.get("wpa3_transition"):
|
||||
return "WPA2/WPA3"
|
||||
return "WPA3-SAE" if mode == "WPA3" else f"{mode or 'WPA2'}-PSK"
|
||||
|
||||
|
||||
def _encryption(wlan: Record | None) -> str:
|
||||
if not wlan:
|
||||
return ""
|
||||
security = str(wlan.get("security") or "")
|
||||
mode = str(wlan.get("wpa_mode") or "").upper()
|
||||
if security == "wpapsk":
|
||||
return _psk(wlan, mode)
|
||||
if security == "wpaeap":
|
||||
return f"{mode or 'WPA2'}-Enterprise"
|
||||
return "WEP" if security == "wep" else security
|
||||
|
||||
|
||||
def _ssid(vap: Record, wlan: Record | None) -> SSIDDict:
|
||||
return {
|
||||
"enabled": bool(vap.get("up", True)),
|
||||
"radio": str(vap.get("radio_name") or vap.get("radio") or ""),
|
||||
"bssid": str(vap.get("bssid") or "").lower(),
|
||||
"encryption": _encryption(wlan),
|
||||
"hidden": bool((wlan or {}).get("hide_ssid", False)),
|
||||
"clients": _int(vap.get("num_sta")),
|
||||
}
|
||||
|
||||
|
||||
def parse_ssids(record: Record, wlans: list[Record] | None = None) -> dict[str, SSIDDict]:
|
||||
"""Each broadcast SSID, keyed by its name; ``"name (band)"`` where it is on several bands.
|
||||
|
||||
*wlans* is the controller's WLAN configuration; without it the encryption is
|
||||
``""`` and the SSID counts as visible.
|
||||
"""
|
||||
by_name = {str(w.get("name")): w for w in wlans or []}
|
||||
vaps = _user_vaps(record)
|
||||
names = [str(v["essid"]) for v in vaps]
|
||||
ssids: dict[str, SSIDDict] = {}
|
||||
for vap in vaps:
|
||||
name = str(vap["essid"])
|
||||
key = name if names.count(name) == 1 else f"{name} ({_band(vap.get('radio'))})"
|
||||
ssids[key] = _ssid(vap, by_name.get(name))
|
||||
return ssids
|
||||
|
||||
|
||||
def frequency_ghz(channel: int, band: str) -> float:
|
||||
"""The centre frequency of *channel* in *band*; ``0.0`` for an unknown channel."""
|
||||
if channel <= 0:
|
||||
return 0.0
|
||||
if band == "2.4GHz":
|
||||
return 2.484 if channel == 14 else (2407 + 5 * channel) / 1000
|
||||
base = 5950 if band == "6GHz" else 5000
|
||||
return (base + 5 * channel) / 1000
|
||||
|
||||
|
||||
def _radio(radio: Record, stats: Record | None) -> RadioStatusDict:
|
||||
band = _band(radio.get("radio"))
|
||||
channel = _int((stats or {}).get("channel", radio.get("channel")))
|
||||
status: RadioStatusDict = {
|
||||
"enabled": not radio.get("disabled", False),
|
||||
"band": band,
|
||||
"channel": channel,
|
||||
"channel_width": _int(radio.get("ht"), DEFAULT_WIDTH),
|
||||
"tx_power": _int((stats or {}).get("tx_power", radio.get("max_txpower"))),
|
||||
"frequency": frequency_ghz(channel, band),
|
||||
}
|
||||
if stats is not None:
|
||||
status["up"] = stats.get("state") == "RUN"
|
||||
return status
|
||||
|
||||
|
||||
def parse_radios(record: Record) -> dict[str, RadioStatusDict]:
|
||||
"""Each radio, keyed by its name (``wifi0``).
|
||||
|
||||
Where the record carries ``radio_table_stats``, channel, power and whether the
|
||||
radio runs (``up``) are what it does; without them the configuration, and no
|
||||
runtime state.
|
||||
"""
|
||||
stats = {s.get("name"): s for s in record.get("radio_table_stats") or []}
|
||||
return {
|
||||
str(r["name"]): _radio(r, stats.get(r["name"]))
|
||||
for r in record.get("radio_table") or []
|
||||
if r.get("name")
|
||||
}
|
||||
|
||||
|
||||
def _client(station: Record, ssid: str, radio: str) -> WirelessClientDict:
|
||||
client: WirelessClientDict = {
|
||||
"mac": str(station.get("mac") or "").lower(),
|
||||
"ssid": ssid,
|
||||
"radio": radio,
|
||||
"signal": _int(station.get("signal")),
|
||||
"noise": _int(station.get("noise")),
|
||||
"tx_rate": _int(station.get("tx_rate")) / 1000,
|
||||
"rx_rate": _int(station.get("rx_rate")) / 1000,
|
||||
"uptime": _int(station.get("uptime")),
|
||||
}
|
||||
if station.get("ip"):
|
||||
client["ip"] = str(station["ip"])
|
||||
if station.get("hostname"):
|
||||
client["hostname"] = str(station["hostname"])
|
||||
return client
|
||||
|
||||
|
||||
def parse_station_list(stations: list[Record], ap_mac: str) -> list[WirelessClientDict]:
|
||||
"""The controller's client list (``stat/sta``), narrowed to the AP with *ap_mac*."""
|
||||
mac = ap_mac.lower()
|
||||
return [
|
||||
_client(s, str(s.get("essid") or ""), str(s.get("radio_name") or s.get("radio") or ""))
|
||||
for s in stations
|
||||
if not s.get("is_wired") and str(s.get("ap_mac") or "").lower() == mac
|
||||
]
|
||||
|
||||
|
||||
def parse_vap_stations(record: Record) -> list[WirelessClientDict]:
|
||||
"""The clients an AP lists under its own VAPs (``mca-dump``)."""
|
||||
return [
|
||||
_client(s, str(vap["essid"]), str(vap.get("radio_name") or vap.get("radio") or ""))
|
||||
for vap in _user_vaps(record)
|
||||
for s in vap.get("sta_table") or []
|
||||
]
|
||||
Whitespace-only changes.
@@ -0,0 +1,113 @@
|
||||
"""Where a switch's or access point's readings come from.
|
||||
|
||||
:class:`ControllerSource` asks the controller that manages the device;
|
||||
:class:`SshSource` asks the device over SSH. Both hand out the same device record
|
||||
(the controller's ``stat/device`` entry is the device's own ``mca-dump``), so the
|
||||
drivers above them need not know which path they are on. A record is read once
|
||||
per connection: the getters of one poll see one moment.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import Any, Protocol
|
||||
|
||||
from napalm.base.exceptions import CommandErrorException
|
||||
from napalm_device_types.access_point_models import WirelessClientDict
|
||||
from napalm_device_types.switch_models import VlanDetailDict
|
||||
|
||||
from napalm_ubiquiti.client import UnifiError
|
||||
from napalm_ubiquiti.parsers.vlans import (
|
||||
parse_running_cfg,
|
||||
parse_vlans_detail_classic,
|
||||
parse_vlans_detail_running_cfg,
|
||||
)
|
||||
from napalm_ubiquiti.parsers.wireless import parse_station_list, parse_vap_stations
|
||||
|
||||
Record = dict[str, Any]
|
||||
|
||||
DUMP_COMMAND = "mca-dump"
|
||||
CONFIG_COMMAND = "cat /tmp/running.cfg"
|
||||
_MAC_SEPARATORS = re.compile(r"[-.]")
|
||||
|
||||
|
||||
class ClassicApi(Protocol):
|
||||
def classic_get(self, site: str, endpoint: str) -> list[Any]: ...
|
||||
|
||||
|
||||
class Shell(Protocol):
|
||||
def run(self, command: str) -> str: ...
|
||||
|
||||
|
||||
def normalise_mac(mac: str) -> str:
|
||||
"""``FC-EC-DA-11-22-33`` -> ``fc:ec:da:11:22:33``."""
|
||||
return _MAC_SEPARATORS.sub(":", mac.strip()).lower()
|
||||
|
||||
|
||||
class ControllerSource:
|
||||
"""The device with *mac* in *site* of the controller behind *client*."""
|
||||
|
||||
def __init__(self, client: ClassicApi, site: str, mac: str) -> None:
|
||||
self.client = client
|
||||
self.site = site
|
||||
self.mac = normalise_mac(mac)
|
||||
self._record: Record | None = None
|
||||
|
||||
@classmethod
|
||||
def find(cls, client: ClassicApi, site: str, address: str) -> ControllerSource:
|
||||
"""The device in *site* whose management address is *address*."""
|
||||
for entry in client.classic_get(site, "stat/device"):
|
||||
if entry.get("ip") == address and entry.get("mac"):
|
||||
source = cls(client, site, str(entry["mac"]))
|
||||
source._record = dict(entry)
|
||||
return source
|
||||
raise UnifiError(f"the controller has no device at {address} in site {site}")
|
||||
|
||||
def record(self) -> Record:
|
||||
if self._record is None:
|
||||
entries = self.client.classic_get(self.site, f"stat/device/{self.mac}")
|
||||
if not entries:
|
||||
raise UnifiError(f"the controller does not manage {self.mac} in site {self.site}")
|
||||
self._record = dict(entries[0])
|
||||
return self._record
|
||||
|
||||
def vlans_detail(self) -> dict[str, VlanDetailDict]:
|
||||
networks = self.client.classic_get(self.site, "rest/networkconf")
|
||||
profiles = self.client.classic_get(self.site, "rest/portconf")
|
||||
return parse_vlans_detail_classic(self.record(), networks, profiles)
|
||||
|
||||
def wireless_clients(self, record: Record) -> list[WirelessClientDict]:
|
||||
return parse_station_list(self.client.classic_get(self.site, "stat/sta"), self.mac)
|
||||
|
||||
def wlans(self) -> list[Record]:
|
||||
return self.client.classic_get(self.site, "rest/wlanconf")
|
||||
|
||||
|
||||
class SshSource:
|
||||
"""The device itself, over the SSH *shell*: read only, its controller owns its config."""
|
||||
|
||||
def __init__(self, shell: Shell) -> None:
|
||||
self.shell = shell
|
||||
self._record: Record | None = None
|
||||
|
||||
def record(self) -> Record:
|
||||
if self._record is None:
|
||||
output = self.shell.run(DUMP_COMMAND)
|
||||
try:
|
||||
self._record = dict(json.loads(output))
|
||||
except ValueError as exc:
|
||||
raise CommandErrorException(f"{DUMP_COMMAND}: no JSON ({output[:80]!r})") from exc
|
||||
return self._record
|
||||
|
||||
def vlans_detail(self) -> dict[str, VlanDetailDict]:
|
||||
indexes = [p["port_idx"] for p in self.record().get("port_table") or [] if "port_idx" in p]
|
||||
config = parse_running_cfg(self.shell.run(CONFIG_COMMAND))
|
||||
return parse_vlans_detail_running_cfg(config, indexes)
|
||||
|
||||
def wireless_clients(self, record: Record) -> list[WirelessClientDict]:
|
||||
return parse_vap_stations(record)
|
||||
|
||||
def wlans(self) -> list[Record]:
|
||||
"""The WLAN configuration is the controller's; a device alone has none to give."""
|
||||
return []
|
||||
@@ -0,0 +1,103 @@
|
||||
"""An SSH shell to a UniFi switch or access point, for reading only.
|
||||
|
||||
The device's host key is verified by :class:`napalm_device_types.HostKeyCheck`
|
||||
(trust on first use, a changed key refused before any login). Only the password
|
||||
or key given is offered: never an SSH agent and never a key file of the machine
|
||||
the driver runs on.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
from collections.abc import Callable, Mapping
|
||||
from typing import Any
|
||||
|
||||
import paramiko
|
||||
from napalm.base.exceptions import CommandErrorException, ConnectionException
|
||||
from napalm_device_types.ssh_host_keys import HostKeyCheck
|
||||
|
||||
DEFAULT_PORT = 22
|
||||
DEFAULT_TIMEOUT = 60.0
|
||||
_KEY_TYPES: tuple[type[paramiko.PKey], ...] = (
|
||||
paramiko.Ed25519Key,
|
||||
paramiko.ECDSAKey,
|
||||
paramiko.RSAKey,
|
||||
)
|
||||
|
||||
|
||||
def load_private_key(text: str) -> paramiko.PKey:
|
||||
"""The private key in *text*, whichever type it is."""
|
||||
for key_type in _KEY_TYPES:
|
||||
try:
|
||||
return key_type.from_private_key(io.StringIO(text))
|
||||
except (paramiko.SSHException, ValueError):
|
||||
continue
|
||||
raise ConnectionException("the SSH private key could not be read")
|
||||
|
||||
|
||||
class SshShell:
|
||||
"""One SSH connection to *host*; :meth:`run` executes one command on it."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
host: str,
|
||||
*,
|
||||
username: str,
|
||||
password: str = "",
|
||||
private_key: str = "",
|
||||
port: int = DEFAULT_PORT,
|
||||
optional_args: Mapping[str, Any] | None = None,
|
||||
timeout: float = DEFAULT_TIMEOUT,
|
||||
client_factory: Callable[[], Any] = paramiko.SSHClient,
|
||||
) -> None:
|
||||
self.host = host
|
||||
self.username = username
|
||||
self.password = password
|
||||
self.private_key = private_key
|
||||
self.port = int(port)
|
||||
self.timeout = timeout
|
||||
self.check = HostKeyCheck(optional_args, host, self.port)
|
||||
self._factory = client_factory
|
||||
self._client: Any = None
|
||||
|
||||
def open(self) -> None:
|
||||
if not (self.password or self.private_key):
|
||||
raise ConnectionException(f"{self.host}: give an SSH password or a private key")
|
||||
pkey = load_private_key(self.private_key) if self.private_key else None
|
||||
client = self._factory()
|
||||
try:
|
||||
self.check.connect(
|
||||
client,
|
||||
username=self.username,
|
||||
password=None if pkey else self.password,
|
||||
pkey=pkey,
|
||||
timeout=self.timeout,
|
||||
allow_agent=False,
|
||||
look_for_keys=False,
|
||||
)
|
||||
except (paramiko.SSHException, OSError) as exc:
|
||||
client.close()
|
||||
raise ConnectionException(f"{self.host}:{self.port}: {exc}") from exc
|
||||
except BaseException: # a refused host key among them: nothing stays open
|
||||
client.close()
|
||||
raise
|
||||
self._client = client
|
||||
|
||||
def run(self, command: str) -> str:
|
||||
"""The standard output of *command*; a non-zero exit raises."""
|
||||
if self._client is None:
|
||||
raise ConnectionException(f"{self.host}: the SSH connection is not open")
|
||||
# Only the source's fixed commands (``DUMP_COMMAND``, ``CONFIG_COMMAND``) come here,
|
||||
# never anything a caller or the device supplied.
|
||||
_, stdout, stderr = self._client.exec_command(command, timeout=self.timeout) # nosec B601
|
||||
output = stdout.read().decode("utf-8", "replace")
|
||||
status = stdout.channel.recv_exit_status()
|
||||
if status != 0:
|
||||
error = stderr.read().decode("utf-8", "replace").strip()
|
||||
raise CommandErrorException(f"{command}: exit {status}: {error}")
|
||||
return str(output)
|
||||
|
||||
def close(self) -> None:
|
||||
if self._client is not None:
|
||||
self._client.close()
|
||||
self._client = None
|
||||
@@ -0,0 +1,36 @@
|
||||
"""A UniFi switch (USW), through its controller or over SSH."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from napalm.base.models import VlanDict
|
||||
from napalm_device_types import SwitchDriver
|
||||
from napalm_device_types.models import PoESummaryDict
|
||||
from napalm_device_types.switch_models import VlanDetailDict
|
||||
|
||||
from napalm_ubiquiti.device import UnifiDevice
|
||||
from napalm_ubiquiti.identity import OUI_PREFIXES
|
||||
from napalm_ubiquiti.parsers.device import parse_poe
|
||||
|
||||
|
||||
class UnifiSwitchDriver(UnifiDevice, SwitchDriver):
|
||||
"""A UniFi switch. Over SSH it is read only: its controller owns its config."""
|
||||
|
||||
DRIVER_NAME = "unifi_switch"
|
||||
OUI_PREFIXES = OUI_PREFIXES
|
||||
#: A UniFi switch reboots in about a minute and a half, then informs again.
|
||||
REBOOT_SETTLE_SECONDS = 90
|
||||
|
||||
def get_poe_status(self) -> PoESummaryDict:
|
||||
return parse_poe(self._record())
|
||||
|
||||
def get_vlans_detail(self) -> dict[str, VlanDetailDict]:
|
||||
return self._source().vlans_detail()
|
||||
|
||||
def get_vlans(self) -> dict[int, VlanDict]:
|
||||
return {
|
||||
int(vid): {
|
||||
"name": vlan["name"],
|
||||
"interfaces": sorted(vlan["untagged"] + vlan["tagged"]),
|
||||
}
|
||||
for vid, vlan in self.get_vlans_detail().items()
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=77"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "napalm-ubiquiti"
|
||||
version = "0.1.0"
|
||||
description = "NAPALM drivers for Ubiquiti UniFi: switches and access points (through the controller or over SSH) and the UniFi Network controller"
|
||||
readme = "README.md"
|
||||
license = "Apache-2.0"
|
||||
requires-python = ">=3.12"
|
||||
authors = [{ name = "Christian Manivong", email = "christian@manivong.de" }]
|
||||
classifiers = [
|
||||
"Programming Language :: Python :: 3",
|
||||
"Operating System :: OS Independent",
|
||||
"Topic :: System :: Networking",
|
||||
]
|
||||
dependencies = [
|
||||
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
|
||||
"napalm-device-types>=4.60", # NetworkControllerDriver, VlanDetailDict
|
||||
"paramiko>=5.0.0", # CVE-2026-44405
|
||||
"requests>=2.31.0",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = ["pytest>=8", "pytest-cov>=5", "mypy>=1.11", "ruff>=0.6", "types-requests", "types-paramiko"]
|
||||
|
||||
[project.urls]
|
||||
Repository = "https://git.netork.io/NAPALM/napalm-ubiquiti"
|
||||
Issues = "https://git.netork.io/NAPALM/napalm-ubiquiti/issues"
|
||||
|
||||
[project.entry-points."napalm.drivers"]
|
||||
unifi_switch = "napalm_ubiquiti:UnifiSwitchDriver"
|
||||
unifi_ap = "napalm_ubiquiti:UnifiAccessPointDriver"
|
||||
unifi_network = "napalm_ubiquiti:UnifiNetworkDriver"
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
include = ["napalm_ubiquiti*"]
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
napalm_ubiquiti = ["py.typed"]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
target-version = "py312"
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "I", "UP", "B"]
|
||||
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
# Recorded device output keeps its lines.
|
||||
"tests/**" = ["E501"]
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.12"
|
||||
strict = true
|
||||
# napalm itself is untyped, so every driver subclasses Any.
|
||||
disallow_subclassing_any = false
|
||||
|
||||
[[tool.mypy.overrides]]
|
||||
module = ["napalm.*"]
|
||||
ignore_missing_imports = true
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
pythonpath = [".", "sim"]
|
||||
|
||||
[tool.coverage.run]
|
||||
source = ["napalm_ubiquiti"]
|
||||
|
||||
[tool.coverage.report]
|
||||
fail_under = 90
|
||||
exclude_also = ["pragma: no cover - live I/O"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# The UniFi simulator: a controller on 8443 and a switch without one on 2222.
|
||||
# Build from the repository root: docker build -f sim/Dockerfile -t unifi-sim .
|
||||
FROM python:3.12-slim
|
||||
|
||||
RUN pip install --no-cache-dir "paramiko>=5.0.0" "cryptography>=43"
|
||||
|
||||
WORKDIR /app
|
||||
COPY sim/unifi_sim /app/unifi_sim
|
||||
COPY tests/fixtures /app/fixtures
|
||||
|
||||
USER nobody
|
||||
EXPOSE 8443 2222
|
||||
ENTRYPOINT ["python", "-m", "unifi_sim", "--host", "0.0.0.0", "--fixtures", "/app/fixtures"]
|
||||
@@ -0,0 +1,52 @@
|
||||
# UniFi simulator
|
||||
|
||||
A UniFi Network controller and a UniFi switch, simulated so the drivers can be
|
||||
tested without hardware. It is not a UniFi implementation. It answers what the
|
||||
drivers ask, by the rules a real controller answers by, from the recorded
|
||||
fixtures in `tests/fixtures`.
|
||||
|
||||
## What it plays
|
||||
|
||||
**The controller** on HTTPS, with a self-signed certificate:
|
||||
|
||||
- UniFi OS (`/proxy/network/...`) or a standalone Network application (`--standalone`).
|
||||
- The Integration API (`/v1/info`, `sites`, `sites/{id}/devices`, and
|
||||
`pending-devices` from 10.0) with an API key, from Network 9.0.108.
|
||||
- The classic API (`self/sites`, `stat/device[/<mac>]`, `stat/sta`,
|
||||
`stat/sysinfo`, `rest/networkconf|portconf|wlanconf`, and
|
||||
`PUT rest/device/<id>`) with an API key or a session.
|
||||
- Logins: UniFi OS (`TOKEN` cookie, `X-CSRF-Token`) or standalone (`unifises`
|
||||
and `csrf_token` cookies). A write on a session needs its CSRF token.
|
||||
- Failures: a wrong key or password (401), a cloud account with MFA (499),
|
||||
too many failed logins (429 with `Retry-After`), an unknown site
|
||||
(`api.err.NoSiteContext`), and every answer a redirect (`redirect=True`).
|
||||
- Data: two sites. `default` holds a US-16-150W, a USW Flex Mini, a UAP-AC-Pro
|
||||
and a U6-LR waiting for adoption. `branch` holds a US-8.
|
||||
|
||||
**A switch without a controller** on SSH (US-24, 7.1.26, login `ubnt`/`ubnt`). It
|
||||
answers `mca-dump` and `cat /tmp/running.cfg`; any other command exits 127. Its
|
||||
Ed25519 host key is new on every start.
|
||||
|
||||
## Use
|
||||
|
||||
In tests (`tests/test_sim_e2e.py`):
|
||||
|
||||
```python
|
||||
from unifi_sim import SimController, SimDevice, serve_controller, serve_device
|
||||
|
||||
controller = serve_controller(SimController.from_fixtures(version="9.1.120"))
|
||||
switch = serve_device(SimDevice.us24())
|
||||
...
|
||||
controller.stop()
|
||||
switch.stop()
|
||||
```
|
||||
|
||||
By hand, or for netOrk on a test server:
|
||||
|
||||
```bash
|
||||
PYTHONPATH=sim python -m unifi_sim --port 8443 --ssh-port 2222 [--version 10.1.84] [--standalone]
|
||||
docker build -f sim/Dockerfile -t unifi-sim . && docker run -p 8443:8443 -p 2222:2222 unifi-sim --api-key <key>
|
||||
```
|
||||
|
||||
It prints the controller's URL, certificate fingerprint, login and API key, and
|
||||
the switch's SSH port and host key.
|
||||
@@ -0,0 +1,20 @@
|
||||
"""A UniFi Network controller and UniFi devices, simulated for the drivers' tests.
|
||||
|
||||
Not a UniFi implementation: it answers what the drivers ask, by the rules a real
|
||||
controller answers by (versions, logins, API keys, CSRF, sites, rate limits),
|
||||
from the recorded fixtures.
|
||||
"""
|
||||
|
||||
from unifi_sim.http import ControllerServer, serve_controller
|
||||
from unifi_sim.model import SimController, SimSite
|
||||
from unifi_sim.ssh import DeviceServer, SimDevice, serve_device
|
||||
|
||||
__all__ = [
|
||||
"ControllerServer",
|
||||
"DeviceServer",
|
||||
"SimController",
|
||||
"SimDevice",
|
||||
"SimSite",
|
||||
"serve_controller",
|
||||
"serve_device",
|
||||
]
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Run the simulator: a controller on HTTPS and one switch without a controller on SSH.
|
||||
|
||||
python -m unifi_sim --port 8443 --ssh-port 2222
|
||||
|
||||
It prints how to reach both and runs until interrupted.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import signal
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from unifi_sim.http import ControllerServer, serve_controller
|
||||
from unifi_sim.model import FIXTURES, SimController
|
||||
from unifi_sim.ssh import DeviceServer, SimDevice, serve_device
|
||||
|
||||
|
||||
def parse(argv: list[str] | None = None) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(prog="unifi_sim", description=__doc__)
|
||||
parser.add_argument("--host", default="127.0.0.1")
|
||||
parser.add_argument("--port", type=int, default=8443, help="the controller's HTTPS port")
|
||||
parser.add_argument("--ssh-port", type=int, default=2222, help="the lone switch's SSH port")
|
||||
parser.add_argument("--version", default="10.6.106", help="the Network application's")
|
||||
parser.add_argument("--standalone", action="store_true", help="no UniFi OS: login only")
|
||||
parser.add_argument("--api-key", default="", help="default: a new random key")
|
||||
parser.add_argument("--fixtures", type=Path, default=FIXTURES)
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def build(args: argparse.Namespace) -> tuple[ControllerServer, DeviceServer]:
|
||||
sim = SimController.from_fixtures(
|
||||
version=args.version, unifi_os=not args.standalone, root=args.fixtures
|
||||
)
|
||||
if args.api_key:
|
||||
sim.api_key = args.api_key
|
||||
controller = serve_controller(sim, args.host, args.port)
|
||||
switch = serve_device(SimDevice.us24(args.fixtures), args.host, args.ssh_port)
|
||||
return controller, switch
|
||||
|
||||
|
||||
def describe(controller: ControllerServer, switch: DeviceServer) -> str:
|
||||
sim = controller.sim
|
||||
kind = "UniFi OS" if sim.unifi_os else "standalone"
|
||||
lines = [
|
||||
f"Controller ({kind}, Network {sim.version}): {controller.url}",
|
||||
f" certificate {controller.fingerprint}",
|
||||
f" login {sim.admin[0]} / {sim.admin[1]}",
|
||||
]
|
||||
if sim.has_integration:
|
||||
lines.append(f" API key {sim.api_key}")
|
||||
lines += [
|
||||
f" sites {', '.join(s.name for s in sim.sites)}",
|
||||
f"Switch without a controller: ssh {switch.device.username}@{switch.host} "
|
||||
f"-p {switch.port} (password {switch.device.password})",
|
||||
f" host key {switch.host_key['key_type']} {switch.host_key['key']}",
|
||||
]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> None: # pragma: no cover - live I/O
|
||||
controller, switch = build(parse(argv))
|
||||
print(describe(controller, switch), flush=True)
|
||||
stop = threading.Event()
|
||||
for sig in (signal.SIGINT, signal.SIGTERM):
|
||||
signal.signal(sig, lambda *_: stop.set())
|
||||
stop.wait()
|
||||
controller.stop()
|
||||
switch.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover - live I/O
|
||||
main()
|
||||
@@ -0,0 +1,211 @@
|
||||
"""The controller's answers, by method and path: no sockets here.
|
||||
|
||||
:func:`handle` takes a request as plain values and returns one as plain values,
|
||||
so the rules can be read (and tested) apart from the HTTP server around them.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
from unifi_sim.model import SimController, integration_device
|
||||
|
||||
UNIFI_OS_CLASSIC = "/proxy/network/api"
|
||||
STANDALONE_CLASSIC = "/api"
|
||||
INTEGRATION = "/proxy/network/integration/v1"
|
||||
DEFAULT_PAGE = 25
|
||||
MAX_PAGE = 200
|
||||
RETRY_AFTER = "300"
|
||||
_SITE_PATH = re.compile(r"^/s/(?P<site>[^/]+)/(?P<endpoint>.+)$")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Request:
|
||||
method: str
|
||||
path: str
|
||||
headers: dict[str, str] = field(default_factory=dict)
|
||||
cookies: dict[str, str] = field(default_factory=dict)
|
||||
body: Any = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class Response:
|
||||
status: int
|
||||
body: Any = None
|
||||
headers: dict[str, str] = field(default_factory=dict)
|
||||
cookies: dict[str, str] = field(default_factory=dict)
|
||||
|
||||
|
||||
def ok(data: list[Any]) -> Response:
|
||||
return Response(200, {"meta": {"rc": "ok"}, "data": data})
|
||||
|
||||
|
||||
def error(status: int, msg: str) -> Response:
|
||||
return Response(status, {"meta": {"rc": "error", "msg": msg}, "data": []})
|
||||
|
||||
|
||||
NOT_FOUND = error(404, "api.err.NotFound")
|
||||
UNAUTHORIZED = error(401, "api.err.LoginRequired")
|
||||
|
||||
|
||||
def handle(sim: SimController, request: Request) -> Response:
|
||||
if sim.redirect:
|
||||
return Response(302, "", {"Location": "https://unifi.ui.com/"})
|
||||
path = urlsplit(request.path).path
|
||||
if request.method == "GET" and path == "/":
|
||||
return home(sim)
|
||||
if request.method == "POST" and path == ("/api/auth/login" if sim.unifi_os else "/api/login"):
|
||||
return login(sim, request)
|
||||
if sim.unifi_os and path.startswith(INTEGRATION + "/"):
|
||||
return integration(sim, request, path[len(INTEGRATION) + 1 :])
|
||||
prefix = UNIFI_OS_CLASSIC if sim.unifi_os else STANDALONE_CLASSIC
|
||||
if path.startswith(prefix + "/"):
|
||||
return classic(sim, request, path[len(prefix) :])
|
||||
return NOT_FOUND
|
||||
|
||||
|
||||
# -- login --------------------------------------------------------------------
|
||||
|
||||
|
||||
def home(sim: SimController) -> Response:
|
||||
"""UniFi OS serves its page; the standalone application sends the browser to /manage."""
|
||||
if sim.unifi_os:
|
||||
return Response(200, "<!DOCTYPE html><title>UniFi OS</title>")
|
||||
return Response(302, "", {"Location": "/manage"})
|
||||
|
||||
|
||||
def _cookie_name(sim: SimController) -> str:
|
||||
return "TOKEN" if sim.unifi_os else "unifises"
|
||||
|
||||
|
||||
def login(sim: SimController, request: Request) -> Response:
|
||||
body = request.body if isinstance(request.body, dict) else {}
|
||||
user, password = str(body.get("username") or ""), str(body.get("password") or "")
|
||||
if sim.failed_logins >= sim.max_failed_logins:
|
||||
reply = Response(429, {"code": "AUTHENTICATION_FAILED_LIMIT_REACHED"})
|
||||
reply.headers["Retry-After"] = RETRY_AFTER
|
||||
return reply
|
||||
if user in sim.mfa_users:
|
||||
return Response(499, {"code": "MFA_AUTH_REQUIRED"})
|
||||
if (user, password) != sim.admin:
|
||||
sim.failed_logins += 1
|
||||
return Response(401, {"code": "AUTHENTICATION_FAILED_INVALID_CREDENTIALS"})
|
||||
token, csrf = secrets.token_urlsafe(16), secrets.token_urlsafe(16)
|
||||
sim.sessions[token] = csrf
|
||||
reply = ok([]) if not sim.unifi_os else Response(200, {"username": user})
|
||||
reply.cookies[_cookie_name(sim)] = token
|
||||
if sim.unifi_os:
|
||||
reply.headers["X-CSRF-Token"] = csrf
|
||||
else:
|
||||
reply.cookies["csrf_token"] = csrf
|
||||
return reply
|
||||
|
||||
|
||||
def _key_ok(sim: SimController, request: Request) -> bool:
|
||||
return sim.has_integration and request.headers.get("x-api-key") == sim.api_key
|
||||
|
||||
|
||||
def _session_ok(sim: SimController, request: Request) -> bool:
|
||||
csrf = sim.sessions.get(request.cookies.get(_cookie_name(sim), ""))
|
||||
if csrf is None:
|
||||
return False
|
||||
return request.method == "GET" or request.headers.get("x-csrf-token") == csrf
|
||||
|
||||
|
||||
# -- the classic API ----------------------------------------------------------
|
||||
|
||||
|
||||
def classic(sim: SimController, request: Request, path: str) -> Response:
|
||||
if not (_key_ok(sim, request) or _session_ok(sim, request)):
|
||||
return UNAUTHORIZED
|
||||
if path == "/self/sites" and request.method == "GET":
|
||||
return ok([s.classic() for s in sim.sites])
|
||||
match = _SITE_PATH.match(path)
|
||||
if match is None:
|
||||
return NOT_FOUND
|
||||
if sim.site(match["site"]) is None:
|
||||
return error(400, "api.err.NoSiteContext")
|
||||
if request.method == "PUT":
|
||||
return _classic_put(sim, match["site"], match["endpoint"], request.body)
|
||||
if request.method == "GET":
|
||||
return _classic_get(sim, match["site"], match["endpoint"])
|
||||
return NOT_FOUND
|
||||
|
||||
|
||||
def _classic_get(sim: SimController, site: str, endpoint: str) -> Response:
|
||||
devices = sim.devices.get(site, [])
|
||||
if endpoint.startswith("stat/device/"):
|
||||
mac = endpoint.rsplit("/", 1)[1].lower()
|
||||
return ok([d for d in devices if str(d.get("mac")).lower() == mac])
|
||||
tables: dict[str, list[Any]] = {
|
||||
"stat/device": devices,
|
||||
"stat/sta": sim.stations if site == "default" else [],
|
||||
"stat/sysinfo": [{"version": sim.version, "name": "UniFi Network"}],
|
||||
"rest/networkconf": sim.networks,
|
||||
"rest/portconf": sim.port_profiles,
|
||||
"rest/wlanconf": sim.wlans,
|
||||
}
|
||||
return ok(tables[endpoint]) if endpoint in tables else NOT_FOUND
|
||||
|
||||
|
||||
def _classic_put(sim: SimController, site: str, endpoint: str, body: Any) -> Response:
|
||||
"""``PUT rest/device/<id>``: the keys given replace the device's, as on a controller."""
|
||||
if not endpoint.startswith("rest/device/") or not isinstance(body, dict):
|
||||
return NOT_FOUND
|
||||
device = sim.device_by_id(site, endpoint.rsplit("/", 1)[1])
|
||||
if device is None:
|
||||
return error(400, "api.err.IdInvalid")
|
||||
device.update(body)
|
||||
return ok([device])
|
||||
|
||||
|
||||
# -- the Integration API ------------------------------------------------------
|
||||
|
||||
|
||||
def integration(sim: SimController, request: Request, endpoint: str) -> Response:
|
||||
if not sim.has_integration:
|
||||
return NOT_FOUND
|
||||
if not _key_ok(sim, request):
|
||||
return Response(401, {"statusCode": 401, "statusName": "UNAUTHORIZED"})
|
||||
if request.method != "GET":
|
||||
return NOT_FOUND
|
||||
if endpoint == "info":
|
||||
return Response(200, {"applicationVersion": sim.version})
|
||||
items = _integration_list(sim, endpoint)
|
||||
if items is None:
|
||||
return Response(404, {"statusCode": 404, "statusName": "NOT_FOUND"})
|
||||
return Response(200, _page(items, parse_qs(urlsplit(request.path).query)))
|
||||
|
||||
|
||||
def _integration_list(sim: SimController, endpoint: str) -> list[Any] | None:
|
||||
if endpoint == "sites":
|
||||
return [s.integration() for s in sim.sites]
|
||||
if endpoint == "pending-devices":
|
||||
return [p for _, p in sim.pending] if sim.has_pending_devices else None
|
||||
parts = endpoint.split("/")
|
||||
if len(parts) == 3 and parts[0] == "sites" and parts[2] == "devices":
|
||||
site = sim.site_by_id(parts[1])
|
||||
return None if site is None else [integration_device(d) for d in sim.devices[site.name]]
|
||||
return None
|
||||
|
||||
|
||||
def _page(items: list[Any], query: dict[str, list[str]]) -> dict[str, Any]:
|
||||
offset = int((query.get("offset") or ["0"])[0])
|
||||
limit = min(int((query.get("limit") or [str(DEFAULT_PAGE)])[0]), MAX_PAGE)
|
||||
data = items[offset : offset + limit]
|
||||
return {
|
||||
"offset": offset,
|
||||
"limit": limit,
|
||||
"count": len(data),
|
||||
"totalCount": len(items),
|
||||
"data": data,
|
||||
}
|
||||
|
||||
|
||||
def encode(body: Any) -> bytes:
|
||||
return body.encode() if isinstance(body, str) else json.dumps(body).encode()
|
||||
@@ -0,0 +1,93 @@
|
||||
"""The simulated controller on HTTPS, in a thread of its own."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import ssl
|
||||
import tempfile
|
||||
import threading
|
||||
from http.cookies import SimpleCookie
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from unifi_sim.api import Request, encode, handle
|
||||
from unifi_sim.model import SimController
|
||||
from unifi_sim.tls import self_signed
|
||||
|
||||
|
||||
def _handler(sim: SimController, lock: threading.Lock) -> type[BaseHTTPRequestHandler]:
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, format: str, *args: Any) -> None: # noqa: A002
|
||||
"""Quiet: a test run is no place for an access log."""
|
||||
|
||||
def _serve(self) -> None:
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
raw = self.rfile.read(length) if length else b""
|
||||
cookies = SimpleCookie(self.headers.get("Cookie") or "")
|
||||
request = Request(
|
||||
method=self.command,
|
||||
path=self.path,
|
||||
headers={k.lower(): v for k, v in self.headers.items()},
|
||||
cookies={k: m.value for k, m in cookies.items()},
|
||||
body=json.loads(raw) if raw else None,
|
||||
)
|
||||
with lock:
|
||||
reply = handle(sim, request)
|
||||
payload = encode(reply.body)
|
||||
self.send_response(reply.status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(payload)))
|
||||
for name, value in reply.headers.items():
|
||||
self.send_header(name, value)
|
||||
for name, value in reply.cookies.items():
|
||||
self.send_header("Set-Cookie", f"{name}={value}; Path=/; Secure; HttpOnly")
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
|
||||
do_GET = do_POST = do_PUT = do_DELETE = _serve
|
||||
|
||||
return Handler
|
||||
|
||||
|
||||
class ControllerServer:
|
||||
""":class:`SimController` *sim* answering on ``https://<host>:<port>``."""
|
||||
|
||||
def __init__(self, sim: SimController, host: str = "127.0.0.1", port: int = 0) -> None:
|
||||
self.sim = sim
|
||||
self.host = host
|
||||
certificate = self_signed(host)
|
||||
self.fingerprint = certificate.fingerprint
|
||||
self._files = tempfile.TemporaryDirectory(prefix="unifi-sim-")
|
||||
cert, key = Path(self._files.name) / "cert.pem", Path(self._files.name) / "key.pem"
|
||||
cert.write_bytes(certificate.cert_pem)
|
||||
key.write_bytes(certificate.key_pem)
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
context.load_cert_chain(cert, key)
|
||||
self._server = ThreadingHTTPServer((host, port), _handler(sim, threading.Lock()))
|
||||
self._server.daemon_threads = True
|
||||
self._server.socket = context.wrap_socket(self._server.socket, server_side=True)
|
||||
self.port = int(self._server.server_address[1])
|
||||
self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
host = f"[{self.host}]" if ":" in self.host else self.host
|
||||
return f"https://{host}:{self.port}"
|
||||
|
||||
def start(self) -> ControllerServer:
|
||||
self._thread.start()
|
||||
return self
|
||||
|
||||
def stop(self) -> None:
|
||||
self._server.shutdown()
|
||||
self._server.server_close()
|
||||
self._files.cleanup()
|
||||
|
||||
|
||||
def serve_controller(
|
||||
sim: SimController, host: str = "127.0.0.1", port: int = 0
|
||||
) -> ControllerServer:
|
||||
return ControllerServer(sim, host, port).start()
|
||||
@@ -0,0 +1,189 @@
|
||||
"""What the simulated controller knows: its sites, devices, networks, and how it behaves.
|
||||
|
||||
Built from the repository's fixtures (``tests/fixtures``): one record per device,
|
||||
as the classic API keeps it. The Integration API's view is translated from the
|
||||
same records, so both APIs always describe the same site, as on a real
|
||||
controller.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import secrets
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
FIXTURES = Path(__file__).resolve().parents[2] / "tests" / "fixtures"
|
||||
#: Namespace for the ids the Integration API gives sites and devices.
|
||||
_IDS = uuid.UUID("6f1d2c3b-4a59-4e7f-8a6b-1c2d3e4f5a6b")
|
||||
|
||||
Record = dict[str, Any]
|
||||
|
||||
#: The classic numeric states, as the Integration API names them.
|
||||
_STATES = {1: "ONLINE", 2: "PENDING_ADOPTION", 4: "UPDATING", 5: "GETTING_READY", 7: "ADOPTING"}
|
||||
_FEATURES = {
|
||||
"usw": ["switching"],
|
||||
"uap": ["accessPoint"],
|
||||
"ugw": ["gateway"],
|
||||
"udm": ["gateway", "switching", "accessPoint"],
|
||||
"uxg": ["gateway"],
|
||||
}
|
||||
#: The first version with the Integration API and API keys; the first with pending devices.
|
||||
INTEGRATION_FROM = (9, 0, 108)
|
||||
PENDING_FROM = (10, 0, 0)
|
||||
|
||||
#: The Default LAN of the fixtures, and one VLAN beside it.
|
||||
DEFAULT_NETWORK = "678a1b2c3d4e5f6071829307"
|
||||
IOT_NETWORK: Record = {
|
||||
"_id": "6790000000000000000000a1",
|
||||
"name": "IoT",
|
||||
"purpose": "corporate",
|
||||
"vlan_enabled": True,
|
||||
"vlan": 20,
|
||||
}
|
||||
#: Port profiles the fixtures' ports name: "All" carries everything, "IoT" only VLAN 20.
|
||||
PORT_PROFILES: list[Record] = [
|
||||
{
|
||||
"_id": "5a32aa4ee4babd4452422ddd22222",
|
||||
"name": "All",
|
||||
"native_networkconf_id": DEFAULT_NETWORK,
|
||||
"forward": "all",
|
||||
},
|
||||
{
|
||||
"_id": "5e1b309714bd614afd3d11a7",
|
||||
"name": "IoT",
|
||||
"native_networkconf_id": IOT_NETWORK["_id"],
|
||||
"forward": "native",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def version_tuple(version: str) -> tuple[int, ...]:
|
||||
return tuple(int(part) for part in version.split(".") if part.isdigit())
|
||||
|
||||
|
||||
def load(name: str, root: Path = FIXTURES) -> Any:
|
||||
return json.loads((root / name).read_text())
|
||||
|
||||
|
||||
def sim_id(kind: str, name: str) -> str:
|
||||
"""The stable Integration API id of a site or device."""
|
||||
return str(uuid.uuid5(_IDS, f"{kind}:{name}"))
|
||||
|
||||
|
||||
def integration_device(record: Record) -> Record:
|
||||
"""A classic ``stat/device`` record as ``/v1/sites/{id}/devices`` lists it."""
|
||||
return {
|
||||
"id": sim_id("device", str(record["mac"])),
|
||||
"macAddress": record["mac"],
|
||||
"ipAddress": record.get("ip"),
|
||||
"name": record.get("name") or "",
|
||||
"model": record.get("model") or "",
|
||||
"state": _STATES.get(record.get("state", 0), "OFFLINE"),
|
||||
"supported": True,
|
||||
"firmwareVersion": record.get("version"),
|
||||
"firmwareUpdatable": bool(record.get("upgradable")),
|
||||
"features": _FEATURES.get(str(record.get("type")), []),
|
||||
"interfaces": ["ports"] if record.get("port_table") else [],
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class SimSite:
|
||||
name: str
|
||||
desc: str
|
||||
|
||||
@property
|
||||
def id(self) -> str:
|
||||
return sim_id("site", self.name)
|
||||
|
||||
def classic(self) -> Record:
|
||||
return {"_id": self.id, "name": self.name, "desc": self.desc, "role": "admin"}
|
||||
|
||||
def integration(self) -> Record:
|
||||
return {"id": self.id, "internalReference": self.name, "name": self.desc}
|
||||
|
||||
|
||||
@dataclass
|
||||
class SimController:
|
||||
"""A UniFi Network application: its data and the rules it answers by."""
|
||||
|
||||
version: str = "10.6.106"
|
||||
unifi_os: bool = True
|
||||
sites: list[SimSite] = field(default_factory=list)
|
||||
devices: dict[str, list[Record]] = field(default_factory=dict)
|
||||
#: Devices waiting for adoption: (target site, Integration API record).
|
||||
pending: list[tuple[str, Record]] = field(default_factory=list)
|
||||
networks: list[Record] = field(default_factory=list)
|
||||
port_profiles: list[Record] = field(default_factory=list)
|
||||
wlans: list[Record] = field(default_factory=list)
|
||||
stations: list[Record] = field(default_factory=list)
|
||||
api_key: str = field(default_factory=lambda: secrets.token_urlsafe(24))
|
||||
admin: tuple[str, str] = ("admin", "sim-password")
|
||||
mfa_users: frozenset[str] = frozenset({"cloud@example.com"})
|
||||
max_failed_logins: int = 5
|
||||
#: Every answer a redirect elsewhere, as behind a misdirected proxy.
|
||||
redirect: bool = False
|
||||
failed_logins: int = 0
|
||||
#: Session cookie -> its CSRF token.
|
||||
sessions: dict[str, str] = field(default_factory=dict)
|
||||
|
||||
@classmethod
|
||||
def from_fixtures(
|
||||
cls,
|
||||
*,
|
||||
version: str = "10.6.106",
|
||||
unifi_os: bool = True,
|
||||
redirect: bool = False,
|
||||
root: Path = FIXTURES,
|
||||
) -> SimController:
|
||||
"""Two sites: ``default`` with a PoE switch, a Flex Mini, an AP and one
|
||||
device waiting for adoption; ``branch`` with a small switch."""
|
||||
|
||||
def record(name: str) -> Record:
|
||||
return dict(load(f"controller/{name}-stat-device.json", root))
|
||||
|
||||
default, branch = SimSite("default", "Default"), SimSite("branch", "Branch office")
|
||||
pending = load("integration/v10.6.106-pending-devices.json", root)["data"]
|
||||
return cls(
|
||||
version=version,
|
||||
unifi_os=unifi_os,
|
||||
redirect=redirect,
|
||||
sites=[default, branch],
|
||||
devices={
|
||||
"default": [
|
||||
record("us16p150-4.0.66"),
|
||||
record("usmini-1.8.4"),
|
||||
record("u7pg2-4.0.69"),
|
||||
],
|
||||
"branch": [record("us8-4.0.66")],
|
||||
},
|
||||
pending=[("default", {**p, "adoptionTargetSiteIds": [default.id]}) for p in pending],
|
||||
networks=[*load("controller/networkconf.json", root), dict(IOT_NETWORK)],
|
||||
port_profiles=[dict(p) for p in PORT_PROFILES],
|
||||
wlans=load("controller/wlanconf.json", root),
|
||||
stations=load("controller/stat-sta.json", root),
|
||||
)
|
||||
|
||||
# -- what this version offers --------------------------------------------
|
||||
|
||||
@property
|
||||
def has_integration(self) -> bool:
|
||||
return self.unifi_os and version_tuple(self.version) >= INTEGRATION_FROM
|
||||
|
||||
@property
|
||||
def has_pending_devices(self) -> bool:
|
||||
return self.has_integration and version_tuple(self.version) >= PENDING_FROM
|
||||
|
||||
# -- lookups ---------------------------------------------------------------
|
||||
|
||||
def site(self, name: str) -> SimSite | None:
|
||||
return next((s for s in self.sites if s.name == name), None)
|
||||
|
||||
def site_by_id(self, site_id: str) -> SimSite | None:
|
||||
return next((s for s in self.sites if s.id == site_id), None)
|
||||
|
||||
def device_by_id(self, site: str, device_id: str) -> Record | None:
|
||||
return next((d for d in self.devices.get(site, []) if d.get("_id") == device_id), None)
|
||||
@@ -0,0 +1,158 @@
|
||||
"""A simulated UniFi switch or access point on SSH: it answers the commands a driver runs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import socket
|
||||
import threading
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import paramiko
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
||||
from paramiko.common import (
|
||||
AUTH_FAILED,
|
||||
AUTH_SUCCESSFUL,
|
||||
OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED,
|
||||
OPEN_SUCCEEDED,
|
||||
)
|
||||
|
||||
from unifi_sim.model import FIXTURES
|
||||
|
||||
COMMAND_WAIT = 5.0
|
||||
NOT_FOUND = 127
|
||||
|
||||
|
||||
@dataclass
|
||||
class SimDevice:
|
||||
"""A device's shell: its ``mca-dump``, its ``running.cfg`` and its login."""
|
||||
|
||||
dump: dict[str, Any]
|
||||
running_cfg: str = ""
|
||||
username: str = "ubnt"
|
||||
password: str = "ubnt"
|
||||
commands: dict[str, str] = field(default_factory=dict)
|
||||
|
||||
@classmethod
|
||||
def us24(cls, root: Path = FIXTURES) -> SimDevice:
|
||||
"""A US-24 (Gen1) on 7.1.26 that no controller has adopted."""
|
||||
return cls(
|
||||
dump=json.loads((root / "ssh/us24-7.1.26-mca-dump.json").read_text()),
|
||||
running_cfg=(root / "ssh/us24-7.1.26-running.cfg").read_text(),
|
||||
)
|
||||
|
||||
def answer(self, command: str) -> tuple[int, str, str]:
|
||||
"""Exit status, standard output and standard error of *command*."""
|
||||
if command == "mca-dump":
|
||||
return 0, json.dumps(self.dump), ""
|
||||
if command == "cat /tmp/running.cfg":
|
||||
return 0, self.running_cfg, ""
|
||||
if command in self.commands:
|
||||
return 0, self.commands[command], ""
|
||||
return NOT_FOUND, "", f"sh: {command.split()[0] if command else ''}: not found\n"
|
||||
|
||||
|
||||
class _Session(paramiko.ServerInterface):
|
||||
def __init__(self, device: SimDevice) -> None:
|
||||
self.device = device
|
||||
self.command = ""
|
||||
self.ready = threading.Event()
|
||||
|
||||
def get_allowed_auths(self, username: str) -> str:
|
||||
return "password"
|
||||
|
||||
def check_auth_password(self, username: str, password: str) -> int:
|
||||
if (username, password) == (self.device.username, self.device.password):
|
||||
return AUTH_SUCCESSFUL
|
||||
return AUTH_FAILED
|
||||
|
||||
def check_channel_request(self, kind: str, chanid: int) -> int:
|
||||
if kind == "session":
|
||||
return OPEN_SUCCEEDED
|
||||
return OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
|
||||
|
||||
def check_channel_exec_request(self, channel: Any, command: bytes) -> bool:
|
||||
self.command = command.decode("utf-8", "replace")
|
||||
self.ready.set()
|
||||
return True
|
||||
|
||||
|
||||
def _host_key() -> paramiko.PKey:
|
||||
pem = Ed25519PrivateKey.generate().private_bytes(
|
||||
serialization.Encoding.PEM,
|
||||
serialization.PrivateFormat.OpenSSH,
|
||||
serialization.NoEncryption(),
|
||||
)
|
||||
return paramiko.Ed25519Key.from_private_key(io.StringIO(pem.decode()))
|
||||
|
||||
|
||||
class DeviceServer:
|
||||
""":class:`SimDevice` *device* answering SSH on ``<host>:<port>``."""
|
||||
|
||||
def __init__(self, device: SimDevice, host: str = "127.0.0.1", port: int = 0) -> None:
|
||||
self.device = device
|
||||
self.host = host
|
||||
self.key = _host_key()
|
||||
self._socket = socket.create_server((host, port))
|
||||
self._socket.settimeout(0.5)
|
||||
self.port = int(self._socket.getsockname()[1])
|
||||
self._stopped = threading.Event()
|
||||
self._thread = threading.Thread(target=self._accept, daemon=True)
|
||||
|
||||
@property
|
||||
def host_key(self) -> dict[str, str]:
|
||||
"""The key as ``ssh_host_keys`` expects one: the two fields of a known_hosts line."""
|
||||
return {"key_type": self.key.get_name(), "key": self.key.get_base64()}
|
||||
|
||||
def start(self) -> DeviceServer:
|
||||
self._thread.start()
|
||||
return self
|
||||
|
||||
def stop(self) -> None:
|
||||
self._stopped.set()
|
||||
self._thread.join(timeout=2)
|
||||
self._socket.close()
|
||||
|
||||
def _accept(self) -> None:
|
||||
while not self._stopped.is_set():
|
||||
try:
|
||||
conn, _ = self._socket.accept()
|
||||
except TimeoutError:
|
||||
continue
|
||||
except OSError:
|
||||
return
|
||||
threading.Thread(target=self._serve, args=(conn,), daemon=True).start()
|
||||
|
||||
def _serve(self, conn: socket.socket) -> None:
|
||||
transport = paramiko.Transport(conn)
|
||||
transport.add_server_key(self.key)
|
||||
session = _Session(self.device)
|
||||
try:
|
||||
transport.start_server(server=session)
|
||||
while transport.is_active() and not self._stopped.is_set():
|
||||
channel = transport.accept(timeout=0.5)
|
||||
if channel is not None:
|
||||
self._run(session, channel)
|
||||
except (paramiko.SSHException, EOFError, OSError):
|
||||
pass
|
||||
finally:
|
||||
transport.close()
|
||||
|
||||
def _run(self, session: _Session, channel: Any) -> None:
|
||||
if not session.ready.wait(COMMAND_WAIT):
|
||||
channel.close()
|
||||
return
|
||||
session.ready.clear()
|
||||
status, out, err = self.device.answer(session.command)
|
||||
channel.sendall(out.encode())
|
||||
if err:
|
||||
channel.sendall_stderr(err.encode())
|
||||
channel.send_exit_status(status)
|
||||
channel.close()
|
||||
|
||||
|
||||
def serve_device(device: SimDevice, host: str = "127.0.0.1", port: int = 0) -> DeviceServer:
|
||||
return DeviceServer(device, host, port).start()
|
||||
@@ -0,0 +1,52 @@
|
||||
"""A self-signed certificate, as every UniFi console ships one."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import hashlib
|
||||
import ipaddress
|
||||
from dataclasses import dataclass
|
||||
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.x509.oid import NameOID
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Certificate:
|
||||
cert_pem: bytes
|
||||
key_pem: bytes
|
||||
#: SHA-256 of the DER certificate, as ``napalm_device_types.tls_certificates`` writes it.
|
||||
fingerprint: str
|
||||
|
||||
|
||||
def self_signed(host: str) -> Certificate:
|
||||
key = ec.generate_private_key(ec.SECP256R1())
|
||||
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "UniFi")])
|
||||
now = datetime.datetime.now(datetime.UTC)
|
||||
try:
|
||||
alt: x509.GeneralName = x509.IPAddress(ipaddress.ip_address(host))
|
||||
except ValueError:
|
||||
alt = x509.DNSName(host)
|
||||
cert = (
|
||||
x509.CertificateBuilder()
|
||||
.subject_name(name)
|
||||
.issuer_name(name)
|
||||
.public_key(key.public_key())
|
||||
.serial_number(x509.random_serial_number())
|
||||
.not_valid_before(now - datetime.timedelta(days=1))
|
||||
.not_valid_after(now + datetime.timedelta(days=3650))
|
||||
.add_extension(x509.SubjectAlternativeName([alt]), critical=False)
|
||||
.sign(key, hashes.SHA256())
|
||||
)
|
||||
digest = hashlib.sha256(cert.public_bytes(serialization.Encoding.DER)).hexdigest().upper()
|
||||
return Certificate(
|
||||
cert_pem=cert.public_bytes(serialization.Encoding.PEM),
|
||||
key_pem=key.private_bytes(
|
||||
serialization.Encoding.PEM,
|
||||
serialization.PrivateFormat.PKCS8,
|
||||
serialization.NoEncryption(),
|
||||
),
|
||||
fingerprint="SHA256:" + ":".join(digest[i : i + 2] for i in range(0, len(digest), 2)),
|
||||
)
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Shared fixtures: recorded UniFi output, anonymised (see tests/fixtures/README.md)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
FIXTURES = pathlib.Path(__file__).parent / "fixtures"
|
||||
|
||||
|
||||
def load(name: str) -> Any:
|
||||
"""A fixture file: JSON parsed, anything else as text."""
|
||||
path = FIXTURES / name
|
||||
text = path.read_text()
|
||||
return json.loads(text) if path.suffix == ".json" else text
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def us16() -> dict[str, Any]:
|
||||
"""A US-16-150W on 4.0.66, as the controller's ``stat/device`` reports it (old LLDP shape)."""
|
||||
return load("controller/us16p150-4.0.66-stat-device.json") # type: ignore[no-any-return]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def us8() -> dict[str, Any]:
|
||||
return load("controller/us8-4.0.66-stat-device.json") # type: ignore[no-any-return]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def usmini() -> dict[str, Any]:
|
||||
"""A USW Flex Mini on 1.8.4: the top-level LLDP shape."""
|
||||
return load("controller/usmini-1.8.4-stat-device.json") # type: ignore[no-any-return]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def uap() -> dict[str, Any]:
|
||||
"""A UAP-AC-Pro (U7PG2) on 4.0.69, as the controller reports it."""
|
||||
return load("controller/u7pg2-4.0.69-stat-device.json") # type: ignore[no-any-return]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def us24_dump() -> dict[str, Any]:
|
||||
"""A US-24 (Gen1) on 7.1.26: ``mca-dump`` over SSH, no controller in between."""
|
||||
return load("ssh/us24-7.1.26-mca-dump.json") # type: ignore[no-any-return]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def us24_cfg() -> str:
|
||||
return load("ssh/us24-7.1.26-running.cfg") # type: ignore[no-any-return]
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Stand-ins for a controller and an SSH shell, answering from recorded output."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from napalm.base.exceptions import CommandErrorException
|
||||
|
||||
|
||||
class FakeClient:
|
||||
"""The classic API of a controller: one answer per endpoint, whatever the site."""
|
||||
|
||||
def __init__(self, data: dict[str, list[Any]]) -> None:
|
||||
self.data = data
|
||||
self.asked: list[tuple[str, str]] = []
|
||||
|
||||
def classic_get(self, site: str, endpoint: str) -> list[Any]:
|
||||
self.asked.append((site, endpoint))
|
||||
return self.data.get(endpoint, [])
|
||||
|
||||
|
||||
class FakeShell:
|
||||
"""A device's shell: one answer per command; any other command fails."""
|
||||
|
||||
def __init__(self, answers: dict[str, str]) -> None:
|
||||
self.answers = answers
|
||||
self.ran: list[str] = []
|
||||
|
||||
def run(self, command: str) -> str:
|
||||
self.ran.append(command)
|
||||
if command not in self.answers:
|
||||
raise CommandErrorException(f"{command}: not found")
|
||||
return self.answers[command]
|
||||
Vendored
+50
@@ -0,0 +1,50 @@
|
||||
# Fixtures
|
||||
|
||||
**None of these is a recording of our own yet.** They come from two open-source
|
||||
projects and from Ubiquiti's published API description, and are replaced by
|
||||
recordings from the first onboarded UniFi devices. Every file went through
|
||||
`tools/sanitize.py`: controller secrets (`x_*` keys, tokens) redacted, MAC
|
||||
addresses that are not part of a test's point replaced by locally administered
|
||||
ones (`02:00:00:…`), addresses moved into documentation or private ranges.
|
||||
|
||||
## `controller/`: the classic API's answers
|
||||
|
||||
The `data` of one classic API answer each, from the test data of
|
||||
[aiounifi](https://github.com/Kane610/aiounifi) (`tests/fixtures.py`), MIT,
|
||||
Copyright (c) 2018 Robert Svensson; the licence is in `controller/LICENSE-aiounifi`.
|
||||
|
||||
| File | What it is |
|
||||
|---|---|
|
||||
| `us16p150-4.0.66-stat-device.json` | US-16-150W, firmware 4.0.66: `stat/device` entry, per-port LLDP |
|
||||
| `us8-4.0.66-stat-device.json` | US-8, firmware 4.0.66 |
|
||||
| `usmini-1.8.4-stat-device.json` | USW Flex Mini, firmware 1.8.4: top-level LLDP |
|
||||
| `u7pg2-4.0.69-stat-device.json` | UAP-AC-Pro, firmware 4.0.69 |
|
||||
| `ugw3-4.4.44-stat-device.json` | USG, firmware 4.4.44 |
|
||||
| `wlanconf.json`, `networkconf.json` | `rest/wlanconf`, `rest/networkconf` |
|
||||
| `self-sites.json` | `self/sites` |
|
||||
| `login-unifios.json` | the answer to a UniFi OS login |
|
||||
| `stat-sta.json` | `stat/sta`: aiounifi's wireless client, plus one wired client written by hand |
|
||||
|
||||
## `ssh/`: a switch read without a controller
|
||||
|
||||
From the test data of [abates/napalm-unifi](https://github.com/abates/napalm-unifi)
|
||||
(`tests/napalm_unifi/testdata/usw`), Apache-2.0 (no NOTICE file).
|
||||
|
||||
| File | What it is |
|
||||
|---|---|
|
||||
| `us24-7.1.26-mca-dump.json` | US-24 (Gen1), firmware 7.1.26: `mca-dump` |
|
||||
| `us24-7.1.26-running.cfg` | the same switch's `/tmp/running.cfg` |
|
||||
|
||||
## `integration/`: the Integration API
|
||||
|
||||
Assembled by hand from the schemas of Ubiquiti's published OpenAPI description of
|
||||
the Network application 10.6.106 (`/proxy/network/integration/v1`), which has no
|
||||
whole-answer examples. The devices carry the MACs of the `controller/` fixtures so
|
||||
that both APIs describe the same site.
|
||||
|
||||
| File | What it is |
|
||||
|---|---|
|
||||
| `v10.6.106-info.json` | `GET /v1/info` |
|
||||
| `v10.6.106-sites.json` | `GET /v1/sites` |
|
||||
| `v10.6.106-devices.json` | `GET /v1/sites/{siteId}/devices` |
|
||||
| `v10.6.106-pending-devices.json` | `GET /v1/pending-devices`: one U6-LR waiting for adoption |
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2018 Robert Svensson
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
{
|
||||
"avatar": "",
|
||||
"avatar_relative_path": "",
|
||||
"cloud_access_granted": false,
|
||||
"create_time": 1585163886,
|
||||
"email": "",
|
||||
"email_status": "UNVERIFIED",
|
||||
"extras": null,
|
||||
"first_name": "Testing",
|
||||
"full_name": "Testing Testing",
|
||||
"groups": [],
|
||||
"id": "868d288b-a642-4209-a768-8425498fa928",
|
||||
"isOwner": false,
|
||||
"isSuperAdmin": true,
|
||||
"last_name": "Testing",
|
||||
"local_account_exist": true,
|
||||
"nfc_display_id": "",
|
||||
"nfc_token": "",
|
||||
"password_revision": 1585163886,
|
||||
"permissions": {
|
||||
"access.management": [
|
||||
"admin"
|
||||
],
|
||||
"led.management": [
|
||||
"admin"
|
||||
],
|
||||
"network.management": [
|
||||
"admin"
|
||||
],
|
||||
"protect.management": [
|
||||
"admin"
|
||||
],
|
||||
"system.management.location": [
|
||||
"admin"
|
||||
],
|
||||
"system.management.user": [
|
||||
"admin"
|
||||
],
|
||||
"talk.management": [
|
||||
"admin"
|
||||
]
|
||||
},
|
||||
"phone": "",
|
||||
"roles": [
|
||||
{
|
||||
"level": 2,
|
||||
"name": "Super Administrator",
|
||||
"system_key": "super_administrator",
|
||||
"system_role": true,
|
||||
"unique_id": "ddf31242-c4f1-4dbc-b362-d0b220cae124"
|
||||
}
|
||||
],
|
||||
"scopes": [
|
||||
"view:user_timezone",
|
||||
"view:user",
|
||||
"view:systemlog",
|
||||
"view:settings",
|
||||
"view:role",
|
||||
"view:permission:viewer",
|
||||
"view:permission:admin",
|
||||
"view:notification",
|
||||
"view:location_policy",
|
||||
"view:location_device",
|
||||
"view:location_activity",
|
||||
"view:location",
|
||||
"view:holiday_timezone",
|
||||
"view:holiday",
|
||||
"view:group",
|
||||
"view:door_group",
|
||||
"view:controller:talk",
|
||||
"view:controller:protect",
|
||||
"view:controller:network",
|
||||
"view:controller:led",
|
||||
"view:controller:access",
|
||||
"view:cloud_access",
|
||||
"view:app:users",
|
||||
"view:app:settings",
|
||||
"view:app:locations",
|
||||
"view:access.visitor",
|
||||
"view:access.systemlog",
|
||||
"view:access.schedule",
|
||||
"view:access.policy",
|
||||
"view:access.nfc_card",
|
||||
"view:access.device",
|
||||
"view:access.dashboard",
|
||||
"update:access.device",
|
||||
"systemlog:user",
|
||||
"systemlog:system",
|
||||
"systemlog:location",
|
||||
"systemlog:access",
|
||||
"notify:user",
|
||||
"notify:location",
|
||||
"notify:access",
|
||||
"manage:controller:talk",
|
||||
"manage:controller:protect",
|
||||
"manage:controller:network",
|
||||
"manage:controller:led",
|
||||
"manage:controller:access",
|
||||
"edit:user_timezone",
|
||||
"edit:user",
|
||||
"edit:systemlog",
|
||||
"edit:settings",
|
||||
"edit:role",
|
||||
"edit:permission:viewer",
|
||||
"edit:permission:admin",
|
||||
"edit:notification",
|
||||
"edit:location_policy",
|
||||
"edit:location_device",
|
||||
"edit:location_activity",
|
||||
"edit:location",
|
||||
"edit:holiday_timezone",
|
||||
"edit:holiday",
|
||||
"edit:group",
|
||||
"edit:feedback",
|
||||
"edit:door_group",
|
||||
"edit:access.visitor",
|
||||
"edit:access.schedule",
|
||||
"edit:access.policy",
|
||||
"edit:access.nfc_card",
|
||||
"edit:access.device",
|
||||
"delete:access.device",
|
||||
"assign:role",
|
||||
"adopt:access.device"
|
||||
],
|
||||
"sso_account": "",
|
||||
"sso_username": "",
|
||||
"sso_uuid": "",
|
||||
"status": "ACTIVE",
|
||||
"uid_sso_account": "",
|
||||
"uid_sso_id": "",
|
||||
"unique_id": "868d288b-a642-4209-a768-8425498fa928",
|
||||
"update_time": 1585167486,
|
||||
"username": "Testing1"
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
[
|
||||
{
|
||||
"_id": "678a1b2c3d4e5f6071829304",
|
||||
"attr_hidden_id": "WAN",
|
||||
"attr_no_delete": true,
|
||||
"enabled": true,
|
||||
"name": "Primary (WAN1)",
|
||||
"purpose": "wan",
|
||||
"site_id": "5a32aa4ee4b0412345678910",
|
||||
"wan_dns_preference": "auto",
|
||||
"wan_failover_priority": 1,
|
||||
"wan_load_balance_type": "weighted",
|
||||
"wan_load_balance_weight": 80,
|
||||
"wan_networkgroup": "WAN",
|
||||
"wan_type": "dhcp"
|
||||
},
|
||||
{
|
||||
"_id": "678a1b2c3d4e5f6071829305",
|
||||
"attr_hidden_id": "WAN2",
|
||||
"attr_no_delete": true,
|
||||
"enabled": true,
|
||||
"name": "Secondary (WAN2)",
|
||||
"purpose": "wan",
|
||||
"site_id": "5a32aa4ee4b0412345678910",
|
||||
"wan_dns_preference": "auto",
|
||||
"wan_failover_priority": 2,
|
||||
"wan_load_balance_type": "weighted",
|
||||
"wan_load_balance_weight": 20,
|
||||
"wan_networkgroup": "WAN2",
|
||||
"wan_type": "dhcp"
|
||||
},
|
||||
{
|
||||
"_id": "678a1b2c3d4e5f6071829306",
|
||||
"enabled": true,
|
||||
"name": "Backup (5G)",
|
||||
"purpose": "wan",
|
||||
"site_id": "5a32aa4ee4b0412345678910",
|
||||
"wan_failover_priority": 3,
|
||||
"wan_load_balance_type": "failover-only",
|
||||
"wan_networkgroup": "WAN3"
|
||||
},
|
||||
{
|
||||
"_id": "678a1b2c3d4e5f6071829307",
|
||||
"enabled": true,
|
||||
"internet_access_enabled": true,
|
||||
"ip_subnet": "192.168.1.1/24",
|
||||
"name": "Default",
|
||||
"purpose": "corporate",
|
||||
"site_id": "5a32aa4ee4b0412345678910",
|
||||
"vlan_enabled": false
|
||||
}
|
||||
]
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"_id": "5e231c10931eb902acf25112",
|
||||
"attr_hidden_id": "default",
|
||||
"attr_no_delete": true,
|
||||
"desc": "Default",
|
||||
"name": "default",
|
||||
"role": "admin"
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"rc": "ok"
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
[
|
||||
{
|
||||
"_id": "5a32b0c9e4b047ede36a85cc",
|
||||
"ap_mac": "80:2a:a8:00:01:02",
|
||||
"assoc_time": 1587753456,
|
||||
"authorized": true,
|
||||
"bssid": "80:2a:a8:00:01:02",
|
||||
"channel": 44,
|
||||
"essid": "SSID",
|
||||
"hostname": "client",
|
||||
"ip": "192.168.0.1",
|
||||
"is_guest": false,
|
||||
"is_wired": false,
|
||||
"mac": "00:00:00:00:00:01",
|
||||
"name": "Client 1",
|
||||
"network": "LAN",
|
||||
"noise": -106,
|
||||
"radio": "na",
|
||||
"radio_name": "wifi1",
|
||||
"radio_proto": "ac",
|
||||
"rssi": 35,
|
||||
"rx_rate": 400000,
|
||||
"signal": -61,
|
||||
"site_id": "5a32aa4ee4b0412345678910",
|
||||
"tx_power": 34,
|
||||
"tx_rate": 216000,
|
||||
"uptime": 11904,
|
||||
"vlan": 0
|
||||
},
|
||||
{
|
||||
"_id": "5a32b0c9e4b047ede36a85cd",
|
||||
"hostname": "wired",
|
||||
"ip": "192.168.0.2",
|
||||
"is_wired": true,
|
||||
"mac": "00:00:00:00:00:02",
|
||||
"sw_mac": "fc:ec:da:11:22:33",
|
||||
"sw_port": 3,
|
||||
"uptime": 300
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,742 @@
|
||||
{
|
||||
"_id": "5a4c022",
|
||||
"_uptime": 3971849,
|
||||
"adoptable_when_upgraded": false,
|
||||
"adopted": true,
|
||||
"antenna_table": [
|
||||
{
|
||||
"default": true,
|
||||
"id": 4,
|
||||
"name": "Combined",
|
||||
"wifi0_gain": 3,
|
||||
"wifi1_gain": 3
|
||||
}
|
||||
],
|
||||
"architecture": "mips",
|
||||
"board_rev": 21,
|
||||
"bytes": 202573081705,
|
||||
"bytes-d": 4275308,
|
||||
"bytes-r": 178137,
|
||||
"cfgversion": "97f3011a27fcfd5b",
|
||||
"config_network": {
|
||||
"ip": "192.168.1.7",
|
||||
"type": "dhcp"
|
||||
},
|
||||
"connect_request_ip": "192.168.0.11",
|
||||
"connect_request_port": "48591",
|
||||
"considered_lost_at": 1588175837,
|
||||
"country_code": 0,
|
||||
"countrycode_table": [],
|
||||
"device_id": "235678987654345678",
|
||||
"downlink_table": [],
|
||||
"element_peer_mac": "",
|
||||
"ethernet_table": [
|
||||
{
|
||||
"mac": "80:2a:a8:00:01:02",
|
||||
"name": "eth0",
|
||||
"num_port": 2
|
||||
}
|
||||
],
|
||||
"fw_caps": 25099583,
|
||||
"gateway_mac": "192.168.0.1",
|
||||
"guest-num_sta": 0,
|
||||
"guest-wlan-num_sta": 0,
|
||||
"guest_token": "REDACTED",
|
||||
"has_eth1": false,
|
||||
"has_fan": false,
|
||||
"has_speaker": false,
|
||||
"has_temperature": false,
|
||||
"hash_id": "REDACTED",
|
||||
"hide_ch_width": "none",
|
||||
"hw_caps": 0,
|
||||
"inform_ip": "192.168.0.5",
|
||||
"inform_url": "http://192.168.0.6:8080/inform",
|
||||
"ip": "192.168.0.4",
|
||||
"isolated": false,
|
||||
"kernel_version": "4.4.153",
|
||||
"known_cfgversion": "23434545676787654",
|
||||
"last_seen": 1588175726,
|
||||
"last_uplink": {
|
||||
"uplink_mac": "f0:9f:11:22:33:44",
|
||||
"uplink_remote_port": 6
|
||||
},
|
||||
"led_override": "on",
|
||||
"license_state": "registered",
|
||||
"locating": false,
|
||||
"mac": "80:2a:a8:00:01:02",
|
||||
"manufacturer_id": 4,
|
||||
"meshv3_peer_mac": "",
|
||||
"model": "U7PG2",
|
||||
"name": "ACCESS POINT AC PRO",
|
||||
"next_heartbeat_at": 1588175763,
|
||||
"next_interval": 27,
|
||||
"num_sta": 12,
|
||||
"outdoor_mode_override": "default",
|
||||
"port_table": [
|
||||
{
|
||||
"aggregated_by": false,
|
||||
"attr_no_edit": true,
|
||||
"autoneg": true,
|
||||
"bytes-r": 177399,
|
||||
"enable": true,
|
||||
"flowctrl_rx": false,
|
||||
"flowctrl_tx": false,
|
||||
"full_duplex": true,
|
||||
"is_uplink": false,
|
||||
"jumbo": false,
|
||||
"mac_table": [
|
||||
{
|
||||
"age": 1,
|
||||
"mac": "10:00:00:00:00:01",
|
||||
"static": false,
|
||||
"uptime": 3971792,
|
||||
"vlan": 1
|
||||
}
|
||||
],
|
||||
"masked": false,
|
||||
"media": "GE",
|
||||
"name": "Main",
|
||||
"op_mode": "switch",
|
||||
"poe_caps": 0,
|
||||
"port_delta": {
|
||||
"rx_bytes": 4136705,
|
||||
"rx_packets": 2930,
|
||||
"time_delta": 24,
|
||||
"time_delta_activity": 24,
|
||||
"tx_bytes": 120873,
|
||||
"tx_packets": 824
|
||||
},
|
||||
"port_idx": 1,
|
||||
"port_poe": false,
|
||||
"portconf_id": "5a32aa4",
|
||||
"rx_broadcast": 2323942,
|
||||
"rx_bytes": 2275836363755,
|
||||
"rx_bytes-r": 172362,
|
||||
"rx_dropped": 0,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 5051177,
|
||||
"rx_packets": 1574257888,
|
||||
"speed": 1000,
|
||||
"stp_pathcost": 0,
|
||||
"stp_state": "forwarding",
|
||||
"tx_broadcast": 218413,
|
||||
"tx_bytes": 53516753422,
|
||||
"tx_bytes-r": 5036,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_multicast": 2935588,
|
||||
"tx_packets": 333052121,
|
||||
"up": true
|
||||
},
|
||||
{
|
||||
"aggregated_by": false,
|
||||
"autoneg": false,
|
||||
"bytes-r": 0,
|
||||
"enable": true,
|
||||
"flowctrl_rx": false,
|
||||
"flowctrl_tx": false,
|
||||
"full_duplex": false,
|
||||
"is_uplink": false,
|
||||
"jumbo": false,
|
||||
"mac_table": [],
|
||||
"masked": false,
|
||||
"media": "GE",
|
||||
"name": "Secondary",
|
||||
"op_mode": "switch",
|
||||
"poe_caps": 0,
|
||||
"port_delta": {
|
||||
"time_delta": 24,
|
||||
"time_delta_activity": 1588175726
|
||||
},
|
||||
"port_idx": 2,
|
||||
"port_poe": false,
|
||||
"portconf_id": "5a32aa4",
|
||||
"rx_broadcast": 0,
|
||||
"rx_bytes": 0,
|
||||
"rx_bytes-r": 0,
|
||||
"rx_dropped": 0,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 0,
|
||||
"rx_packets": 0,
|
||||
"speed": 0,
|
||||
"stp_pathcost": 0,
|
||||
"stp_state": "forwarding",
|
||||
"tx_broadcast": 0,
|
||||
"tx_bytes": 0,
|
||||
"tx_bytes-r": 0,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_multicast": 0,
|
||||
"tx_packets": 0,
|
||||
"up": false
|
||||
}
|
||||
],
|
||||
"radio_table": [
|
||||
{
|
||||
"antenna_gain": 6,
|
||||
"builtin_ant_gain": 3,
|
||||
"builtin_antenna": true,
|
||||
"channel": 1,
|
||||
"current_antenna_gain": 0,
|
||||
"ht": "20",
|
||||
"max_txpower": 22,
|
||||
"min_rssi_enabled": false,
|
||||
"min_txpower": 6,
|
||||
"name": "wifi0",
|
||||
"nss": 3,
|
||||
"radio": "ng",
|
||||
"radio_caps": 16420,
|
||||
"sens_level_enabled": false,
|
||||
"tx_power_mode": "low",
|
||||
"wlangroup_id": "5a32aa4ee4"
|
||||
},
|
||||
{
|
||||
"antenna_gain": 6,
|
||||
"builtin_ant_gain": 3,
|
||||
"builtin_antenna": true,
|
||||
"channel": "auto",
|
||||
"current_antenna_gain": 0,
|
||||
"hard_noise_floor_enabled": false,
|
||||
"has_dfs": true,
|
||||
"has_fccdfs": true,
|
||||
"ht": "40",
|
||||
"is_11ac": true,
|
||||
"max_txpower": 22,
|
||||
"min_rssi_enabled": false,
|
||||
"min_txpower": 6,
|
||||
"name": "wifi1",
|
||||
"nss": 3,
|
||||
"radio": "na",
|
||||
"radio_caps": 50479140,
|
||||
"sens_level_enabled": false,
|
||||
"tx_power_mode": "high",
|
||||
"wlangroup_id": "5a32aa4ee4"
|
||||
}
|
||||
],
|
||||
"radio_table_stats": [
|
||||
{
|
||||
"ast_be_xmit": 239,
|
||||
"ast_cst": null,
|
||||
"ast_txto": null,
|
||||
"channel": 1,
|
||||
"cu_self_rx": 20,
|
||||
"cu_self_tx": 0,
|
||||
"cu_total": 21,
|
||||
"extchannel": 0,
|
||||
"gain": 3,
|
||||
"guest-num_sta": 0,
|
||||
"name": "wifi0",
|
||||
"num_sta": 3,
|
||||
"radio": "ng",
|
||||
"satisfaction": 99,
|
||||
"state": "RUN",
|
||||
"tx_packets": 30,
|
||||
"tx_power": 6,
|
||||
"tx_retries": 16,
|
||||
"user-num_sta": 3
|
||||
},
|
||||
{
|
||||
"ast_be_xmit": 239,
|
||||
"ast_cst": null,
|
||||
"ast_txto": null,
|
||||
"channel": 44,
|
||||
"cu_self_rx": 1,
|
||||
"cu_self_tx": 1,
|
||||
"cu_total": 2,
|
||||
"extchannel": 1,
|
||||
"gain": 3,
|
||||
"guest-num_sta": 0,
|
||||
"name": "wifi1",
|
||||
"num_sta": 9,
|
||||
"radio": "na",
|
||||
"satisfaction": 97,
|
||||
"state": "RUN",
|
||||
"tx_packets": 2902,
|
||||
"tx_power": 17,
|
||||
"tx_retries": 121,
|
||||
"user-num_sta": 9
|
||||
}
|
||||
],
|
||||
"required_version": "3.4.1",
|
||||
"rx_bytes": 4049050176,
|
||||
"rx_bytes-d": 126600,
|
||||
"satisfaction": 97,
|
||||
"scan_radio_table": [],
|
||||
"scanning": false,
|
||||
"serial": "802AA8000102",
|
||||
"site_id": "5a32aa4ee4b0412345678910",
|
||||
"spectrum_scanning": false,
|
||||
"ssh_session_table": [],
|
||||
"start_connected_millis": 1587859252498,
|
||||
"start_disconnected_millis": 1587859249141,
|
||||
"stat": {
|
||||
"ap": {
|
||||
"ap": "80:2a:a8:00:01:02",
|
||||
"bytes": 202573081705.0,
|
||||
"datetime": "2020-04-26T00:00:00Z",
|
||||
"duration": 316470000.0,
|
||||
"guest-mac_filter_rejections": 0.0,
|
||||
"guest-rx_bytes": 0.0,
|
||||
"guest-rx_crypts": 0.0,
|
||||
"guest-rx_dropped": 0.0,
|
||||
"guest-rx_errors": 0.0,
|
||||
"guest-rx_frags": 0.0,
|
||||
"guest-rx_packets": 0.0,
|
||||
"guest-tx_bytes": 0.0,
|
||||
"guest-tx_dropped": 0.0,
|
||||
"guest-tx_errors": 0.0,
|
||||
"guest-tx_packets": 0.0,
|
||||
"guest-tx_retries": 0.0,
|
||||
"guest-wifi_tx_attempts": 0.0,
|
||||
"guest-wifi_tx_dropped": 0.0,
|
||||
"mac_filter_rejections": 0.0,
|
||||
"o": "ap",
|
||||
"oid": "80:2a:a8:00:01:02",
|
||||
"port_1-rx_broadcast": 172074.0,
|
||||
"port_1-rx_bytes": 216612809001.0,
|
||||
"port_1-rx_multicast": 403649.0,
|
||||
"port_1-rx_packets": 148071452.0,
|
||||
"port_1-tx_broadcast": 19948.0,
|
||||
"port_1-tx_bytes": 3988805922.0,
|
||||
"port_1-tx_multicast": 258376.0,
|
||||
"port_1-tx_packets": 26448260.0,
|
||||
"rx_bytes": 4049050176.0,
|
||||
"rx_crypts": 20074.0,
|
||||
"rx_dropped": 41540.0,
|
||||
"rx_errors": 20385.0,
|
||||
"rx_frags": 0.0,
|
||||
"rx_packets": 27062516.0,
|
||||
"site_id": "5a32aa4ee4b0412345678910",
|
||||
"time": 1587859200000,
|
||||
"tx_bytes": 198524031529.0,
|
||||
"tx_dropped": 0.0,
|
||||
"tx_errors": 233910.0,
|
||||
"tx_packets": 148794592.0,
|
||||
"tx_retries": 5259147.0,
|
||||
"user-mac_filter_rejections": 0.0,
|
||||
"user-rx_bytes": 4049050176.0,
|
||||
"user-rx_crypts": 20074.0,
|
||||
"user-rx_dropped": 41540.0,
|
||||
"user-rx_errors": 20385.0,
|
||||
"user-rx_frags": 0.0,
|
||||
"user-rx_packets": 27062516.0,
|
||||
"user-tx_bytes": 198524031529.0,
|
||||
"user-tx_dropped": 0.0,
|
||||
"user-tx_errors": 233910.0,
|
||||
"user-tx_packets": 148794592.0,
|
||||
"user-tx_retries": 5259147.0,
|
||||
"user-wifi0-ath0-3453453453453-rx_bytes": 543942635.0,
|
||||
"user-wifi0-ath0-3453453453453-rx_crypts": 8532.0,
|
||||
"user-wifi0-ath0-3453453453453-rx_dropped": 17899.0,
|
||||
"user-wifi0-ath0-3453453453453-rx_errors": 8843.0,
|
||||
"user-wifi0-ath0-3453453453453-rx_packets": 1286990.0,
|
||||
"user-wifi0-ath0-3453453453453-tx_bytes": 1631875402.0,
|
||||
"user-wifi0-ath0-3453453453453-tx_packets": 2143440.0,
|
||||
"user-wifi0-ath0-3453453453453-tx_retries": 815193.0,
|
||||
"user-wifi0-ath0-3453453453453-wifi_tx_attempts": 2251168.0,
|
||||
"user-wifi0-ath0-3453453453453-wifi_tx_dropped": 5689.0,
|
||||
"user-wifi0-mac_filter_rejections": 0.0,
|
||||
"user-wifi0-rx_bytes": 543942635.0,
|
||||
"user-wifi0-rx_crypts": 8532.0,
|
||||
"user-wifi0-rx_dropped": 17899.0,
|
||||
"user-wifi0-rx_errors": 8843.0,
|
||||
"user-wifi0-rx_frags": 0.0,
|
||||
"user-wifi0-rx_packets": 1286990.0,
|
||||
"user-wifi0-tx_bytes": 1631875402.0,
|
||||
"user-wifi0-tx_dropped": 0.0,
|
||||
"user-wifi0-tx_errors": 0.0,
|
||||
"user-wifi0-tx_packets": 2143440.0,
|
||||
"user-wifi0-tx_retries": 815193.0,
|
||||
"user-wifi0-wifi_tx_attempts": 2251168.0,
|
||||
"user-wifi0-wifi_tx_dropped": 5689.0,
|
||||
"user-wifi1-ath1-3453453453453-rx_bytes": 3505107541.0,
|
||||
"user-wifi1-ath1-3453453453453-rx_crypts": 11542.0,
|
||||
"user-wifi1-ath1-3453453453453-rx_dropped": 23641.0,
|
||||
"user-wifi1-ath1-3453453453453-rx_errors": 11542.0,
|
||||
"user-wifi1-ath1-3453453453453-rx_packets": 25775526.0,
|
||||
"user-wifi1-ath1-3453453453453-tx_bytes": 196892156127.0,
|
||||
"user-wifi1-ath1-3453453453453-tx_errors": 233910.0,
|
||||
"user-wifi1-ath1-3453453453453-tx_packets": 146651152.0,
|
||||
"user-wifi1-ath1-3453453453453-tx_retries": 4443954.0,
|
||||
"user-wifi1-ath1-3453453453453-wifi_tx_attempts": 79575052.0,
|
||||
"user-wifi1-ath1-3453453453453-wifi_tx_dropped": 512.0,
|
||||
"user-wifi1-mac_filter_rejections": 0.0,
|
||||
"user-wifi1-rx_bytes": 3505107541.0,
|
||||
"user-wifi1-rx_crypts": 11542.0,
|
||||
"user-wifi1-rx_dropped": 23641.0,
|
||||
"user-wifi1-rx_errors": 11542.0,
|
||||
"user-wifi1-rx_frags": 0.0,
|
||||
"user-wifi1-rx_packets": 25775526.0,
|
||||
"user-wifi1-tx_bytes": 196892156127.0,
|
||||
"user-wifi1-tx_dropped": 0.0,
|
||||
"user-wifi1-tx_errors": 233910.0,
|
||||
"user-wifi1-tx_packets": 146651152.0,
|
||||
"user-wifi1-tx_retries": 4443954.0,
|
||||
"user-wifi1-wifi_tx_attempts": 79575052.0,
|
||||
"user-wifi1-wifi_tx_dropped": 512.0,
|
||||
"user-wifi_tx_attempts": 81826220.0,
|
||||
"user-wifi_tx_dropped": 6201.0,
|
||||
"wifi0-mac_filter_rejections": 0.0,
|
||||
"wifi0-rx_bytes": 543942635.0,
|
||||
"wifi0-rx_crypts": 8532.0,
|
||||
"wifi0-rx_dropped": 17899.0,
|
||||
"wifi0-rx_errors": 8843.0,
|
||||
"wifi0-rx_frags": 0.0,
|
||||
"wifi0-rx_packets": 1286990.0,
|
||||
"wifi0-tx_bytes": 1631875402.0,
|
||||
"wifi0-tx_dropped": 0.0,
|
||||
"wifi0-tx_errors": 0.0,
|
||||
"wifi0-tx_packets": 2143440.0,
|
||||
"wifi0-tx_retries": 815193.0,
|
||||
"wifi0-wifi_tx_attempts": 2251168.0,
|
||||
"wifi0-wifi_tx_dropped": 5689.0,
|
||||
"wifi1-mac_filter_rejections": 0.0,
|
||||
"wifi1-rx_bytes": 3505107541.0,
|
||||
"wifi1-rx_crypts": 11542.0,
|
||||
"wifi1-rx_dropped": 23641.0,
|
||||
"wifi1-rx_errors": 11542.0,
|
||||
"wifi1-rx_frags": 0.0,
|
||||
"wifi1-rx_packets": 25775526.0,
|
||||
"wifi1-tx_bytes": 196892156127.0,
|
||||
"wifi1-tx_dropped": 0.0,
|
||||
"wifi1-tx_errors": 233910.0,
|
||||
"wifi1-tx_packets": 146651152.0,
|
||||
"wifi1-tx_retries": 4443954.0,
|
||||
"wifi1-wifi_tx_attempts": 79575052.0,
|
||||
"wifi1-wifi_tx_dropped": 512.0,
|
||||
"wifi_tx_attempts": 81826220.0,
|
||||
"wifi_tx_dropped": 6201.0
|
||||
}
|
||||
},
|
||||
"state": 1,
|
||||
"switch_caps": {
|
||||
"feature_caps": 32,
|
||||
"max_aggregate_sessions": 0,
|
||||
"max_mirror_sessions": 0
|
||||
},
|
||||
"sys_error_caps": 0,
|
||||
"sys_stats": {
|
||||
"loadavg_1": "0.15",
|
||||
"loadavg_15": "0.02",
|
||||
"loadavg_5": "0.08",
|
||||
"mem_buffer": 0,
|
||||
"mem_total": 128622592,
|
||||
"mem_used": 63606784
|
||||
},
|
||||
"syslog_key": "REDACTED",
|
||||
"system-stats": {
|
||||
"cpu": "3.1",
|
||||
"mem": "27.4",
|
||||
"uptime": "3971849"
|
||||
},
|
||||
"two_phase_adopt": false,
|
||||
"tx_bytes": 198524031529,
|
||||
"tx_bytes-d": 4148708,
|
||||
"type": "uap",
|
||||
"unsupported": false,
|
||||
"unsupported_reason": 0,
|
||||
"upgradable": true,
|
||||
"upgrade_state": 0,
|
||||
"upgrade_to_firmware": "4.0.80.10875",
|
||||
"uplink": {
|
||||
"full_duplex": true,
|
||||
"ip": "0.0.0.0",
|
||||
"mac": "80:2a:a8:00:01:02",
|
||||
"max_speed": 1000,
|
||||
"max_vlan": 96,
|
||||
"name": "eth0",
|
||||
"netmask": "0.0.0.0",
|
||||
"num_port": 2,
|
||||
"rx_bytes": 1755202154,
|
||||
"rx_bytes-r": 171857,
|
||||
"rx_dropped": 131000,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 0,
|
||||
"rx_packets": 1574229881,
|
||||
"speed": 1000,
|
||||
"tx_bytes": 537697796,
|
||||
"tx_bytes-r": 4916,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_packets": 333052303,
|
||||
"type": "wire",
|
||||
"up": true,
|
||||
"uplink_mac": "f0:9f:11:22:33:44",
|
||||
"uplink_remote_port": 6
|
||||
},
|
||||
"uplink_table": [],
|
||||
"uptime": 3971849,
|
||||
"user-num_sta": 12,
|
||||
"user-wlan-num_sta": 12,
|
||||
"vap_table": [
|
||||
{
|
||||
"anomalies_bar_chart": {
|
||||
"high_dns_latency": 0,
|
||||
"high_tcp_latency": 0,
|
||||
"high_tcp_packet_loss": 0,
|
||||
"high_wifi_latency": 0,
|
||||
"high_wifi_retries": 0,
|
||||
"low_phy_rate": 0,
|
||||
"poor_stream_eff": 0,
|
||||
"sleepy_client": 0,
|
||||
"sta_arp_timeout": 0,
|
||||
"sta_dns_timeout": 0,
|
||||
"sta_ip_timeout": 0,
|
||||
"weak_signal": 0
|
||||
},
|
||||
"anomalies_bar_chart_now": {
|
||||
"high_dns_latency": 0,
|
||||
"high_tcp_latency": 0,
|
||||
"high_tcp_packet_loss": 0,
|
||||
"high_wifi_latency": 0,
|
||||
"high_wifi_retries": 0,
|
||||
"low_phy_rate": 0,
|
||||
"poor_stream_eff": 0,
|
||||
"sleepy_client": 0,
|
||||
"sta_arp_timeout": 0,
|
||||
"sta_dns_timeout": 0,
|
||||
"sta_ip_timeout": 0,
|
||||
"weak_signal": 0
|
||||
},
|
||||
"ap_mac": "80:2a:a8:00:01:02",
|
||||
"avg_client_signal": -75,
|
||||
"bssid": "80:2a:11:22:33:44",
|
||||
"ccq": 340,
|
||||
"channel": 44,
|
||||
"dns_avg_latency": 6,
|
||||
"essid": "PhG",
|
||||
"extchannel": 1,
|
||||
"id": "3453453453453",
|
||||
"is_guest": false,
|
||||
"is_wep": false,
|
||||
"mac_filter_rejections": 0,
|
||||
"map_id": null,
|
||||
"name": "ath1",
|
||||
"num_satisfaction_sta": 9,
|
||||
"num_sta": 9,
|
||||
"radio": "na",
|
||||
"radio_name": "wifi1",
|
||||
"reasons_bar_chart": {
|
||||
"phy_rate": 0,
|
||||
"signal": 3,
|
||||
"sleepy_client": 0,
|
||||
"sta_arp_timeout": 0,
|
||||
"sta_dns_latency": 0,
|
||||
"sta_dns_timeout": 0,
|
||||
"sta_ip_timeout": 0,
|
||||
"stream_eff": 0,
|
||||
"tcp_latency": 2,
|
||||
"tcp_packet_loss": 0,
|
||||
"wifi_latency": 2,
|
||||
"wifi_retries": 2
|
||||
},
|
||||
"reasons_bar_chart_now": {
|
||||
"phy_rate": 0,
|
||||
"signal": 2,
|
||||
"sleepy_client": 0,
|
||||
"sta_arp_timeout": 0,
|
||||
"sta_dns_latency": 2,
|
||||
"sta_dns_timeout": 0,
|
||||
"sta_ip_timeout": 0,
|
||||
"stream_eff": 0,
|
||||
"tcp_latency": 1,
|
||||
"tcp_packet_loss": 0,
|
||||
"wifi_latency": 1,
|
||||
"wifi_retries": 1
|
||||
},
|
||||
"rx_bytes": 2772787976,
|
||||
"rx_crypts": 193706,
|
||||
"rx_dropped": 377847,
|
||||
"rx_errors": 193706,
|
||||
"rx_frags": 0,
|
||||
"rx_nwids": 244037,
|
||||
"rx_packets": 253573604,
|
||||
"rx_tcp_stats": {
|
||||
"goodbytes": 16307156809,
|
||||
"lat_avg": 26,
|
||||
"lat_max": 180,
|
||||
"lat_min": 10,
|
||||
"stalls": 0
|
||||
},
|
||||
"satisfaction": 97,
|
||||
"site_id": "5a32aa4ee4b0412345678910",
|
||||
"state": "RUN",
|
||||
"t": "vap",
|
||||
"tx_bytes": 2122358914,
|
||||
"tx_combined_retries": 3708330,
|
||||
"tx_data_mpdu_bytes": 181801507822,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 1710454,
|
||||
"tx_packets": 1282805591,
|
||||
"tx_power": 17,
|
||||
"tx_retries": 3708330,
|
||||
"tx_rts_retries": 0,
|
||||
"tx_success": 64435416,
|
||||
"tx_tcp_stats": {
|
||||
"goodbytes": 298206899,
|
||||
"lat_avg": 21,
|
||||
"lat_max": 110,
|
||||
"lat_min": 10,
|
||||
"stalls": 0
|
||||
},
|
||||
"tx_total": 64435427,
|
||||
"up": true,
|
||||
"usage": "user",
|
||||
"wifi_tx_attempts": 68143757,
|
||||
"wifi_tx_dropped": 11,
|
||||
"wifi_tx_latency_mov": {
|
||||
"avg": 968,
|
||||
"max": 3985,
|
||||
"min": 97,
|
||||
"total": 888421,
|
||||
"total_count": 917
|
||||
},
|
||||
"wlanconf_id": "3453453453453"
|
||||
},
|
||||
{
|
||||
"anomalies_bar_chart": {
|
||||
"high_dns_latency": 0,
|
||||
"high_tcp_latency": 0,
|
||||
"high_tcp_packet_loss": 0,
|
||||
"high_wifi_latency": 0,
|
||||
"high_wifi_retries": 0,
|
||||
"low_phy_rate": 0,
|
||||
"poor_stream_eff": 0,
|
||||
"sleepy_client": 0,
|
||||
"sta_arp_timeout": 0,
|
||||
"sta_dns_timeout": 0,
|
||||
"sta_ip_timeout": 0,
|
||||
"weak_signal": 0
|
||||
},
|
||||
"anomalies_bar_chart_now": {
|
||||
"high_dns_latency": 0,
|
||||
"high_tcp_latency": 0,
|
||||
"high_tcp_packet_loss": 0,
|
||||
"high_wifi_latency": 0,
|
||||
"high_wifi_retries": 0,
|
||||
"low_phy_rate": 0,
|
||||
"poor_stream_eff": 0,
|
||||
"sleepy_client": 0,
|
||||
"sta_arp_timeout": 0,
|
||||
"sta_dns_timeout": 0,
|
||||
"sta_ip_timeout": 0,
|
||||
"weak_signal": 0
|
||||
},
|
||||
"ap_mac": "80:2a:a8:00:01:02",
|
||||
"avg_client_signal": -70,
|
||||
"bssid": "80:2a:22:33:44:55:66",
|
||||
"ccq": 633,
|
||||
"channel": 1,
|
||||
"dns_avg_latency": 5,
|
||||
"essid": "PhG",
|
||||
"id": "3453453453453",
|
||||
"is_guest": false,
|
||||
"is_wep": false,
|
||||
"mac_filter_rejections": 0,
|
||||
"map_id": null,
|
||||
"name": "ath0",
|
||||
"num_satisfaction_sta": 3,
|
||||
"num_sta": 3,
|
||||
"radio": "ng",
|
||||
"radio_name": "wifi0",
|
||||
"reasons_bar_chart": {
|
||||
"phy_rate": 0,
|
||||
"signal": 0,
|
||||
"sleepy_client": 0,
|
||||
"sta_arp_timeout": 0,
|
||||
"sta_dns_latency": 1,
|
||||
"sta_dns_timeout": 0,
|
||||
"sta_ip_timeout": 0,
|
||||
"stream_eff": 0,
|
||||
"tcp_latency": 0,
|
||||
"tcp_packet_loss": 0,
|
||||
"wifi_latency": 2,
|
||||
"wifi_retries": 0
|
||||
},
|
||||
"reasons_bar_chart_now": {
|
||||
"phy_rate": 0,
|
||||
"signal": 0,
|
||||
"sleepy_client": 0,
|
||||
"sta_arp_timeout": 0,
|
||||
"sta_dns_latency": 1,
|
||||
"sta_dns_timeout": 0,
|
||||
"sta_ip_timeout": 0,
|
||||
"stream_eff": 0,
|
||||
"tcp_latency": 0,
|
||||
"tcp_packet_loss": 0,
|
||||
"wifi_latency": 2,
|
||||
"wifi_retries": 0
|
||||
},
|
||||
"rx_bytes": 1680489730,
|
||||
"rx_crypts": 111491,
|
||||
"rx_dropped": 140008,
|
||||
"rx_errors": 112587,
|
||||
"rx_frags": 0,
|
||||
"rx_nwids": 3448793,
|
||||
"rx_packets": 23062297,
|
||||
"rx_tcp_stats": {
|
||||
"goodbytes": 22571928,
|
||||
"lat_avg": 3,
|
||||
"lat_max": 10,
|
||||
"lat_min": 10,
|
||||
"stalls": 0
|
||||
},
|
||||
"satisfaction": 99,
|
||||
"site_id": "5a32aa4ee4b0412345678910",
|
||||
"state": "RUN",
|
||||
"t": "vap",
|
||||
"tx_bytes": 2405174619,
|
||||
"tx_combined_retries": 198754,
|
||||
"tx_data_mpdu_bytes": 65829188,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_packets": 59362177,
|
||||
"tx_power": 6,
|
||||
"tx_retries": 144922,
|
||||
"tx_rts_retries": 53832,
|
||||
"tx_success": 411226,
|
||||
"tx_tcp_stats": {
|
||||
"goodbytes": 51240971,
|
||||
"lat_avg": 3,
|
||||
"lat_max": 10,
|
||||
"lat_min": 10,
|
||||
"stalls": 0
|
||||
},
|
||||
"tx_total": 411704,
|
||||
"up": true,
|
||||
"usage": "user",
|
||||
"wifi_tx_attempts": 556148,
|
||||
"wifi_tx_dropped": 478,
|
||||
"wifi_tx_latency_mov": {
|
||||
"avg": 516,
|
||||
"max": 12117,
|
||||
"min": 0,
|
||||
"total": 20141,
|
||||
"total_count": 39
|
||||
},
|
||||
"wlanconf_id": "3453453453453"
|
||||
}
|
||||
],
|
||||
"version": "4.0.69.10871",
|
||||
"vwireEnabled": false,
|
||||
"vwire_table": [],
|
||||
"vwire_vap_table": [],
|
||||
"wifi_caps": 573429,
|
||||
"wlan_overrides": [
|
||||
{
|
||||
"name": "My5GHzSSID1",
|
||||
"radio": "na",
|
||||
"radio_name": "wifi1",
|
||||
"wlan_id": "012345678910111213141516"
|
||||
}
|
||||
],
|
||||
"wlangroup_id_na": "5a32aa4ee4123",
|
||||
"wlangroup_id_ng": "5a32aa4ee4123",
|
||||
"x_aes_gcm": "REDACTED",
|
||||
"x_authkey": "REDACTED",
|
||||
"x_fingerprint": "REDACTED",
|
||||
"x_has_ssh_hostkey": "REDACTED",
|
||||
"x_inform_authkey": "REDACTED",
|
||||
"x_ssh_hostkey_fingerprint": "REDACTED",
|
||||
"x_vwirekey": "REDACTED"
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
{
|
||||
"_id": "5a4c0cc1e4b0f3665471969a",
|
||||
"_uptime": 3971869,
|
||||
"adoptable_when_upgraded": false,
|
||||
"adopted": true,
|
||||
"board_rev": 16,
|
||||
"bytes": 1204107284393,
|
||||
"cfgversion": "464ab1e08b5bd1a2",
|
||||
"config_network": {
|
||||
"ip": "192.168.0.1",
|
||||
"type": "dhcp"
|
||||
},
|
||||
"connect_request_ip": "192.168.0.1",
|
||||
"connect_request_port": "48714",
|
||||
"considered_lost_at": 1588175842,
|
||||
"device_id": "235678987654345678",
|
||||
"ethernet_overrides": [
|
||||
{
|
||||
"ifname": "eth1",
|
||||
"networkgroup": "LAN"
|
||||
},
|
||||
{
|
||||
"ifname": "eth0",
|
||||
"networkgroup": "WAN"
|
||||
}
|
||||
],
|
||||
"ethernet_table": [
|
||||
{
|
||||
"mac": "78:8a:20:33:44:55",
|
||||
"name": "eth0",
|
||||
"num_port": 1
|
||||
},
|
||||
{
|
||||
"mac": "192.168.0.1",
|
||||
"name": "eth1",
|
||||
"num_port": 1
|
||||
},
|
||||
{
|
||||
"mac": "78:8a:20:33:44:56",
|
||||
"name": "eth2",
|
||||
"num_port": 1
|
||||
}
|
||||
],
|
||||
"fw_caps": 184323,
|
||||
"guest-num_sta": 0,
|
||||
"guest_token": "REDACTED",
|
||||
"hw_caps": 0,
|
||||
"inform_ip": "192.168.0.5",
|
||||
"inform_url": "http://192.168.0.7:8080/inform",
|
||||
"ip": "1.2.3.4",
|
||||
"known_cfgversion": "23434545676787654",
|
||||
"last_seen": 1588175740,
|
||||
"last_wan_ip": "1.2.3.4",
|
||||
"last_wan_status": {
|
||||
"WAN": "online",
|
||||
"WAN2": "online"
|
||||
},
|
||||
"led_override": "on",
|
||||
"license_state": "registered",
|
||||
"locating": false,
|
||||
"mac": "78:8a:20:33:44:55",
|
||||
"model": "UGW3",
|
||||
"name": "USG",
|
||||
"network_table": [
|
||||
{
|
||||
"_id": "5a32aa4ee4b3456542345678765",
|
||||
"attr_hidden_id": "LAN",
|
||||
"attr_no_delete": true,
|
||||
"dhcp_relay_enabled": false,
|
||||
"dhcpd_dns_1": "192.168.0.7",
|
||||
"dhcpd_dns_enabled": false,
|
||||
"dhcpd_enabled": true,
|
||||
"dhcpd_gateway_enabled": false,
|
||||
"dhcpd_leasetime": 86400,
|
||||
"dhcpd_start": "192.168.0.11",
|
||||
"dhcpd_stop": "192.168.0.254",
|
||||
"dhcpd_time_offset_enabled": false,
|
||||
"dhcpd_unifi_controller": "192.168.0.7",
|
||||
"domain_name": "localdomain",
|
||||
"enabled": true,
|
||||
"ip": "192.168.0.1",
|
||||
"ip_subnet": "192.168.0.1/24",
|
||||
"is_guest": false,
|
||||
"is_nat": true,
|
||||
"lte_lan_enabled": true,
|
||||
"mac": "192.168.0.1",
|
||||
"name": "LAN",
|
||||
"networkgroup": "LAN",
|
||||
"num_sta": 16,
|
||||
"purpose": "corporate",
|
||||
"rx_bytes": 1103117408747,
|
||||
"rx_packets": 805953276,
|
||||
"site_id": "5a32aa4ee4b0412345678910",
|
||||
"tx_bytes": 96022594996,
|
||||
"tx_packets": 341451260,
|
||||
"up": "true",
|
||||
"vlan_enabled": false
|
||||
}
|
||||
],
|
||||
"next_heartbeat_at": 1588175774,
|
||||
"next_interval": 24,
|
||||
"num_desktop": 4,
|
||||
"num_handheld": 1,
|
||||
"num_mobile": 0,
|
||||
"num_sta": 20,
|
||||
"outdoor_mode_override": "default",
|
||||
"port_table": [
|
||||
{
|
||||
"dns": [
|
||||
"127.0.0.1"
|
||||
],
|
||||
"enable": true,
|
||||
"full_duplex": true,
|
||||
"gateway": "2.3.4.5",
|
||||
"ifname": "eth0",
|
||||
"ip": "1.2.3.4",
|
||||
"mac": "78:8a:20:33:44:55",
|
||||
"name": "wan",
|
||||
"netmask": "255.255.254.0",
|
||||
"rx_bytes": 1107294012155,
|
||||
"rx_dropped": 3929,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 0,
|
||||
"rx_packets": 807555430,
|
||||
"speed": 1000,
|
||||
"tx_bytes": 96813272238,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_packets": 344559427,
|
||||
"up": true
|
||||
},
|
||||
{
|
||||
"enable": true,
|
||||
"full_duplex": true,
|
||||
"ifname": "eth1",
|
||||
"ip": "192.168.0.1",
|
||||
"mac": "192.168.0.1",
|
||||
"name": "lan",
|
||||
"netmask": "255.255.255.0",
|
||||
"rx_bytes": 98681321728,
|
||||
"rx_dropped": 1379,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 247602,
|
||||
"rx_packets": 349214866,
|
||||
"speed": 1000,
|
||||
"tx_bytes": 1105756381870,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_packets": 808015520,
|
||||
"up": true
|
||||
},
|
||||
{
|
||||
"enable": false,
|
||||
"full_duplex": false,
|
||||
"ifname": "eth2",
|
||||
"ip": "0.0.0.0",
|
||||
"mac": "78:8a:20:33:44:56",
|
||||
"name": "lan2",
|
||||
"netmask": "0.0.0.0",
|
||||
"rx_bytes": 0,
|
||||
"rx_dropped": 0,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 0,
|
||||
"rx_packets": 0,
|
||||
"speed": 0,
|
||||
"tx_bytes": 0,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_packets": 0,
|
||||
"up": false
|
||||
}
|
||||
],
|
||||
"required_version": "4.0.0",
|
||||
"rx_bytes": 96813272238,
|
||||
"serial": "788A20334455",
|
||||
"site_id": "5a32aa4ee4b0412345678910",
|
||||
"speedtest-status": {
|
||||
"latency": 0,
|
||||
"rundate": 0,
|
||||
"runtime": 0,
|
||||
"status_download": 0,
|
||||
"status_ping": 0,
|
||||
"status_summary": 0,
|
||||
"status_upload": 0,
|
||||
"xput_download": 0.0,
|
||||
"xput_upload": 0.0
|
||||
},
|
||||
"speedtest-status-saved": true,
|
||||
"start_connected_millis": 1587859256101,
|
||||
"start_disconnected_millis": 1587859249149,
|
||||
"stat": {
|
||||
"gw": {
|
||||
"datetime": "2020-04-26T00:00:00Z",
|
||||
"duration": 316484000.0,
|
||||
"gw": "78:8a:20:33:44:55",
|
||||
"lan-rx_bytes": 5964025490.0,
|
||||
"lan-rx_dropped": 10.0,
|
||||
"lan-rx_packets": 24227687.0,
|
||||
"lan-tx_bytes": 76685302301.0,
|
||||
"lan-tx_packets": 56428312.0,
|
||||
"o": "gw",
|
||||
"oid": "78:8a:20:33:44:55",
|
||||
"site_id": "5a32aa4ee4b0412345678910",
|
||||
"time": 1587859200000,
|
||||
"wan-rx_bytes": 76769209870.0,
|
||||
"wan-rx_dropped": 231.0,
|
||||
"wan-rx_packets": 56473855.0,
|
||||
"wan-tx_bytes": 5836684857.0,
|
||||
"wan-tx_packets": 23887040.0
|
||||
}
|
||||
},
|
||||
"state": 1,
|
||||
"storage": [
|
||||
{
|
||||
"mount_point": "/persistent",
|
||||
"name": "Backup",
|
||||
"size": 2040373248,
|
||||
"type": "eMMC",
|
||||
"used": 148353024
|
||||
},
|
||||
{
|
||||
"mount_point": "/tmp",
|
||||
"name": "Temporary",
|
||||
"size": 1073741824,
|
||||
"type": "other",
|
||||
"used": 90112
|
||||
}
|
||||
],
|
||||
"sys_stats": {
|
||||
"loadavg_1": "0.03",
|
||||
"loadavg_15": "0.08",
|
||||
"loadavg_5": "0.07",
|
||||
"mem_buffer": 57561088,
|
||||
"mem_total": 507412480,
|
||||
"mem_used": 293453824
|
||||
},
|
||||
"syslog_key": "REDACTED",
|
||||
"system-stats": {
|
||||
"cpu": "0",
|
||||
"mem": "25",
|
||||
"uptime": "3971505"
|
||||
},
|
||||
"temperatures": [
|
||||
{
|
||||
"name": "CPU",
|
||||
"type": "cpu",
|
||||
"value": 66.0
|
||||
},
|
||||
{
|
||||
"name": "Local",
|
||||
"type": "board",
|
||||
"value": 48.75
|
||||
},
|
||||
{
|
||||
"name": "PHY",
|
||||
"type": "board",
|
||||
"value": 50.25
|
||||
}
|
||||
],
|
||||
"two_phase_adopt": false,
|
||||
"tx_bytes": 1107294012155,
|
||||
"type": "ugw",
|
||||
"unsupported": false,
|
||||
"unsupported_reason": 0,
|
||||
"upgradable": true,
|
||||
"upgrade_state": 0,
|
||||
"upgrade_to_firmware": "4.4.50.5272448",
|
||||
"uplink": {
|
||||
"bytes-r": 242330,
|
||||
"drops": 4,
|
||||
"enable": true,
|
||||
"full_duplex": true,
|
||||
"gateways": [
|
||||
"2.3.4.5"
|
||||
],
|
||||
"ip": "1.2.3.4",
|
||||
"latency": 1,
|
||||
"mac": "78:8a:20:33:44:55",
|
||||
"max_speed": 1000,
|
||||
"name": "eth0",
|
||||
"nameservers": [
|
||||
"127.0.0.1"
|
||||
],
|
||||
"netmask": "255.255.254.0",
|
||||
"num_port": 1,
|
||||
"rx_bytes": 1107294012155,
|
||||
"rx_bytes-r": 239494,
|
||||
"rx_dropped": 3929,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 0,
|
||||
"rx_packets": 807555430,
|
||||
"speed": 1000,
|
||||
"speedtest_lastrun": 0,
|
||||
"speedtest_ping": 0,
|
||||
"speedtest_status": "Idle",
|
||||
"tx_bytes": 96813272238,
|
||||
"tx_bytes-r": 2836,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_packets": 344559427,
|
||||
"type": "wire",
|
||||
"up": true,
|
||||
"uptime": 855760,
|
||||
"xput_down": 0.0,
|
||||
"xput_up": 0.0
|
||||
},
|
||||
"uptime": 3971869,
|
||||
"uptime_stats": {
|
||||
"WAN": {
|
||||
"monitors": [
|
||||
{
|
||||
"availability": 100.0,
|
||||
"latency_average": 5,
|
||||
"target": "www.microsoft.com",
|
||||
"type": "icmp"
|
||||
},
|
||||
{
|
||||
"availability": 100.0,
|
||||
"latency_average": 7,
|
||||
"target": "google.com",
|
||||
"type": "icmp"
|
||||
},
|
||||
{
|
||||
"availability": 100.0,
|
||||
"latency_average": 5,
|
||||
"target": "1.1.1.1",
|
||||
"type": "icmp"
|
||||
}
|
||||
]
|
||||
},
|
||||
"WAN2": {
|
||||
"monitors": [
|
||||
{
|
||||
"availability": 0.0,
|
||||
"target": "www.microsoft.com",
|
||||
"type": "icmp"
|
||||
},
|
||||
{
|
||||
"availability": 0.0,
|
||||
"target": "google.com",
|
||||
"type": "icmp"
|
||||
},
|
||||
{
|
||||
"availability": 0.0,
|
||||
"target": "1.1.1.1",
|
||||
"type": "icmp"
|
||||
}
|
||||
]
|
||||
},
|
||||
"WAN3": {
|
||||
"monitors": [
|
||||
{
|
||||
"availability": 100.0,
|
||||
"latency_average": 41,
|
||||
"target": "www.microsoft.com",
|
||||
"type": "icmp"
|
||||
},
|
||||
{
|
||||
"availability": 100.0,
|
||||
"latency_average": 32,
|
||||
"target": "google.com",
|
||||
"type": "icmp"
|
||||
},
|
||||
{
|
||||
"availability": 100.0,
|
||||
"latency_average": 16,
|
||||
"target": "1.1.1.1",
|
||||
"type": "icmp"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"user-num_sta": 20,
|
||||
"usg_caps": 786431,
|
||||
"version": "4.4.44.5213844",
|
||||
"wan1": {
|
||||
"bytes-r": 242330,
|
||||
"dns": [
|
||||
"127.0.0.1"
|
||||
],
|
||||
"enable": true,
|
||||
"full_duplex": true,
|
||||
"gateway": "2.3.4.5",
|
||||
"ifname": "eth0",
|
||||
"ip": "1.2.3.4",
|
||||
"mac": "78:8a:20:33:44:55",
|
||||
"max_speed": 1000,
|
||||
"name": "wan",
|
||||
"netmask": "255.255.254.0",
|
||||
"rx_bytes": 1107294012155,
|
||||
"rx_bytes-r": 239494,
|
||||
"rx_dropped": 3929,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 0,
|
||||
"rx_packets": 807555430,
|
||||
"speed": 1000,
|
||||
"tx_bytes": 96813272238,
|
||||
"tx_bytes-r": 2836,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_packets": 344559427,
|
||||
"type": "wire",
|
||||
"up": true
|
||||
},
|
||||
"wan2": {
|
||||
"bytes-r": 1024,
|
||||
"dns": [
|
||||
"8.8.8.8"
|
||||
],
|
||||
"enable": true,
|
||||
"full_duplex": true,
|
||||
"gateway": "10.0.0.1",
|
||||
"ifname": "eth1",
|
||||
"ip": "10.0.0.2",
|
||||
"mac": "78:8a:20:33:44:56",
|
||||
"max_speed": 1000,
|
||||
"name": "wan2",
|
||||
"netmask": "255.255.255.0",
|
||||
"rx_bytes": 500000000,
|
||||
"rx_bytes-r": 512,
|
||||
"rx_dropped": 0,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 0,
|
||||
"rx_packets": 1000000,
|
||||
"speed": 1000,
|
||||
"tx_bytes": 200000000,
|
||||
"tx_bytes-r": 512,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_packets": 500000,
|
||||
"type": "wire",
|
||||
"up": true
|
||||
},
|
||||
"x_aes_gcm": "REDACTED",
|
||||
"x_authkey": "REDACTED",
|
||||
"x_has_ssh_hostkey": "REDACTED",
|
||||
"x_inform_authkey": "REDACTED",
|
||||
"x_ssh_hostkey_fingerprint": "REDACTED"
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,587 @@
|
||||
{
|
||||
"_id": "5a7cc21ae4b068sbddb234565324134",
|
||||
"_uptime": 3971894,
|
||||
"adoptable_when_upgraded": false,
|
||||
"adopted": true,
|
||||
"architecture": "armv7l",
|
||||
"board_rev": 10,
|
||||
"bytes": 1209354602451,
|
||||
"cfgversion": "123131b3x1d2x454xx",
|
||||
"config_network": {
|
||||
"ip": "192.168.0.8",
|
||||
"type": "dhcp"
|
||||
},
|
||||
"connect_request_ip": "192.168.0.8",
|
||||
"connect_request_port": "49349",
|
||||
"considered_lost_at": 1588175834,
|
||||
"device_id": "235678987654345678",
|
||||
"dhcp_server_table": [],
|
||||
"dot1x_portctrl_enabled": false,
|
||||
"downlink_table": [
|
||||
{
|
||||
"full_duplex": true,
|
||||
"mac": "fc:ec:da:11:22:33",
|
||||
"port_idx": 5,
|
||||
"speed": 1000
|
||||
},
|
||||
{
|
||||
"full_duplex": true,
|
||||
"mac": "80:2a:a8:00:01:02",
|
||||
"port_idx": 6,
|
||||
"speed": 1000
|
||||
}
|
||||
],
|
||||
"ethernet_table": [
|
||||
{
|
||||
"mac": "f0:9f:11:22:33:44",
|
||||
"name": "eth0",
|
||||
"num_port": 8
|
||||
},
|
||||
{
|
||||
"mac": "f0:9f:11:22:33:4a",
|
||||
"name": "srv0"
|
||||
}
|
||||
],
|
||||
"flowctrl_enabled": false,
|
||||
"fw_caps": 21683749,
|
||||
"gateway_mac": "192.168.0.1",
|
||||
"guest-num_sta": 0,
|
||||
"has_fan": false,
|
||||
"has_temperature": false,
|
||||
"hash_id": "REDACTED",
|
||||
"hw_caps": 0,
|
||||
"inform_ip": "192.168.0.5",
|
||||
"inform_url": "http://192.168.0.7:8080/inform",
|
||||
"internet": true,
|
||||
"ip": "192.168.0.8",
|
||||
"jumboframe_enabled": false,
|
||||
"kernel_version": "3.6.5",
|
||||
"known_cfgversion": "23434545676787654",
|
||||
"last_seen": 1588175735,
|
||||
"last_uplink": {
|
||||
"uplink_mac": "78:8a:20:33:44:55"
|
||||
},
|
||||
"led_override": "on",
|
||||
"license_state": "registered",
|
||||
"locating": false,
|
||||
"mac": "f0:9f:11:22:33:44",
|
||||
"manufacturer_id": 4,
|
||||
"model": "US8",
|
||||
"name": "Switch 8",
|
||||
"next_heartbeat_at": 1588175768,
|
||||
"next_interval": 23,
|
||||
"num_sta": 4,
|
||||
"outdoor_mode_override": "default",
|
||||
"overheating": false,
|
||||
"port_overrides": [
|
||||
{
|
||||
"poe_mode": "auto",
|
||||
"port_idx": 5,
|
||||
"portconf_id": "5a32aa4ee4babd4452422ddd22222"
|
||||
}
|
||||
],
|
||||
"port_table": [
|
||||
{
|
||||
"aggregated_by": false,
|
||||
"autoneg": true,
|
||||
"bytes-r": 0,
|
||||
"dot1x_mode": "unknown",
|
||||
"dot1x_status": "disabled",
|
||||
"enable": true,
|
||||
"flowctrl_rx": false,
|
||||
"flowctrl_tx": false,
|
||||
"full_duplex": false,
|
||||
"is_uplink": false,
|
||||
"jumbo": false,
|
||||
"lldp_table": [],
|
||||
"masked": false,
|
||||
"media": "GE",
|
||||
"name": "Port 1",
|
||||
"op_mode": "switch",
|
||||
"poe_caps": 0,
|
||||
"port_idx": 1,
|
||||
"port_poe": false,
|
||||
"portconf_id": "5a32aa4ee4babd4452422ddd22222",
|
||||
"rx_broadcast": 0,
|
||||
"rx_bytes": 0,
|
||||
"rx_bytes-r": 0,
|
||||
"rx_dropped": 0,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 0,
|
||||
"rx_packets": 0,
|
||||
"satisfaction": 100,
|
||||
"speed": 0,
|
||||
"speed_caps": 1048623,
|
||||
"stp_pathcost": 0,
|
||||
"stp_state": "disabled",
|
||||
"tx_broadcast": 0,
|
||||
"tx_bytes": 0,
|
||||
"tx_bytes-r": 0,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_multicast": 0,
|
||||
"tx_packets": 0,
|
||||
"up": false
|
||||
},
|
||||
{
|
||||
"aggregated_by": false,
|
||||
"autoneg": true,
|
||||
"bytes-r": 244434,
|
||||
"dot1x_mode": "unknown",
|
||||
"dot1x_status": "disabled",
|
||||
"enable": true,
|
||||
"flowctrl_rx": false,
|
||||
"flowctrl_tx": false,
|
||||
"full_duplex": true,
|
||||
"is_uplink": true,
|
||||
"jumbo": false,
|
||||
"lldp_table": [
|
||||
{
|
||||
"lldp_chassis_id": "78:8A:20:44:33:22:11",
|
||||
"lldp_port_id": "eth1",
|
||||
"lldp_system_name": "USG"
|
||||
}
|
||||
],
|
||||
"masked": false,
|
||||
"media": "GE",
|
||||
"name": "Port 2",
|
||||
"op_mode": "switch",
|
||||
"poe_caps": 0,
|
||||
"port_idx": 2,
|
||||
"port_poe": false,
|
||||
"portconf_id": "5a32aa4ee4babd4452422ddd22222",
|
||||
"rx_broadcast": 44064,
|
||||
"rx_bytes": 1109019728759,
|
||||
"rx_bytes-r": 240953,
|
||||
"rx_dropped": 0,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 138783,
|
||||
"rx_packets": 808013990,
|
||||
"satisfaction": 100,
|
||||
"speed": 1000,
|
||||
"speed_caps": 1048623,
|
||||
"stp_pathcost": 20000,
|
||||
"stp_state": "forwarding",
|
||||
"tx_broadcast": 2498252,
|
||||
"tx_bytes": 100334873692,
|
||||
"tx_bytes-r": 3480,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_multicast": 7847706,
|
||||
"tx_packets": 356816368,
|
||||
"up": true
|
||||
},
|
||||
{
|
||||
"aggregated_by": false,
|
||||
"autoneg": true,
|
||||
"bytes-r": 0,
|
||||
"dot1x_mode": "unknown",
|
||||
"dot1x_status": "disabled",
|
||||
"enable": true,
|
||||
"flowctrl_rx": false,
|
||||
"flowctrl_tx": false,
|
||||
"full_duplex": false,
|
||||
"is_uplink": false,
|
||||
"jumbo": false,
|
||||
"lldp_table": [],
|
||||
"masked": false,
|
||||
"media": "GE",
|
||||
"name": "Port 3",
|
||||
"op_mode": "switch",
|
||||
"poe_caps": 0,
|
||||
"port_idx": 3,
|
||||
"port_poe": false,
|
||||
"portconf_id": "5a32aa4ee4babd4452422ddd22222",
|
||||
"rx_broadcast": 0,
|
||||
"rx_bytes": 0,
|
||||
"rx_bytes-r": 0,
|
||||
"rx_dropped": 0,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 0,
|
||||
"rx_packets": 0,
|
||||
"satisfaction": 100,
|
||||
"speed": 0,
|
||||
"speed_caps": 1048623,
|
||||
"stp_pathcost": 0,
|
||||
"stp_state": "disabled",
|
||||
"tx_broadcast": 0,
|
||||
"tx_bytes": 0,
|
||||
"tx_bytes-r": 0,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_multicast": 0,
|
||||
"tx_packets": 0,
|
||||
"up": false
|
||||
},
|
||||
{
|
||||
"aggregated_by": false,
|
||||
"autoneg": true,
|
||||
"bytes-r": 388,
|
||||
"dot1x_mode": "unknown",
|
||||
"dot1x_status": "disabled",
|
||||
"enable": true,
|
||||
"flowctrl_rx": false,
|
||||
"flowctrl_tx": false,
|
||||
"full_duplex": true,
|
||||
"is_uplink": false,
|
||||
"jumbo": false,
|
||||
"lldp_table": [],
|
||||
"masked": false,
|
||||
"media": "GE",
|
||||
"name": "Port 4",
|
||||
"op_mode": "switch",
|
||||
"poe_caps": 0,
|
||||
"port_idx": 4,
|
||||
"port_poe": false,
|
||||
"portconf_id": "5a32aa4ee4babd4452422ddd22222",
|
||||
"rx_broadcast": 17,
|
||||
"rx_bytes": 9242748,
|
||||
"rx_bytes-r": 5,
|
||||
"rx_dropped": 0,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 0,
|
||||
"rx_packets": 136169,
|
||||
"satisfaction": 100,
|
||||
"speed": 100,
|
||||
"speed_caps": 1048623,
|
||||
"stp_pathcost": 200000,
|
||||
"stp_state": "forwarding",
|
||||
"tx_broadcast": 2542342,
|
||||
"tx_bytes": 1919704579,
|
||||
"tx_bytes-r": 383,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_multicast": 7854446,
|
||||
"tx_packets": 10540945,
|
||||
"up": true
|
||||
},
|
||||
{
|
||||
"aggregated_by": false,
|
||||
"autoneg": true,
|
||||
"bytes-r": 1781,
|
||||
"dot1x_mode": "unknown",
|
||||
"dot1x_status": "disabled",
|
||||
"enable": true,
|
||||
"flowctrl_rx": false,
|
||||
"flowctrl_tx": false,
|
||||
"full_duplex": true,
|
||||
"is_uplink": false,
|
||||
"jumbo": false,
|
||||
"lldp_table": [
|
||||
{
|
||||
"lldp_chassis_id": "FC:EC:DA:33:22:44",
|
||||
"lldp_port_id": "0/1",
|
||||
"lldp_system_name": "Switch16"
|
||||
}
|
||||
],
|
||||
"masked": false,
|
||||
"media": "GE",
|
||||
"name": "Port 5",
|
||||
"op_mode": "switch",
|
||||
"poe_caps": 0,
|
||||
"poe_mode": "auto",
|
||||
"port_idx": 5,
|
||||
"port_poe": false,
|
||||
"portconf_id": "5a32aa4ee4babd4452422ddd22222",
|
||||
"rx_broadcast": 129026,
|
||||
"rx_bytes": 435751727043,
|
||||
"rx_bytes-r": 867,
|
||||
"rx_dropped": 0,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 411610,
|
||||
"rx_packets": 457317083,
|
||||
"satisfaction": 100,
|
||||
"speed": 1000,
|
||||
"speed_caps": 1048623,
|
||||
"stp_pathcost": 20000,
|
||||
"stp_state": "forwarding",
|
||||
"tx_broadcast": 2413331,
|
||||
"tx_bytes": 429589071593,
|
||||
"tx_bytes-r": 914,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_multicast": 7573771,
|
||||
"tx_packets": 370316574,
|
||||
"up": true
|
||||
},
|
||||
{
|
||||
"aggregated_by": false,
|
||||
"autoneg": true,
|
||||
"bytes-r": 244345,
|
||||
"dot1x_mode": "unknown",
|
||||
"dot1x_status": "disabled",
|
||||
"enable": true,
|
||||
"flowctrl_rx": false,
|
||||
"flowctrl_tx": false,
|
||||
"full_duplex": true,
|
||||
"is_uplink": false,
|
||||
"jumbo": false,
|
||||
"lldp_table": [
|
||||
{
|
||||
"lldp_chassis_id": "80:2A:A8:55:44:33",
|
||||
"lldp_port_id": "80:2A:A8:55:44:33",
|
||||
"lldp_system_name": "UAPACPRO"
|
||||
}
|
||||
],
|
||||
"masked": false,
|
||||
"media": "GE",
|
||||
"name": "Port 6",
|
||||
"op_mode": "switch",
|
||||
"poe_caps": 0,
|
||||
"port_idx": 6,
|
||||
"port_poe": false,
|
||||
"portconf_id": "5a32aa4ee4babd4452422ddd22222",
|
||||
"rx_broadcast": 218412,
|
||||
"rx_bytes": 53516789416,
|
||||
"rx_bytes-r": 4113,
|
||||
"rx_dropped": 0,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 2935589,
|
||||
"rx_packets": 333052376,
|
||||
"satisfaction": 90,
|
||||
"speed": 1000,
|
||||
"speed_caps": 1048623,
|
||||
"stp_pathcost": 20000,
|
||||
"stp_state": "forwarding",
|
||||
"tx_broadcast": 2323945,
|
||||
"tx_bytes": 2275838496776,
|
||||
"tx_bytes-r": 240232,
|
||||
"tx_dropped": 2665,
|
||||
"tx_errors": 0,
|
||||
"tx_multicast": 5051186,
|
||||
"tx_packets": 1574259392,
|
||||
"up": true
|
||||
},
|
||||
{
|
||||
"aggregated_by": false,
|
||||
"autoneg": true,
|
||||
"bytes-r": 3508,
|
||||
"dot1x_mode": "unknown",
|
||||
"dot1x_status": "disabled",
|
||||
"enable": true,
|
||||
"flowctrl_rx": false,
|
||||
"flowctrl_tx": false,
|
||||
"full_duplex": true,
|
||||
"is_uplink": false,
|
||||
"jumbo": false,
|
||||
"lldp_table": [],
|
||||
"masked": false,
|
||||
"media": "GE",
|
||||
"name": "Port 7",
|
||||
"op_mode": "switch",
|
||||
"poe_caps": 0,
|
||||
"port_idx": 7,
|
||||
"port_poe": false,
|
||||
"portconf_id": "5a32aa4ee4babd4452422ddd22222",
|
||||
"rx_broadcast": 2031756,
|
||||
"rx_bytes": 1602876591571,
|
||||
"rx_bytes-r": 613,
|
||||
"rx_dropped": 0,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 2646968,
|
||||
"rx_packets": 1117936736,
|
||||
"satisfaction": 100,
|
||||
"speed": 1000,
|
||||
"speed_caps": 1048623,
|
||||
"stp_pathcost": 20000,
|
||||
"stp_state": "forwarding",
|
||||
"tx_broadcast": 510499,
|
||||
"tx_bytes": 400026198993,
|
||||
"tx_bytes-r": 2895,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_multicast": 5207435,
|
||||
"tx_packets": 440118452,
|
||||
"up": true
|
||||
},
|
||||
{
|
||||
"aggregated_by": false,
|
||||
"autoneg": true,
|
||||
"bytes-r": 0,
|
||||
"dot1x_mode": "unknown",
|
||||
"dot1x_status": "disabled",
|
||||
"enable": true,
|
||||
"flowctrl_rx": false,
|
||||
"flowctrl_tx": false,
|
||||
"full_duplex": false,
|
||||
"is_uplink": false,
|
||||
"jumbo": false,
|
||||
"lldp_table": [],
|
||||
"masked": false,
|
||||
"media": "GE",
|
||||
"name": "Port 8",
|
||||
"op_mode": "switch",
|
||||
"poe_caps": 8,
|
||||
"poe_enable": false,
|
||||
"poe_mode": "off",
|
||||
"poe_voltage": "48.00",
|
||||
"port_idx": 8,
|
||||
"port_poe": true,
|
||||
"portconf_id": "5a32aa4ee4babd4452422ddd22222",
|
||||
"rx_broadcast": 0,
|
||||
"rx_bytes": 0,
|
||||
"rx_bytes-r": 0,
|
||||
"rx_dropped": 0,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 0,
|
||||
"rx_packets": 0,
|
||||
"satisfaction": 100,
|
||||
"speed": 0,
|
||||
"speed_caps": 1048623,
|
||||
"stp_pathcost": 0,
|
||||
"stp_state": "disabled",
|
||||
"tx_broadcast": 0,
|
||||
"tx_bytes": 0,
|
||||
"tx_bytes-r": 0,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_multicast": 0,
|
||||
"tx_packets": 0,
|
||||
"up": false
|
||||
}
|
||||
],
|
||||
"power_source": "262144",
|
||||
"power_source_voltage": "48.00",
|
||||
"prev_non_busy_state": 1,
|
||||
"required_version": "3.7.16",
|
||||
"rx_bytes": 100334873692,
|
||||
"satisfaction": 98,
|
||||
"serial": "F09F11223344",
|
||||
"site_id": "5a32aa4ee4b0412345678910",
|
||||
"ssh_session_table": [],
|
||||
"start_connected_millis": 1587859250668,
|
||||
"start_disconnected_millis": 1587859249151,
|
||||
"stat": {
|
||||
"sw": {
|
||||
"bytes": 522138756790.0,
|
||||
"datetime": "2020-04-26T00:00:00Z",
|
||||
"duration": 316469000.0,
|
||||
"o": "sw",
|
||||
"oid": "f0:9f:11:22:33:44",
|
||||
"port_2-rx_broadcast": 3728.0,
|
||||
"port_2-rx_bytes": 76911368375.0,
|
||||
"port_2-rx_multicast": 11056.0,
|
||||
"port_2-rx_packets": 56426757.0,
|
||||
"port_2-tx_broadcast": 188293.0,
|
||||
"port_2-tx_bytes": 6099269315.0,
|
||||
"port_2-tx_multicast": 650992.0,
|
||||
"port_2-tx_packets": 24859744.0,
|
||||
"port_4-rx_bytes": 1255789.0,
|
||||
"port_4-rx_packets": 18703.0,
|
||||
"port_4-tx_broadcast": 192021.0,
|
||||
"port_4-tx_bytes": 156439725.0,
|
||||
"port_4-tx_multicast": 651520.0,
|
||||
"port_4-tx_packets": 862886.0,
|
||||
"port_5-rx_broadcast": 10231.0,
|
||||
"port_5-rx_bytes": 1916386586.0,
|
||||
"port_5-rx_multicast": 33021.0,
|
||||
"port_5-rx_packets": 14642662.0,
|
||||
"port_5-tx_broadcast": 181790.0,
|
||||
"port_5-tx_bytes": 36477482238.0,
|
||||
"port_5-tx_multicast": 628931.0,
|
||||
"port_5-tx_packets": 27718236.0,
|
||||
"port_6-rx_broadcast": 19949.0,
|
||||
"port_6-rx_bytes": 3988926804.0,
|
||||
"port_6-rx_multicast": 258385.0,
|
||||
"port_6-rx_packets": 26449642.0,
|
||||
"port_6-tx_broadcast": 172072.0,
|
||||
"port_6-tx_bytes": 216628215977.0,
|
||||
"port_6-tx_dropped": 202.0,
|
||||
"port_6-tx_multicast": 403675.0,
|
||||
"port_6-tx_packets": 148081715.0,
|
||||
"port_7-rx_broadcast": 148618.0,
|
||||
"port_7-rx_bytes": 177986447879.0,
|
||||
"port_7-rx_multicast": 211883.0,
|
||||
"port_7-rx_packets": 119394527.0,
|
||||
"port_7-tx_broadcast": 43403.0,
|
||||
"port_7-tx_bytes": 1972964102.0,
|
||||
"port_7-tx_multicast": 439638.0,
|
||||
"port_7-tx_packets": 18291623.0,
|
||||
"rx_broadcast": 182526.0,
|
||||
"rx_bytes": 260804385433.0,
|
||||
"rx_crypts": 0.0,
|
||||
"rx_dropped": 0.0,
|
||||
"rx_errors": 0.0,
|
||||
"rx_frags": 0.0,
|
||||
"rx_multicast": 514345.0,
|
||||
"rx_packets": 216932291.0,
|
||||
"site_id": "5a32aa4ee4b0412345678910",
|
||||
"sw": "f0:9f:11:22:33:44",
|
||||
"time": 1587859200000,
|
||||
"tx_broadcast": 777579.0,
|
||||
"tx_bytes": 261334371357.0,
|
||||
"tx_dropped": 202.0,
|
||||
"tx_errors": 0.0,
|
||||
"tx_multicast": 2774756.0,
|
||||
"tx_packets": 219814204.0,
|
||||
"tx_retries": 0.0
|
||||
}
|
||||
},
|
||||
"state": 1,
|
||||
"stp_priority": "32768",
|
||||
"stp_version": "rstp",
|
||||
"switch_caps": {
|
||||
"feature_caps": 1022,
|
||||
"max_aggregate_sessions": 4,
|
||||
"max_mirror_sessions": 1
|
||||
},
|
||||
"sys_error_caps": 0,
|
||||
"sys_stats": {
|
||||
"loadavg_1": "1.12",
|
||||
"loadavg_15": "1.45",
|
||||
"loadavg_5": "1.31",
|
||||
"mem_buffer": 0,
|
||||
"mem_total": 262402048,
|
||||
"mem_used": 128737280
|
||||
},
|
||||
"syslog_key": "REDACTED",
|
||||
"system-stats": {
|
||||
"cpu": "56.3",
|
||||
"mem": "49.1",
|
||||
"uptime": "3971894"
|
||||
},
|
||||
"total_max_power": 0,
|
||||
"two_phase_adopt": false,
|
||||
"tx_bytes": 1109019728759,
|
||||
"type": "usw",
|
||||
"unsupported": false,
|
||||
"unsupported_reason": 0,
|
||||
"upgradable": true,
|
||||
"upgrade_state": 0,
|
||||
"upgrade_to_firmware": "4.0.80.10875",
|
||||
"uplink": {
|
||||
"full_duplex": true,
|
||||
"ip": "192.168.0.8",
|
||||
"mac": "f0:9f:11:22:33:44",
|
||||
"max_speed": 1000,
|
||||
"media": "GE",
|
||||
"name": "eth0",
|
||||
"netmask": "255.255.255.0",
|
||||
"num_port": 8,
|
||||
"port_idx": 2,
|
||||
"rx_bytes": 1109019728759,
|
||||
"rx_bytes-r": 240953,
|
||||
"rx_dropped": 0,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 0,
|
||||
"rx_packets": 808013990,
|
||||
"speed": 1000,
|
||||
"tx_bytes": 100334873692,
|
||||
"tx_bytes-r": 3480,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_packets": 356816368,
|
||||
"type": "wire",
|
||||
"up": true,
|
||||
"uplink_mac": "78:8a:20:33:44:55"
|
||||
},
|
||||
"uplink_depth": 1,
|
||||
"uptime": 3971894,
|
||||
"user-num_sta": 4,
|
||||
"version": "4.0.66.10832",
|
||||
"x_aes_gcm": "REDACTED",
|
||||
"x_authkey": "REDACTED",
|
||||
"x_has_ssh_hostkey": "REDACTED",
|
||||
"x_inform_authkey": "REDACTED",
|
||||
"x_ssh_hostkey_fingerprint": "REDACTED"
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
{
|
||||
"_id": "5f47a419c753120123456789",
|
||||
"_uptime": 9273422,
|
||||
"adopt_ip": "198.168.0.9",
|
||||
"adopt_url": "http://192.168.0.1:8080/inform",
|
||||
"adoptable_when_upgraded": false,
|
||||
"adopted": true,
|
||||
"anomalies": -1,
|
||||
"anon_id": "REDACTED",
|
||||
"board_rev": 12,
|
||||
"bytes": 0,
|
||||
"cfgversion": "96376fe9d11ae1ac",
|
||||
"config_network": {
|
||||
"ip": "198.168.0.9",
|
||||
"type": "dhcp"
|
||||
},
|
||||
"connect_request_ip": "198.168.0.9",
|
||||
"connect_request_port": "60216",
|
||||
"connected_at": 1634732311,
|
||||
"connection_network_name": "LAN",
|
||||
"default": false,
|
||||
"device_id": "5f47a419c753120123456789",
|
||||
"dhcp_server_table": [],
|
||||
"discovered_via": "l2",
|
||||
"displayable_version": "1.8.4",
|
||||
"dot1x_portctrl_enabled": false,
|
||||
"downlink_table": [],
|
||||
"ethernet_table": [
|
||||
{
|
||||
"mac": "74:ac:b9:a1:01:01",
|
||||
"name": "eth0",
|
||||
"num_port": 5
|
||||
}
|
||||
],
|
||||
"flowctrl_enabled": false,
|
||||
"fw_caps": 0,
|
||||
"guest-num_sta": 0,
|
||||
"has_fan": false,
|
||||
"has_temperature": false,
|
||||
"hw_caps": 0,
|
||||
"inform_ip": "192.168.0.1",
|
||||
"inform_url": "http://192.168.0.1:8080/inform",
|
||||
"ip": "198.168.0.9",
|
||||
"jumboframe_enabled": false,
|
||||
"known_cfgversion": "96376fe9d11ae1ac",
|
||||
"last_seen": 1635577067,
|
||||
"last_uplink": {
|
||||
"port_idx": 1,
|
||||
"type": "wire",
|
||||
"uplink_mac": "fc:ec:00:11:22:33",
|
||||
"uplink_remote_port": 13
|
||||
},
|
||||
"lcm_brightness_override": false,
|
||||
"lcm_idle_timeout_override": false,
|
||||
"lcm_tracker_enabled": false,
|
||||
"led_override": "on",
|
||||
"led_override_color": "#0000ff",
|
||||
"led_override_color_brightness": 100,
|
||||
"license_state": "registered",
|
||||
"lldp_table": [
|
||||
{
|
||||
"chassis_id": "fc:ec:00:11:22:33",
|
||||
"is_wired": true,
|
||||
"local_port_idx": 1,
|
||||
"local_port_name": "eth0",
|
||||
"port_id": "Port "
|
||||
}
|
||||
],
|
||||
"locating": false,
|
||||
"mac": "74:ac:b9:a1:01:01",
|
||||
"manufacturer_id": 2,
|
||||
"model": "USMINI",
|
||||
"model_in_eol": false,
|
||||
"model_in_lts": false,
|
||||
"model_incompatible": false,
|
||||
"name": "UniFi Switch Flex Mini",
|
||||
"next_interval": 34,
|
||||
"num_sta": 0,
|
||||
"outdoor_mode_override": "default",
|
||||
"overheating": false,
|
||||
"port_table": [
|
||||
{
|
||||
"aggregated_by": false,
|
||||
"autoneg": true,
|
||||
"bytes-r": 577,
|
||||
"enable": true,
|
||||
"flowctrl_rx": false,
|
||||
"flowctrl_tx": false,
|
||||
"full_duplex": true,
|
||||
"is_uplink": true,
|
||||
"jumbo": false,
|
||||
"masked": false,
|
||||
"media": "GE",
|
||||
"name": "Port 1",
|
||||
"op_mode": "switch",
|
||||
"port_idx": 1,
|
||||
"port_poe": false,
|
||||
"portconf_id": "5f3edd2aba4cc806a19f2db2",
|
||||
"rx_broadcast": 6679204,
|
||||
"rx_bytes": 6147696151,
|
||||
"rx_bytes-r": 452,
|
||||
"rx_dropped": 0,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 20240009,
|
||||
"rx_packets": 30183544,
|
||||
"speed": 1000,
|
||||
"speed_caps": 1048623,
|
||||
"tx_broadcast": 3397,
|
||||
"tx_bytes": 1243754733,
|
||||
"tx_bytes-r": 124,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_multicast": 310278,
|
||||
"tx_packets": 3836158,
|
||||
"up": true
|
||||
},
|
||||
{
|
||||
"aggregated_by": false,
|
||||
"autoneg": true,
|
||||
"bytes-r": 0,
|
||||
"enable": true,
|
||||
"flowctrl_rx": false,
|
||||
"flowctrl_tx": false,
|
||||
"full_duplex": false,
|
||||
"is_uplink": false,
|
||||
"jumbo": false,
|
||||
"masked": false,
|
||||
"media": "GE",
|
||||
"name": "Port 2",
|
||||
"op_mode": "switch",
|
||||
"port_idx": 2,
|
||||
"port_poe": false,
|
||||
"portconf_id": "5f3edd2aba4cc806a19f2db2",
|
||||
"rx_broadcast": 0,
|
||||
"rx_bytes": 0,
|
||||
"rx_bytes-r": 0,
|
||||
"rx_dropped": 0,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 0,
|
||||
"rx_packets": 0,
|
||||
"speed": 0,
|
||||
"speed_caps": 1048623,
|
||||
"tx_broadcast": 0,
|
||||
"tx_bytes": 0,
|
||||
"tx_bytes-r": 0,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_multicast": 0,
|
||||
"tx_packets": 0,
|
||||
"up": false
|
||||
},
|
||||
{
|
||||
"aggregated_by": false,
|
||||
"autoneg": true,
|
||||
"bytes-r": 0,
|
||||
"enable": true,
|
||||
"flowctrl_rx": false,
|
||||
"flowctrl_tx": false,
|
||||
"full_duplex": false,
|
||||
"is_uplink": false,
|
||||
"jumbo": false,
|
||||
"masked": false,
|
||||
"media": "GE",
|
||||
"name": "Port 3",
|
||||
"op_mode": "switch",
|
||||
"port_idx": 3,
|
||||
"port_poe": false,
|
||||
"portconf_id": "5f3edd2aba4cc806a19f2db2",
|
||||
"rx_broadcast": 0,
|
||||
"rx_bytes": 0,
|
||||
"rx_bytes-r": 0,
|
||||
"rx_dropped": 0,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 0,
|
||||
"rx_packets": 0,
|
||||
"speed": 0,
|
||||
"speed_caps": 1048623,
|
||||
"tx_broadcast": 0,
|
||||
"tx_bytes": 0,
|
||||
"tx_bytes-r": 0,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_multicast": 0,
|
||||
"tx_packets": 0,
|
||||
"up": false
|
||||
},
|
||||
{
|
||||
"aggregated_by": false,
|
||||
"autoneg": true,
|
||||
"bytes-r": 0,
|
||||
"enable": true,
|
||||
"flowctrl_rx": false,
|
||||
"flowctrl_tx": false,
|
||||
"full_duplex": false,
|
||||
"is_uplink": false,
|
||||
"jumbo": false,
|
||||
"masked": false,
|
||||
"media": "GE",
|
||||
"name": "Port 4",
|
||||
"op_mode": "switch",
|
||||
"port_idx": 4,
|
||||
"port_poe": false,
|
||||
"portconf_id": "5f3edd2aba4cc806a19f2db2",
|
||||
"rx_broadcast": 0,
|
||||
"rx_bytes": 0,
|
||||
"rx_bytes-r": 0,
|
||||
"rx_dropped": 0,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 0,
|
||||
"rx_packets": 0,
|
||||
"speed": 0,
|
||||
"speed_caps": 1048623,
|
||||
"tx_broadcast": 0,
|
||||
"tx_bytes": 0,
|
||||
"tx_bytes-r": 0,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_multicast": 0,
|
||||
"tx_packets": 0,
|
||||
"up": false
|
||||
},
|
||||
{
|
||||
"aggregated_by": false,
|
||||
"autoneg": true,
|
||||
"bytes-r": 0,
|
||||
"enable": true,
|
||||
"flowctrl_rx": false,
|
||||
"flowctrl_tx": false,
|
||||
"full_duplex": false,
|
||||
"is_uplink": false,
|
||||
"jumbo": false,
|
||||
"masked": false,
|
||||
"media": "GE",
|
||||
"name": "Port 5",
|
||||
"op_mode": "switch",
|
||||
"port_idx": 5,
|
||||
"port_poe": false,
|
||||
"portconf_id": "5f3edd2aba4cc806a19f2db2",
|
||||
"rx_broadcast": 0,
|
||||
"rx_bytes": 0,
|
||||
"rx_bytes-r": 0,
|
||||
"rx_dropped": 0,
|
||||
"rx_errors": 0,
|
||||
"rx_multicast": 0,
|
||||
"rx_packets": 0,
|
||||
"speed": 0,
|
||||
"speed_caps": 1048623,
|
||||
"tx_broadcast": 0,
|
||||
"tx_bytes": 0,
|
||||
"tx_bytes-r": 0,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_multicast": 0,
|
||||
"tx_packets": 0,
|
||||
"up": false
|
||||
}
|
||||
],
|
||||
"power_source_ctrl_enabled": false,
|
||||
"provisioned_at": 1610008100,
|
||||
"required_version": "1.7.3",
|
||||
"rollupgrade": false,
|
||||
"rx_bytes": 0,
|
||||
"satisfaction": -1,
|
||||
"serial": "74ACB9A10101",
|
||||
"site_id": "5a32aa4ee4b0412345678910",
|
||||
"start_connected_millis": 1634732311256,
|
||||
"start_disconnected_millis": 1634732296240,
|
||||
"startup_timestamp": 1626303645,
|
||||
"stat": {
|
||||
"sw": {
|
||||
"bytes": 648398923.0,
|
||||
"datetime": "2021-10-20T12:15:00Z",
|
||||
"duration": 844723000.0,
|
||||
"o": "sw",
|
||||
"oid": "74:ac:b9:a1:01:01",
|
||||
"port_1-rx_broadcast": 565601.0,
|
||||
"port_1-rx_bytes": 535337644.0,
|
||||
"port_1-rx_multicast": 1790802.0,
|
||||
"port_1-rx_packets": 2652630.0,
|
||||
"port_1-tx_broadcast": 335.0,
|
||||
"port_1-tx_bytes": 113061279.0,
|
||||
"port_1-tx_multicast": 28157.0,
|
||||
"port_1-tx_packets": 348590.0,
|
||||
"rx_broadcast": 565601.0,
|
||||
"rx_bytes": 535337644.0,
|
||||
"rx_crypts": 0.0,
|
||||
"rx_dropped": 0.0,
|
||||
"rx_errors": 0.0,
|
||||
"rx_frags": 0.0,
|
||||
"rx_multicast": 1790802.0,
|
||||
"rx_packets": 2652630.0,
|
||||
"site_id": "5a32aa4ee4b0412345678910",
|
||||
"sw": "74:ac:b9:a1:01:01",
|
||||
"time": 1634732100000,
|
||||
"tx_broadcast": 335.0,
|
||||
"tx_bytes": 113061279.0,
|
||||
"tx_dropped": 0.0,
|
||||
"tx_errors": 0.0,
|
||||
"tx_multicast": 28157.0,
|
||||
"tx_packets": 348590.0,
|
||||
"tx_retries": 0.0
|
||||
}
|
||||
},
|
||||
"state": 1,
|
||||
"stp_priority": "32768",
|
||||
"stp_version": "rstp",
|
||||
"switch_caps": {
|
||||
"feature_caps": 44,
|
||||
"max_aggregate_sessions": 0,
|
||||
"max_mirror_sessions": 1,
|
||||
"vlan_caps": 2
|
||||
},
|
||||
"sys_error_caps": 0,
|
||||
"sys_stats": {
|
||||
"mem_total": 163840,
|
||||
"mem_used": 131940
|
||||
},
|
||||
"syslog_key": "REDACTED",
|
||||
"system-stats": {},
|
||||
"two_phase_adopt": false,
|
||||
"tx_bytes": 0,
|
||||
"type": "usw",
|
||||
"unsupported": false,
|
||||
"unsupported_reason": 0,
|
||||
"upgradable": false,
|
||||
"uplink": {
|
||||
"full_duplex": true,
|
||||
"ip": "198.168.0.9",
|
||||
"mac": "74:ac:b9:a1:01:01",
|
||||
"max_speed": 1000,
|
||||
"media": "GE",
|
||||
"name": "eth0",
|
||||
"netmask": "255.255.255.0",
|
||||
"num_port": 5,
|
||||
"port_idx": 1,
|
||||
"rx_bytes": 0,
|
||||
"rx_bytes-r": 0,
|
||||
"rx_dropped": 0,
|
||||
"rx_errors": 0,
|
||||
"rx_packets": 0,
|
||||
"speed": 1000,
|
||||
"tx_bytes": 0,
|
||||
"tx_bytes-r": 0,
|
||||
"tx_dropped": 0,
|
||||
"tx_errors": 0,
|
||||
"tx_packets": 0,
|
||||
"type": "wire",
|
||||
"up": true,
|
||||
"uplink_mac": "fc:ec:00:11:22:33",
|
||||
"uplink_remote_port": 13
|
||||
},
|
||||
"uplink_depth": 2,
|
||||
"uptime": 9273422,
|
||||
"user-num_sta": 0,
|
||||
"version": "1.8.4.674",
|
||||
"x_aes_gcm": "REDACTED",
|
||||
"x_authkey": "REDACTED",
|
||||
"x_has_ssh_hostkey": "REDACTED"
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
[
|
||||
{
|
||||
"_id": "012345678910111213141516",
|
||||
"bc_filter_enabled": false,
|
||||
"bc_filter_list": [],
|
||||
"dtim_mode": "default",
|
||||
"dtim_na": 1,
|
||||
"dtim_ng": 1,
|
||||
"enabled": true,
|
||||
"group_rekey": 3600,
|
||||
"mac_filter_enabled": false,
|
||||
"mac_filter_list": [],
|
||||
"mac_filter_policy": "allow",
|
||||
"minrate_na_advertising_rates": false,
|
||||
"minrate_na_beacon_rate_kbps": 6000,
|
||||
"minrate_na_data_rate_kbps": 6000,
|
||||
"minrate_na_enabled": false,
|
||||
"minrate_na_mgmt_rate_kbps": 6000,
|
||||
"minrate_ng_advertising_rates": false,
|
||||
"minrate_ng_beacon_rate_kbps": 1000,
|
||||
"minrate_ng_data_rate_kbps": 1000,
|
||||
"minrate_ng_enabled": false,
|
||||
"minrate_ng_mgmt_rate_kbps": 1000,
|
||||
"name": "SSID 1",
|
||||
"no2ghz_oui": false,
|
||||
"schedule": [],
|
||||
"security": "wpapsk",
|
||||
"site_id": "5a32aa4ee4b0412345678910",
|
||||
"usergroup_id": "012345678910111213141518",
|
||||
"wep_idx": 1,
|
||||
"wlangroup_id": "012345678910111213141519",
|
||||
"wpa_enc": "ccmp",
|
||||
"wpa_mode": "wpa2",
|
||||
"x_iapp_key": "REDACTED",
|
||||
"x_passphrase": "REDACTED"
|
||||
},
|
||||
{
|
||||
"_id": "123456789101112161415160",
|
||||
"bc_filter_enabled": true,
|
||||
"bc_filter_list": [],
|
||||
"dtim_mode": "default",
|
||||
"dtim_na": 1,
|
||||
"dtim_ng": 1,
|
||||
"enabled": false,
|
||||
"group_rekey": 3600,
|
||||
"hide_ssid": true,
|
||||
"is_guest": true,
|
||||
"mac_filter_enabled": false,
|
||||
"mac_filter_list": [],
|
||||
"mac_filter_policy": "allow",
|
||||
"minrate_na_advertising_rates": false,
|
||||
"minrate_na_beacon_rate_kbps": 6000,
|
||||
"minrate_na_data_rate_kbps": 6000,
|
||||
"minrate_na_enabled": false,
|
||||
"minrate_na_mgmt_rate_kbps": 6000,
|
||||
"minrate_ng_advertising_rates": false,
|
||||
"minrate_ng_beacon_rate_kbps": 1000,
|
||||
"minrate_ng_cck_rates_enabled": true,
|
||||
"minrate_ng_data_rate_kbps": 1000,
|
||||
"minrate_ng_enabled": false,
|
||||
"minrate_ng_mgmt_rate_kbps": 1000,
|
||||
"name": "SSID 2",
|
||||
"schedule": [],
|
||||
"security": "wpapsk",
|
||||
"site_id": "5a32aa4ee4b0412345678910",
|
||||
"usergroup_id": "123456789101112161415162",
|
||||
"wep_idx": 1,
|
||||
"wlangroup_id": "123456789101112161415163",
|
||||
"wpa_enc": "ccmp",
|
||||
"wpa_mode": "wpa2",
|
||||
"x_iapp_key": "REDACTED",
|
||||
"x_passphrase": "REDACTED"
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,78 @@
|
||||
{
|
||||
"offset": 0,
|
||||
"limit": 25,
|
||||
"count": 4,
|
||||
"totalCount": 4,
|
||||
"data": [
|
||||
{
|
||||
"id": "5b5e2c17-0d3c-3c47-a0f1-6c1d2f1e0001",
|
||||
"macAddress": "fc:ec:da:11:22:33",
|
||||
"ipAddress": "192.168.0.57",
|
||||
"name": "Switch 16",
|
||||
"model": "US16P150",
|
||||
"state": "ONLINE",
|
||||
"supported": true,
|
||||
"firmwareVersion": "4.0.66.10832",
|
||||
"firmwareUpdatable": true,
|
||||
"features": [
|
||||
"switching"
|
||||
],
|
||||
"interfaces": [
|
||||
"ports"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "5b5e2c17-0d3c-3c47-a0f1-6c1d2f1e0002",
|
||||
"macAddress": "80:2a:a8:00:01:02",
|
||||
"ipAddress": "192.168.0.4",
|
||||
"name": "ACCESS POINT AC PRO",
|
||||
"model": "U7PG2",
|
||||
"state": "ONLINE",
|
||||
"supported": true,
|
||||
"firmwareVersion": "4.0.69.10871",
|
||||
"firmwareUpdatable": false,
|
||||
"features": [
|
||||
"accessPoint"
|
||||
],
|
||||
"interfaces": [
|
||||
"ports",
|
||||
"radios"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "5b5e2c17-0d3c-3c47-a0f1-6c1d2f1e0003",
|
||||
"macAddress": "74:ac:b9:a1:01:01",
|
||||
"ipAddress": "198.168.0.9",
|
||||
"name": "UniFi Switch Flex Mini",
|
||||
"model": "USMINI",
|
||||
"state": "CONNECTION_INTERRUPTED",
|
||||
"supported": true,
|
||||
"firmwareVersion": "1.8.4.674",
|
||||
"firmwareUpdatable": false,
|
||||
"features": [
|
||||
"switching"
|
||||
],
|
||||
"interfaces": [
|
||||
"ports"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "5b5e2c17-0d3c-3c47-a0f1-6c1d2f1e0004",
|
||||
"macAddress": "78:8a:20:33:44:55",
|
||||
"ipAddress": "1.2.3.4",
|
||||
"name": "USG",
|
||||
"model": "UGW3",
|
||||
"state": "UPDATING",
|
||||
"supported": true,
|
||||
"firmwareVersion": "4.4.44.5213844",
|
||||
"firmwareUpdatable": false,
|
||||
"features": [
|
||||
"gateway",
|
||||
"switching"
|
||||
],
|
||||
"interfaces": [
|
||||
"ports"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"applicationVersion": "10.6.106"
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"offset": 0,
|
||||
"limit": 25,
|
||||
"count": 1,
|
||||
"totalCount": 1,
|
||||
"data": [
|
||||
{
|
||||
"macAddress": "f4:92:bf:00:00:aa",
|
||||
"ipAddress": "192.168.0.77",
|
||||
"model": "U6LR",
|
||||
"state": "PENDING_ADOPTION",
|
||||
"supported": true,
|
||||
"firmwareVersion": "6.6.55",
|
||||
"firmwareUpdatable": false,
|
||||
"features": [
|
||||
"accessPoint"
|
||||
],
|
||||
"adoptionTargetSiteIds": [
|
||||
"88f7af54-98f8-306a-a1c7-c9349722b1f6"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"offset": 0,
|
||||
"limit": 25,
|
||||
"count": 1,
|
||||
"totalCount": 1,
|
||||
"data": [
|
||||
{
|
||||
"id": "88f7af54-98f8-306a-a1c7-c9349722b1f6",
|
||||
"internalReference": "default",
|
||||
"name": "Default"
|
||||
}
|
||||
]
|
||||
}
|
||||
+1220
File diff suppressed because it is too large.
Load diff
+482
@@ -0,0 +1,482 @@
|
||||
# unifi
|
||||
unifi.version=9.0.114
|
||||
unifi.anonymous_controller_id=00000000-0000-4000-8000-000000000001
|
||||
unifi.anonymous_site_id=00000000-0000-4000-8000-000000000002
|
||||
unifi.reporterid=00000000-0000-4000-8000-000000000001
|
||||
unifi.siteid=000000000000000000000001
|
||||
unifi.idp=enabled
|
||||
unifi.mcip=239.254.127.63
|
||||
unifi.key=REDACTED
|
||||
unifi.feature.always_send_crash_logs=enabled
|
||||
# system
|
||||
system.analytics.status=disabled
|
||||
system.timezone=EST5EDT,M3.2.0,M11.1.0
|
||||
locale.timezone=EST5EDT,M3.2.0,M11.1.0
|
||||
# users
|
||||
users.status=enabled
|
||||
users.1.name=admin
|
||||
users.1.password=REDACTED
|
||||
users.1.status=enabled
|
||||
users.2.name=nobody
|
||||
users.2.password=REDACTED
|
||||
users.2.shell=/bin/false
|
||||
users.2.status=enabled
|
||||
# vlan
|
||||
vlan.status=disabled
|
||||
# bridge
|
||||
bridge.status=disabled
|
||||
# netconf
|
||||
netconf.status=enabled
|
||||
netconf.1.status=enabled
|
||||
netconf.1.devname=eth0
|
||||
netconf.1.ip=10.0.0.10
|
||||
netconf.1.autoip.status=disabled
|
||||
netconf.1.netmask=255.255.255.0
|
||||
netconf.1.promisc=enabled
|
||||
netconf.1.up=enabled
|
||||
# dhcpc
|
||||
dhcpc.status=enabled
|
||||
# route
|
||||
route.1.status=enabled
|
||||
route.1.devname=eth0
|
||||
route.1.ip=0.0.0.0
|
||||
route.1.gateway=10.0.0.1
|
||||
route.status=enabled
|
||||
# resolv
|
||||
resolv.status=enabled
|
||||
resolv.host.1.name=usw-1
|
||||
resolv.nameserver.1.ip=1.1.1.1
|
||||
resolv.nameserver.2.status=disabled
|
||||
# switch
|
||||
switch.power_source.status=disabled
|
||||
switch.managementvlan=1
|
||||
switch.wevent.idp=enabled
|
||||
switch.wevent.mcip=239.254.127.63
|
||||
switch.wevent.key=REDACTED
|
||||
switch.jumboframes=disabled
|
||||
switch.mtu=9216
|
||||
switch.stp.version=rstp
|
||||
switch.stp.priority=0
|
||||
switch.stp.status=enabled
|
||||
switch.dot1x.status=disabled
|
||||
switch.vlan.1.id=1
|
||||
switch.vlan.1.mode=untagged
|
||||
switch.vlan.1.status=enabled
|
||||
switch.vlan.2.id=2
|
||||
switch.vlan.2.mode=tagged
|
||||
switch.vlan.2.status=enabled
|
||||
switch.vlan.2.igmp_snooping=true
|
||||
switch.vlan.2.igmp_fastleave=false
|
||||
switch.vlan.2.igmp_maxresponse=10
|
||||
switch.vlan.2.igmp_mcrtrexpiretime=0
|
||||
switch.vlan.2.igmp_groupmembership=260
|
||||
switch.vlan.2.igmp_querier=
|
||||
switch.vlan.2.igmp_supression=false
|
||||
switch.vlan.2.forward_unknown_multicast=false
|
||||
switch.vlan.3.id=3
|
||||
switch.vlan.3.mode=tagged
|
||||
switch.vlan.3.status=enabled
|
||||
switch.vlan.3.igmp_snooping=true
|
||||
switch.vlan.3.igmp_fastleave=false
|
||||
switch.vlan.3.igmp_maxresponse=10
|
||||
switch.vlan.3.igmp_mcrtrexpiretime=0
|
||||
switch.vlan.3.igmp_groupmembership=260
|
||||
switch.vlan.3.igmp_querier=
|
||||
switch.vlan.3.igmp_supression=false
|
||||
switch.vlan.3.forward_unknown_multicast=false
|
||||
switch.vlan.4.id=4
|
||||
switch.vlan.4.mode=tagged
|
||||
switch.vlan.4.status=enabled
|
||||
switch.vlan.4.igmp_snooping=true
|
||||
switch.vlan.4.igmp_fastleave=false
|
||||
switch.vlan.4.igmp_maxresponse=10
|
||||
switch.vlan.4.igmp_mcrtrexpiretime=0
|
||||
switch.vlan.4.igmp_groupmembership=260
|
||||
switch.vlan.4.igmp_querier=
|
||||
switch.vlan.4.igmp_supression=false
|
||||
switch.vlan.4.forward_unknown_multicast=false
|
||||
switch.vlan.5.id=5
|
||||
switch.vlan.5.mode=tagged
|
||||
switch.vlan.5.status=enabled
|
||||
switch.vlan.5.igmp_snooping=true
|
||||
switch.vlan.5.igmp_fastleave=false
|
||||
switch.vlan.5.igmp_maxresponse=10
|
||||
switch.vlan.5.igmp_mcrtrexpiretime=0
|
||||
switch.vlan.5.igmp_groupmembership=260
|
||||
switch.vlan.5.igmp_querier=
|
||||
switch.vlan.5.igmp_supression=false
|
||||
switch.vlan.5.forward_unknown_multicast=false
|
||||
switch.vlan.6.id=6
|
||||
switch.vlan.6.mode=tagged
|
||||
switch.vlan.6.status=enabled
|
||||
switch.vlan.6.igmp_snooping=true
|
||||
switch.vlan.6.igmp_fastleave=false
|
||||
switch.vlan.6.igmp_maxresponse=10
|
||||
switch.vlan.6.igmp_mcrtrexpiretime=0
|
||||
switch.vlan.6.igmp_groupmembership=260
|
||||
switch.vlan.6.igmp_querier=
|
||||
switch.vlan.6.igmp_supression=false
|
||||
switch.vlan.6.forward_unknown_multicast=false
|
||||
switch.vlan.7.id=7
|
||||
switch.vlan.7.mode=tagged
|
||||
switch.vlan.7.status=enabled
|
||||
switch.vlan.8.id=8
|
||||
switch.vlan.8.mode=tagged
|
||||
switch.vlan.8.status=enabled
|
||||
switch.vlan.8.igmp_snooping=true
|
||||
switch.vlan.8.igmp_fastleave=false
|
||||
switch.vlan.8.igmp_maxresponse=10
|
||||
switch.vlan.8.igmp_mcrtrexpiretime=0
|
||||
switch.vlan.8.igmp_groupmembership=260
|
||||
switch.vlan.8.igmp_querier=
|
||||
switch.vlan.8.igmp_supression=false
|
||||
switch.vlan.8.forward_unknown_multicast=false
|
||||
switch.vlan.9.id=9
|
||||
switch.vlan.9.mode=tagged
|
||||
switch.vlan.9.status=enabled
|
||||
switch.vlan.10.id=10
|
||||
switch.vlan.10.mode=tagged
|
||||
switch.vlan.10.status=enabled
|
||||
switch.vlan.10.igmp_snooping=true
|
||||
switch.vlan.10.igmp_fastleave=false
|
||||
switch.vlan.10.igmp_maxresponse=10
|
||||
switch.vlan.10.igmp_mcrtrexpiretime=0
|
||||
switch.vlan.10.igmp_groupmembership=260
|
||||
switch.vlan.10.igmp_querier=
|
||||
switch.vlan.10.igmp_supression=false
|
||||
switch.vlan.10.forward_unknown_multicast=false
|
||||
switch.vlan.11.id=11
|
||||
switch.vlan.11.mode=tagged
|
||||
switch.vlan.11.status=enabled
|
||||
switch.vlan.12.id=12
|
||||
switch.vlan.12.mode=tagged
|
||||
switch.vlan.12.status=enabled
|
||||
switch.vlan.13.id=100
|
||||
switch.vlan.13.mode=tagged
|
||||
switch.vlan.13.status=enabled
|
||||
switch.dhcp_snoop.status=enabled
|
||||
# switch ACL
|
||||
switch.routing_enabled=false
|
||||
switch.port.1.name=1
|
||||
switch.port.1.status=disabled
|
||||
switch.port.1.lldpmed.opmode=enabled
|
||||
switch.port.1.lldpmed.topology_notify=disabled
|
||||
switch.port.1.stp.port_mode=enabled
|
||||
switch.port.1.keepalive=disabled
|
||||
switch.port.1.opmode=switch
|
||||
switch.port.1.port-security=enabled
|
||||
switch.port.2.name=2
|
||||
switch.port.2.lldpmed.opmode=enabled
|
||||
switch.port.2.lldpmed.topology_notify=disabled
|
||||
switch.port.2.stp.port_mode=enabled
|
||||
switch.port.2.keepalive=disabled
|
||||
switch.port.2.opmode=switch
|
||||
switch.port.2.pvid=11
|
||||
switch.port.2.port-security=disabled
|
||||
switch.vlan.1.port.2.mode=exclude
|
||||
switch.vlan.2.port.2.mode=exclude
|
||||
switch.vlan.3.port.2.mode=exclude
|
||||
switch.vlan.4.port.2.mode=exclude
|
||||
switch.vlan.5.port.2.mode=exclude
|
||||
switch.vlan.6.port.2.mode=exclude
|
||||
switch.vlan.7.port.2.mode=exclude
|
||||
switch.vlan.8.port.2.mode=exclude
|
||||
switch.vlan.9.port.2.mode=exclude
|
||||
switch.vlan.10.port.2.mode=exclude
|
||||
switch.vlan.11.port.2.mode=untagged
|
||||
switch.vlan.12.port.2.mode=exclude
|
||||
switch.vlan.13.port.2.mode=exclude
|
||||
switch.port.3.name=3
|
||||
switch.port.3.lldpmed.opmode=enabled
|
||||
switch.port.3.lldpmed.topology_notify=disabled
|
||||
switch.port.3.stp.port_mode=enabled
|
||||
switch.port.3.keepalive=disabled
|
||||
switch.port.3.opmode=switch
|
||||
switch.port.3.port-security=disabled
|
||||
switch.port.4.name=4
|
||||
switch.port.4.lldpmed.opmode=enabled
|
||||
switch.port.4.lldpmed.topology_notify=disabled
|
||||
switch.port.4.stp.port_mode=enabled
|
||||
switch.port.4.keepalive=disabled
|
||||
switch.port.4.opmode=switch
|
||||
switch.port.4.port-security=disabled
|
||||
switch.port.5.name=5
|
||||
switch.port.5.lldpmed.opmode=enabled
|
||||
switch.port.5.lldpmed.topology_notify=disabled
|
||||
switch.port.5.stp.port_mode=enabled
|
||||
switch.port.5.keepalive=disabled
|
||||
switch.port.5.opmode=switch
|
||||
switch.port.5.port-security=disabled
|
||||
switch.port.6.name=6
|
||||
switch.port.6.lldpmed.opmode=enabled
|
||||
switch.port.6.lldpmed.topology_notify=disabled
|
||||
switch.port.6.stp.port_mode=enabled
|
||||
switch.port.6.keepalive=disabled
|
||||
switch.port.6.opmode=switch
|
||||
switch.port.6.port-security=disabled
|
||||
switch.port.7.name=7
|
||||
switch.port.7.lldpmed.opmode=enabled
|
||||
switch.port.7.lldpmed.topology_notify=disabled
|
||||
switch.port.7.stp.port_mode=enabled
|
||||
switch.port.7.keepalive=disabled
|
||||
switch.port.7.opmode=switch
|
||||
switch.port.7.port-security=disabled
|
||||
switch.port.8.name=8
|
||||
switch.port.8.lldpmed.opmode=enabled
|
||||
switch.port.8.lldpmed.topology_notify=disabled
|
||||
switch.port.8.stp.port_mode=enabled
|
||||
switch.port.8.keepalive=disabled
|
||||
switch.port.8.opmode=switch
|
||||
switch.port.8.port-security=disabled
|
||||
switch.port.9.name=9
|
||||
switch.port.9.lldpmed.opmode=enabled
|
||||
switch.port.9.lldpmed.topology_notify=disabled
|
||||
switch.port.9.stp.port_mode=enabled
|
||||
switch.port.9.keepalive=disabled
|
||||
switch.port.9.opmode=switch
|
||||
switch.port.9.pvid=8
|
||||
switch.port.9.port-security=disabled
|
||||
switch.vlan.1.port.9.mode=exclude
|
||||
switch.vlan.2.port.9.mode=exclude
|
||||
switch.vlan.3.port.9.mode=exclude
|
||||
switch.vlan.4.port.9.mode=exclude
|
||||
switch.vlan.5.port.9.mode=exclude
|
||||
switch.vlan.6.port.9.mode=exclude
|
||||
switch.vlan.7.port.9.mode=exclude
|
||||
switch.vlan.8.port.9.mode=untagged
|
||||
switch.vlan.9.port.9.mode=exclude
|
||||
switch.vlan.10.port.9.mode=exclude
|
||||
switch.vlan.11.port.9.mode=exclude
|
||||
switch.vlan.12.port.9.mode=exclude
|
||||
switch.vlan.13.port.9.mode=exclude
|
||||
switch.port.10.name=10
|
||||
switch.port.10.lldpmed.opmode=enabled
|
||||
switch.port.10.lldpmed.topology_notify=disabled
|
||||
switch.port.10.stp.port_mode=enabled
|
||||
switch.port.10.keepalive=disabled
|
||||
switch.port.10.opmode=switch
|
||||
switch.port.10.pvid=12
|
||||
switch.port.10.port-security=disabled
|
||||
switch.vlan.1.port.10.mode=exclude
|
||||
switch.vlan.2.port.10.mode=exclude
|
||||
switch.vlan.3.port.10.mode=exclude
|
||||
switch.vlan.4.port.10.mode=exclude
|
||||
switch.vlan.5.port.10.mode=exclude
|
||||
switch.vlan.6.port.10.mode=exclude
|
||||
switch.vlan.7.port.10.mode=exclude
|
||||
switch.vlan.8.port.10.mode=exclude
|
||||
switch.vlan.9.port.10.mode=exclude
|
||||
switch.vlan.10.port.10.mode=exclude
|
||||
switch.vlan.11.port.10.mode=exclude
|
||||
switch.vlan.12.port.10.mode=untagged
|
||||
switch.vlan.13.port.10.mode=exclude
|
||||
switch.port.11.name=11
|
||||
switch.port.11.lldpmed.opmode=enabled
|
||||
switch.port.11.lldpmed.topology_notify=disabled
|
||||
switch.port.11.stp.port_mode=enabled
|
||||
switch.port.11.keepalive=disabled
|
||||
switch.port.11.opmode=switch
|
||||
switch.port.11.pvid=12
|
||||
switch.port.11.port-security=disabled
|
||||
switch.vlan.1.port.11.mode=exclude
|
||||
switch.vlan.2.port.11.mode=exclude
|
||||
switch.vlan.3.port.11.mode=exclude
|
||||
switch.vlan.4.port.11.mode=exclude
|
||||
switch.vlan.5.port.11.mode=exclude
|
||||
switch.vlan.6.port.11.mode=exclude
|
||||
switch.vlan.7.port.11.mode=exclude
|
||||
switch.vlan.8.port.11.mode=exclude
|
||||
switch.vlan.9.port.11.mode=exclude
|
||||
switch.vlan.10.port.11.mode=exclude
|
||||
switch.vlan.11.port.11.mode=exclude
|
||||
switch.vlan.12.port.11.mode=untagged
|
||||
switch.vlan.13.port.11.mode=exclude
|
||||
switch.port.12.name=12
|
||||
switch.port.12.lldpmed.opmode=enabled
|
||||
switch.port.12.lldpmed.topology_notify=disabled
|
||||
switch.port.12.stp.port_mode=enabled
|
||||
switch.port.12.keepalive=disabled
|
||||
switch.port.12.opmode=switch
|
||||
switch.port.12.pvid=6
|
||||
switch.port.12.port-security=disabled
|
||||
switch.vlan.1.port.12.mode=exclude
|
||||
switch.vlan.2.port.12.mode=exclude
|
||||
switch.vlan.3.port.12.mode=exclude
|
||||
switch.vlan.4.port.12.mode=exclude
|
||||
switch.vlan.5.port.12.mode=exclude
|
||||
switch.vlan.6.port.12.mode=untagged
|
||||
switch.vlan.7.port.12.mode=exclude
|
||||
switch.vlan.8.port.12.mode=exclude
|
||||
switch.vlan.9.port.12.mode=exclude
|
||||
switch.vlan.10.port.12.mode=exclude
|
||||
switch.vlan.11.port.12.mode=exclude
|
||||
switch.vlan.12.port.12.mode=exclude
|
||||
switch.vlan.13.port.12.mode=exclude
|
||||
switch.port.13.name=13
|
||||
switch.port.13.lldpmed.opmode=enabled
|
||||
switch.port.13.lldpmed.topology_notify=disabled
|
||||
switch.port.13.stp.port_mode=enabled
|
||||
switch.port.13.keepalive=disabled
|
||||
switch.port.13.opmode=switch
|
||||
switch.port.13.pvid=8
|
||||
switch.port.13.port-security=disabled
|
||||
switch.vlan.1.port.13.mode=exclude
|
||||
switch.vlan.2.port.13.mode=exclude
|
||||
switch.vlan.3.port.13.mode=exclude
|
||||
switch.vlan.4.port.13.mode=exclude
|
||||
switch.vlan.5.port.13.mode=exclude
|
||||
switch.vlan.6.port.13.mode=exclude
|
||||
switch.vlan.7.port.13.mode=exclude
|
||||
switch.vlan.8.port.13.mode=untagged
|
||||
switch.vlan.9.port.13.mode=exclude
|
||||
switch.vlan.10.port.13.mode=exclude
|
||||
switch.vlan.11.port.13.mode=exclude
|
||||
switch.vlan.12.port.13.mode=exclude
|
||||
switch.vlan.13.port.13.mode=exclude
|
||||
switch.port.14.name=14
|
||||
switch.port.14.lldpmed.opmode=enabled
|
||||
switch.port.14.lldpmed.topology_notify=disabled
|
||||
switch.port.14.stp.port_mode=enabled
|
||||
switch.port.14.keepalive=disabled
|
||||
switch.port.14.opmode=switch
|
||||
switch.port.14.pvid=12
|
||||
switch.port.14.port-security=disabled
|
||||
switch.vlan.1.port.14.mode=exclude
|
||||
switch.vlan.2.port.14.mode=exclude
|
||||
switch.vlan.3.port.14.mode=exclude
|
||||
switch.vlan.4.port.14.mode=exclude
|
||||
switch.vlan.5.port.14.mode=exclude
|
||||
switch.vlan.6.port.14.mode=exclude
|
||||
switch.vlan.7.port.14.mode=exclude
|
||||
switch.vlan.8.port.14.mode=exclude
|
||||
switch.vlan.9.port.14.mode=exclude
|
||||
switch.vlan.10.port.14.mode=exclude
|
||||
switch.vlan.11.port.14.mode=exclude
|
||||
switch.vlan.12.port.14.mode=untagged
|
||||
switch.vlan.13.port.14.mode=exclude
|
||||
switch.port.15.name=15
|
||||
switch.port.15.lldpmed.opmode=enabled
|
||||
switch.port.15.lldpmed.topology_notify=disabled
|
||||
switch.port.15.stp.port_mode=enabled
|
||||
switch.port.15.keepalive=disabled
|
||||
switch.port.15.opmode=switch
|
||||
switch.port.15.pvid=6
|
||||
switch.port.15.port-security=disabled
|
||||
switch.vlan.1.port.15.mode=exclude
|
||||
switch.vlan.2.port.15.mode=exclude
|
||||
switch.vlan.3.port.15.mode=exclude
|
||||
switch.vlan.4.port.15.mode=exclude
|
||||
switch.vlan.5.port.15.mode=exclude
|
||||
switch.vlan.6.port.15.mode=untagged
|
||||
switch.vlan.7.port.15.mode=exclude
|
||||
switch.vlan.8.port.15.mode=exclude
|
||||
switch.vlan.9.port.15.mode=exclude
|
||||
switch.vlan.10.port.15.mode=exclude
|
||||
switch.vlan.11.port.15.mode=exclude
|
||||
switch.vlan.12.port.15.mode=exclude
|
||||
switch.vlan.13.port.15.mode=exclude
|
||||
switch.port.16.name=16
|
||||
switch.port.16.lldpmed.opmode=enabled
|
||||
switch.port.16.lldpmed.topology_notify=disabled
|
||||
switch.port.16.stp.port_mode=enabled
|
||||
switch.port.16.keepalive=disabled
|
||||
switch.port.16.opmode=switch
|
||||
switch.port.16.pvid=6
|
||||
switch.port.16.port-security=disabled
|
||||
switch.vlan.1.port.16.mode=exclude
|
||||
switch.vlan.2.port.16.mode=exclude
|
||||
switch.vlan.3.port.16.mode=exclude
|
||||
switch.vlan.4.port.16.mode=exclude
|
||||
switch.vlan.5.port.16.mode=exclude
|
||||
switch.vlan.6.port.16.mode=untagged
|
||||
switch.vlan.7.port.16.mode=exclude
|
||||
switch.vlan.8.port.16.mode=exclude
|
||||
switch.vlan.9.port.16.mode=exclude
|
||||
switch.vlan.10.port.16.mode=exclude
|
||||
switch.vlan.11.port.16.mode=exclude
|
||||
switch.vlan.12.port.16.mode=exclude
|
||||
switch.vlan.13.port.16.mode=exclude
|
||||
switch.port.17.name=17
|
||||
switch.port.17.lldpmed.opmode=enabled
|
||||
switch.port.17.lldpmed.topology_notify=disabled
|
||||
switch.port.17.stp.port_mode=enabled
|
||||
switch.port.17.keepalive=disabled
|
||||
switch.port.17.opmode=switch
|
||||
switch.port.17.port-security=disabled
|
||||
switch.port.18.name=18
|
||||
switch.port.18.lldpmed.opmode=enabled
|
||||
switch.port.18.lldpmed.topology_notify=disabled
|
||||
switch.port.18.stp.port_mode=enabled
|
||||
switch.port.18.keepalive=disabled
|
||||
switch.port.18.opmode=switch
|
||||
switch.port.18.port-security=disabled
|
||||
switch.port.19.name=19
|
||||
switch.port.19.lldpmed.opmode=enabled
|
||||
switch.port.19.lldpmed.topology_notify=disabled
|
||||
switch.port.19.stp.port_mode=enabled
|
||||
switch.port.19.keepalive=disabled
|
||||
switch.port.19.opmode=switch
|
||||
switch.port.19.port-security=disabled
|
||||
switch.port.20.name=20
|
||||
switch.port.20.lldpmed.opmode=enabled
|
||||
switch.port.20.lldpmed.topology_notify=disabled
|
||||
switch.port.20.stp.port_mode=enabled
|
||||
switch.port.20.keepalive=disabled
|
||||
switch.port.20.opmode=switch
|
||||
switch.port.20.port-security=disabled
|
||||
switch.port.21.name=21
|
||||
switch.port.21.lldpmed.opmode=enabled
|
||||
switch.port.21.lldpmed.topology_notify=disabled
|
||||
switch.port.21.stp.port_mode=enabled
|
||||
switch.port.21.keepalive=disabled
|
||||
switch.port.21.opmode=switch
|
||||
switch.port.21.port-security=disabled
|
||||
switch.port.22.name=22
|
||||
switch.port.22.lldpmed.opmode=enabled
|
||||
switch.port.22.lldpmed.topology_notify=disabled
|
||||
switch.port.22.stp.port_mode=enabled
|
||||
switch.port.22.keepalive=disabled
|
||||
switch.port.22.opmode=switch
|
||||
switch.port.22.port-security=disabled
|
||||
switch.port.23.name=23
|
||||
switch.port.23.lldpmed.opmode=enabled
|
||||
switch.port.23.lldpmed.topology_notify=disabled
|
||||
switch.port.23.stp.port_mode=enabled
|
||||
switch.port.23.keepalive=disabled
|
||||
switch.port.23.opmode=switch
|
||||
switch.port.23.port-security=disabled
|
||||
switch.port.24.name=24
|
||||
switch.port.24.lldpmed.opmode=enabled
|
||||
switch.port.24.lldpmed.topology_notify=disabled
|
||||
switch.port.24.stp.port_mode=enabled
|
||||
switch.port.24.keepalive=disabled
|
||||
switch.port.24.opmode=switch
|
||||
switch.port.24.port-security=disabled
|
||||
switch.port.25.name=SFP 1
|
||||
switch.port.25.lldpmed.opmode=enabled
|
||||
switch.port.25.lldpmed.topology_notify=disabled
|
||||
switch.port.25.stp.port_mode=enabled
|
||||
switch.port.25.keepalive=disabled
|
||||
switch.port.25.opmode=switch
|
||||
switch.port.25.port-security=disabled
|
||||
switch.port.26.name=SFP 2
|
||||
switch.port.26.lldpmed.opmode=enabled
|
||||
switch.port.26.lldpmed.topology_notify=disabled
|
||||
switch.port.26.stp.port_mode=enabled
|
||||
switch.port.26.keepalive=disabled
|
||||
switch.port.26.opmode=switch
|
||||
switch.port.26.port-security=disabled
|
||||
# syslog
|
||||
syslog.status=enabled
|
||||
syslog.level=7
|
||||
sshd.status=enabled
|
||||
sshd.auth.passwd=enabled
|
||||
sshd.1.status=enabled
|
||||
sshd.1.ifname=eth0
|
||||
# ntpclient
|
||||
ntpclient.status=enabled
|
||||
ntpclient.1.status=enabled
|
||||
ntpclient.1.server=0.pool.ntp.org
|
||||
ntpclient.2.status=enabled
|
||||
ntpclient.2.server=1.pool.ntp.org
|
||||
# misc
|
||||
@@ -0,0 +1,385 @@
|
||||
"""The controller client: which API, how it logs in, how its failures read.
|
||||
|
||||
The HTTP transport is replaced by a fake session that answers by method and path;
|
||||
no test opens a socket.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from napalm.base.exceptions import ConnectionException
|
||||
|
||||
from napalm_ubiquiti.client import (
|
||||
NotFound,
|
||||
RateLimited,
|
||||
SiteNotFound,
|
||||
UnifiClient,
|
||||
UnifiError,
|
||||
)
|
||||
|
||||
|
||||
class FakeResponse:
|
||||
def __init__(
|
||||
self, status: int, body: Any = None, headers: dict[str, str] | None = None
|
||||
) -> None:
|
||||
self.status_code = status
|
||||
self._body = body
|
||||
self.headers = headers or {}
|
||||
self.text = body if isinstance(body, str) else json.dumps(body)
|
||||
|
||||
def json(self) -> Any:
|
||||
if isinstance(self._body, str):
|
||||
raise ValueError("not json")
|
||||
return self._body
|
||||
|
||||
|
||||
class FakeSession:
|
||||
def __init__(self, answers: dict[tuple[str, str], Any]) -> None:
|
||||
self.answers = answers
|
||||
self.sent: list[dict[str, Any]] = []
|
||||
self.headers: dict[str, str] = {}
|
||||
self.cookies: dict[str, str] = {}
|
||||
self.verify: Any = True
|
||||
|
||||
def request(self, method: str, url: str, **kwargs: Any) -> FakeResponse:
|
||||
path = url.split("://", 1)[1].split("/", 1)[1]
|
||||
path = "/" + path
|
||||
self.sent.append({"method": method, "path": path, "headers": dict(self.headers), **kwargs})
|
||||
answer = self.answers.get((method, path))
|
||||
if answer is None:
|
||||
return FakeResponse(404, {"meta": {"rc": "error", "msg": "api.err.NotFound"}})
|
||||
if callable(answer):
|
||||
return answer(kwargs) # type: ignore[no-any-return]
|
||||
return answer # type: ignore[no-any-return]
|
||||
|
||||
|
||||
#: What ``GET /`` answers: UniFi OS serves its page, a standalone controller redirects.
|
||||
UNIFI_OS_HOME = {("GET", "/"): FakeResponse(200, "<html>UniFi OS</html>")}
|
||||
STANDALONE_HOME = {("GET", "/"): FakeResponse(302, "", {"Location": "/manage"})}
|
||||
|
||||
|
||||
def ok(data: Any) -> FakeResponse:
|
||||
return FakeResponse(200, {"meta": {"rc": "ok"}, "data": data})
|
||||
|
||||
|
||||
def _client(answers: dict[tuple[str, str], Any], **kwargs: Any) -> tuple[UnifiClient, FakeSession]:
|
||||
session = FakeSession(answers)
|
||||
client = UnifiClient("https://192.0.2.1", session=session, **kwargs)
|
||||
return client, session
|
||||
|
||||
|
||||
class TestApiKey:
|
||||
def test_the_key_goes_in_a_header_and_no_login_happens(self) -> None:
|
||||
client, session = _client(
|
||||
{("GET", "/proxy/network/api/s/default/stat/device"): ok([{"mac": "x"}])}, api_key="k3y"
|
||||
)
|
||||
|
||||
client.login()
|
||||
records = client.classic_get("default", "stat/device")
|
||||
|
||||
assert records == [{"mac": "x"}]
|
||||
assert session.headers["X-API-KEY"] == "k3y"
|
||||
assert [s["path"] for s in session.sent] == ["/proxy/network/api/s/default/stat/device"]
|
||||
|
||||
def test_redirects_are_never_followed(self) -> None:
|
||||
client, session = _client(
|
||||
{
|
||||
("GET", "/proxy/network/integration/v1/info"): FakeResponse(
|
||||
302, "", {"Location": "https://evil/"}
|
||||
)
|
||||
},
|
||||
api_key="k",
|
||||
)
|
||||
|
||||
with pytest.raises(UnifiError, match="redirect"):
|
||||
client.integration_get("info")
|
||||
|
||||
assert session.sent[0]["allow_redirects"] is False
|
||||
|
||||
def test_a_refused_key(self) -> None:
|
||||
client, _ = _client(
|
||||
{
|
||||
("GET", "/proxy/network/integration/v1/info"): FakeResponse(
|
||||
401, {"error": "unauthorized"}
|
||||
)
|
||||
},
|
||||
api_key="k",
|
||||
)
|
||||
|
||||
with pytest.raises(ConnectionException, match="API key"):
|
||||
client.integration_get("info")
|
||||
|
||||
|
||||
class TestLogin:
|
||||
def test_a_unifi_os_console_logs_in_and_keeps_the_csrf_token(self) -> None:
|
||||
login = FakeResponse(200, {"username": "admin"}, {"X-CSRF-Token": "csrf-1"})
|
||||
client, session = _client(
|
||||
{
|
||||
**UNIFI_OS_HOME,
|
||||
("POST", "/api/auth/login"): login,
|
||||
("PUT", "/proxy/network/api/s/default/rest/device/abc"): ok([]),
|
||||
},
|
||||
username="admin",
|
||||
password="pw",
|
||||
)
|
||||
|
||||
client.login()
|
||||
client.classic_write("PUT", "default", "rest/device/abc", {"port_overrides": []})
|
||||
|
||||
assert client.unifi_os is True
|
||||
assert session.sent[1]["json"] == {"username": "admin", "password": "pw", "remember": True}
|
||||
assert session.sent[2]["headers"]["X-CSRF-Token"] == "csrf-1"
|
||||
|
||||
def test_a_standalone_controller_is_told_apart_by_its_redirect(self) -> None:
|
||||
client, session = _client(
|
||||
{
|
||||
**STANDALONE_HOME,
|
||||
("POST", "/api/login"): ok([]),
|
||||
("GET", "/api/s/default/stat/device"): ok([]),
|
||||
},
|
||||
username="admin",
|
||||
password="pw",
|
||||
)
|
||||
|
||||
client.login()
|
||||
client.classic_get("default", "stat/device")
|
||||
|
||||
assert client.unifi_os is False
|
||||
assert [s["path"] for s in session.sent] == [
|
||||
"/",
|
||||
"/api/login",
|
||||
"/api/s/default/stat/device",
|
||||
]
|
||||
|
||||
def test_a_standalone_controller_sends_its_csrf_cookie_back_as_a_header(self) -> None:
|
||||
client, session = _client(
|
||||
{
|
||||
**STANDALONE_HOME,
|
||||
("POST", "/api/login"): ok([]),
|
||||
("PUT", "/api/s/default/rest/device/abc"): ok([]),
|
||||
},
|
||||
username="admin",
|
||||
password="pw",
|
||||
)
|
||||
session.cookies["csrf_token"] = "csrf-2"
|
||||
|
||||
client.login()
|
||||
client.classic_write("PUT", "default", "rest/device/abc", {})
|
||||
|
||||
assert session.sent[-1]["headers"]["X-CSRF-Token"] == "csrf-2"
|
||||
|
||||
def test_a_cloud_account_with_mfa_is_refused_with_the_way_in(self) -> None:
|
||||
client, _ = _client(
|
||||
{
|
||||
**UNIFI_OS_HOME,
|
||||
("POST", "/api/auth/login"): FakeResponse(499, {"code": "MFA_AUTH_REQUIRED"}),
|
||||
},
|
||||
username="me@example.com",
|
||||
password="pw",
|
||||
)
|
||||
|
||||
with pytest.raises(ConnectionException, match="local admin|API key"):
|
||||
client.login()
|
||||
|
||||
def test_wrong_credentials(self) -> None:
|
||||
client, _ = _client(
|
||||
{
|
||||
**UNIFI_OS_HOME,
|
||||
("POST", "/api/auth/login"): FakeResponse(
|
||||
401, {"code": "AUTHENTICATION_FAILED_INVALID_CREDENTIALS"}
|
||||
),
|
||||
},
|
||||
username="a",
|
||||
password="b",
|
||||
)
|
||||
|
||||
with pytest.raises(ConnectionException, match="refused"):
|
||||
client.login()
|
||||
|
||||
def test_the_login_rate_limit_backs_off_instead_of_retrying(self) -> None:
|
||||
client, session = _client(
|
||||
{
|
||||
**UNIFI_OS_HOME,
|
||||
("POST", "/api/auth/login"): FakeResponse(
|
||||
429, {"code": "AUTHENTICATION_FAILED_LIMIT_REACHED"}, {"Retry-After": "300"}
|
||||
),
|
||||
},
|
||||
username="a",
|
||||
password="b",
|
||||
)
|
||||
|
||||
with pytest.raises(RateLimited) as caught:
|
||||
client.login()
|
||||
|
||||
assert caught.value.retry_after == 300
|
||||
assert [s["method"] for s in session.sent] == ["GET", "POST"]
|
||||
|
||||
def test_something_else_at_the_address(self) -> None:
|
||||
client, _ = _client(
|
||||
{("GET", "/"): FakeResponse(404, "not here")}, username="a", password="b"
|
||||
)
|
||||
|
||||
with pytest.raises(ConnectionException, match="UniFi"):
|
||||
client.login()
|
||||
|
||||
def test_a_login_that_redirects_is_not_followed(self) -> None:
|
||||
client, _ = _client(
|
||||
{**STANDALONE_HOME, ("POST", "/api/login"): FakeResponse(302, "", {"Location": "/x"})},
|
||||
username="a",
|
||||
password="b",
|
||||
)
|
||||
|
||||
with pytest.raises(ConnectionException, match="redirect"):
|
||||
client.login()
|
||||
|
||||
def test_neither_key_nor_login(self) -> None:
|
||||
client, _ = _client({})
|
||||
|
||||
with pytest.raises(ConnectionException, match="API key or"):
|
||||
client.login()
|
||||
|
||||
|
||||
class TestClassic:
|
||||
def test_a_wrong_site_is_not_an_empty_controller(self) -> None:
|
||||
answer = FakeResponse(
|
||||
401, {"meta": {"rc": "error", "msg": "api.err.NoSiteContext"}, "data": []}
|
||||
)
|
||||
client, _ = _client(
|
||||
{("GET", "/proxy/network/api/s/nosuch/stat/device"): answer}, api_key="k"
|
||||
)
|
||||
|
||||
with pytest.raises(SiteNotFound, match="nosuch"):
|
||||
client.classic_get("nosuch", "stat/device")
|
||||
|
||||
def test_an_error_answer_raises(self) -> None:
|
||||
answer = FakeResponse(400, {"meta": {"rc": "error", "msg": "api.err.Invalid"}, "data": []})
|
||||
client, _ = _client(
|
||||
{("GET", "/proxy/network/api/s/default/rest/portconf"): answer}, api_key="k"
|
||||
)
|
||||
|
||||
with pytest.raises(UnifiError, match="api.err.Invalid"):
|
||||
client.classic_get("default", "rest/portconf")
|
||||
|
||||
def test_an_error_inside_a_200_answer_raises(self) -> None:
|
||||
answer = FakeResponse(200, {"meta": {"rc": "error", "msg": "api.err.InvalidObject"}})
|
||||
client, _ = _client({("GET", "/proxy/network/api/s/default/rest/x"): answer}, api_key="k")
|
||||
|
||||
with pytest.raises(UnifiError, match="InvalidObject"):
|
||||
client.classic_get("default", "rest/x")
|
||||
|
||||
def test_a_wrong_site_inside_a_200_answer(self) -> None:
|
||||
answer = FakeResponse(200, {"meta": {"rc": "error", "msg": "api.err.NoSiteContext"}})
|
||||
client, _ = _client({("GET", "/proxy/network/api/s/x/stat/device"): answer}, api_key="k")
|
||||
|
||||
with pytest.raises(SiteNotFound):
|
||||
client.classic_get("x", "stat/device")
|
||||
|
||||
def test_an_answer_that_is_no_object(self) -> None:
|
||||
answer = FakeResponse(500, ["boom"])
|
||||
client, _ = _client({("GET", "/proxy/network/api/s/default/rest/x"): answer}, api_key="k")
|
||||
|
||||
with pytest.raises(UnifiError, match="boom"):
|
||||
client.classic_get("default", "rest/x")
|
||||
|
||||
def test_a_missing_endpoint_is_not_found(self) -> None:
|
||||
client, _ = _client({}, api_key="k")
|
||||
|
||||
with pytest.raises(NotFound):
|
||||
client.classic_get("default", "rest/nothing")
|
||||
|
||||
def test_sites_come_from_self_sites(self) -> None:
|
||||
client, _ = _client(
|
||||
{
|
||||
("GET", "/proxy/network/api/self/sites"): ok(
|
||||
[{"name": "default", "desc": "Default"}]
|
||||
)
|
||||
},
|
||||
api_key="k",
|
||||
)
|
||||
|
||||
assert client.classic_sites() == [{"name": "default", "desc": "Default"}]
|
||||
|
||||
def test_a_server_error_names_the_status(self) -> None:
|
||||
client, _ = _client(
|
||||
{("GET", "/proxy/network/api/s/default/stat/device"): FakeResponse(502, "Bad Gateway")},
|
||||
api_key="k",
|
||||
)
|
||||
|
||||
with pytest.raises(UnifiError, match="502"):
|
||||
client.classic_get("default", "stat/device")
|
||||
|
||||
|
||||
class TestIntegration:
|
||||
def test_pages_are_followed_to_the_total(self) -> None:
|
||||
def page(kwargs: dict[str, Any]) -> FakeResponse:
|
||||
offset = kwargs["params"]["offset"]
|
||||
data = [{"n": offset + i} for i in range(2 if offset < 4 else 1)]
|
||||
return FakeResponse(
|
||||
200,
|
||||
{"offset": offset, "limit": 2, "count": len(data), "totalCount": 5, "data": data},
|
||||
)
|
||||
|
||||
client, session = _client(
|
||||
{("GET", "/proxy/network/integration/v1/sites"): page}, api_key="k"
|
||||
)
|
||||
|
||||
items = client.integration_list("sites")
|
||||
|
||||
assert [i["n"] for i in items] == [0, 1, 2, 3, 4]
|
||||
assert [s["params"]["offset"] for s in session.sent] == [0, 2, 4]
|
||||
assert session.sent[0]["params"]["limit"] == 200
|
||||
|
||||
def test_an_empty_page_stops_the_walk(self) -> None:
|
||||
answer = FakeResponse(
|
||||
200, {"offset": 0, "limit": 200, "count": 0, "totalCount": 9, "data": []}
|
||||
)
|
||||
client, session = _client(
|
||||
{("GET", "/proxy/network/integration/v1/sites"): answer}, api_key="k"
|
||||
)
|
||||
|
||||
assert client.integration_list("sites") == []
|
||||
assert len(session.sent) == 1
|
||||
|
||||
def test_the_application_version(self) -> None:
|
||||
client, _ = _client(
|
||||
{
|
||||
("GET", "/proxy/network/integration/v1/info"): FakeResponse(
|
||||
200, {"applicationVersion": "10.6.106"}
|
||||
)
|
||||
},
|
||||
api_key="k",
|
||||
)
|
||||
|
||||
assert client.application_version() == (10, 6, 106)
|
||||
|
||||
def test_no_integration_api_on_a_standalone_controller(self) -> None:
|
||||
client, _ = _client(
|
||||
{**STANDALONE_HOME, ("POST", "/api/login"): ok([])}, username="a", password="b"
|
||||
)
|
||||
client.login()
|
||||
|
||||
with pytest.raises(NotFound):
|
||||
client.integration_get("info")
|
||||
|
||||
def test_an_endpoint_older_controllers_lack(self) -> None:
|
||||
client, _ = _client({}, api_key="k")
|
||||
|
||||
with pytest.raises(NotFound):
|
||||
client.integration_list("sites/x/networks")
|
||||
|
||||
|
||||
class TestTransportErrors:
|
||||
def test_an_unreachable_controller(self) -> None:
|
||||
class Down(FakeSession):
|
||||
def request(self, method: str, url: str, **kwargs: Any) -> FakeResponse:
|
||||
import requests
|
||||
|
||||
raise requests.ConnectionError("refused")
|
||||
|
||||
client = UnifiClient("https://192.0.2.1", session=Down({}), api_key="k")
|
||||
|
||||
with pytest.raises(ConnectionException, match="192.0.2.1"):
|
||||
client.integration_get("info")
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Reaching a controller: its address, the credentials netOrk hands over, its certificate."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from napalm.base.exceptions import ConnectionException
|
||||
from napalm_device_types.tls_certificates import CertificateCheck, TlsCertificateMismatch
|
||||
|
||||
from napalm_ubiquiti import connection
|
||||
from napalm_ubiquiti.connection import (
|
||||
ControllerLogin,
|
||||
controller_login,
|
||||
host_and_port,
|
||||
open_controller,
|
||||
)
|
||||
|
||||
|
||||
class TestAddress:
|
||||
def test_a_bare_host_is_https_on_443(self) -> None:
|
||||
assert host_and_port("https://unifi.example") == ("unifi.example", 443)
|
||||
|
||||
def test_a_standalone_controller_on_8443(self) -> None:
|
||||
assert host_and_port("https://192.0.2.5:8443") == ("192.0.2.5", 8443)
|
||||
|
||||
def test_an_ipv6_address(self) -> None:
|
||||
assert host_and_port("https://[2001:db8::1]:8443") == ("2001:db8::1", 8443)
|
||||
|
||||
|
||||
class TestLogin:
|
||||
def test_the_secret_of_an_api_token_profile_is_the_key(self) -> None:
|
||||
login = controller_login("", "", {"token_name": "netork", "token_value": "s3cret"})
|
||||
|
||||
assert login == ControllerLogin(api_key="s3cret", username="", password="")
|
||||
|
||||
def test_api_secret_counts_as_the_key_too(self) -> None:
|
||||
login = controller_login("", "", {"api_key": "netork", "api_secret": "s3cret"})
|
||||
|
||||
assert login.api_key == "s3cret"
|
||||
|
||||
def test_without_a_key_the_login_is_used(self) -> None:
|
||||
assert controller_login("admin", "pw", {}) == ControllerLogin("", "admin", "pw")
|
||||
|
||||
def test_a_separate_controller_login_wins(self) -> None:
|
||||
args = {"controller_username": "netork", "controller_password": "pw2"}
|
||||
|
||||
assert controller_login("ubnt", "ssh-pw", args) == ControllerLogin("", "netork", "pw2")
|
||||
|
||||
|
||||
class FakeSession:
|
||||
def __init__(self) -> None:
|
||||
self.headers: dict[str, str] = {}
|
||||
self.verify: Any = True
|
||||
self.mounted: list[str] = []
|
||||
|
||||
def mount(self, prefix: str, adapter: Any) -> None:
|
||||
self.mounted.append(prefix)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def handshake(monkeypatch: pytest.MonkeyPatch) -> list[CertificateCheck]:
|
||||
"""The TLS handshake replaced: every server presents the certificate ``b"der"``."""
|
||||
checks: list[CertificateCheck] = []
|
||||
|
||||
def verify_server(self: CertificateCheck, timeout: float, **_: Any) -> Any:
|
||||
checks.append(self)
|
||||
return self.verify(b"der")
|
||||
|
||||
monkeypatch.setattr(CertificateCheck, "verify_server", verify_server)
|
||||
return checks
|
||||
|
||||
|
||||
class TestOpen:
|
||||
def test_the_certificate_is_checked_pinned_and_reported(
|
||||
self, handshake: list[CertificateCheck]
|
||||
) -> None:
|
||||
seen: list[dict[str, Any]] = []
|
||||
session = FakeSession()
|
||||
|
||||
client = open_controller(
|
||||
"https://192.0.2.1",
|
||||
ControllerLogin("k3y", "", ""),
|
||||
{"tls_certificate_observer": seen.append},
|
||||
timeout=5,
|
||||
session=session,
|
||||
)
|
||||
|
||||
assert (handshake[0].host, handshake[0].port) == ("192.0.2.1", 443)
|
||||
assert session.mounted == ["https://"]
|
||||
assert session.verify is False
|
||||
assert seen[0]["accepted"] is True
|
||||
assert client.unifi_os is True
|
||||
|
||||
def test_a_changed_certificate_is_refused_before_the_login(
|
||||
self, handshake: list[CertificateCheck]
|
||||
) -> None:
|
||||
args = {"tls_fingerprints": {"443": "AA" * 32}}
|
||||
|
||||
with pytest.raises(TlsCertificateMismatch):
|
||||
open_controller(
|
||||
"https://192.0.2.1", ControllerLogin("", "a", "b"), args, 5, FakeSession()
|
||||
)
|
||||
|
||||
def test_ca_verification_on_request(self, handshake: list[CertificateCheck]) -> None:
|
||||
session = FakeSession()
|
||||
|
||||
open_controller(
|
||||
"https://192.0.2.1", ControllerLogin("k", "", ""), {"ssl_verify": True}, 5, session
|
||||
)
|
||||
|
||||
assert session.verify is True
|
||||
|
||||
def test_plain_http_is_refused(self) -> None:
|
||||
with pytest.raises(ConnectionException, match="https"):
|
||||
open_controller("http://192.0.2.1", ControllerLogin("k", "", ""), {}, 5, FakeSession())
|
||||
|
||||
def test_the_login_runs_on_the_pinned_session(
|
||||
self, handshake: list[CertificateCheck], monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
logins: list[Any] = []
|
||||
monkeypatch.setattr(
|
||||
connection.UnifiClient, "login", lambda self: logins.append(self.session)
|
||||
)
|
||||
session = FakeSession()
|
||||
|
||||
open_controller("https://192.0.2.1", ControllerLogin("", "a", "b"), {}, 5, session)
|
||||
|
||||
assert logins == [session]
|
||||
@@ -0,0 +1,267 @@
|
||||
"""What a UniFi switch or access point driver does with its arguments and its source.
|
||||
|
||||
The controller and the SSH shell are replaced at the seams ``open_controller`` and
|
||||
``SshShell``; the record comes from the fixtures.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from conftest import load
|
||||
from napalm.base.exceptions import ConnectionException
|
||||
|
||||
from napalm_ubiquiti import device
|
||||
from napalm_ubiquiti.client import UnifiError
|
||||
from napalm_ubiquiti.device import UnifiDevice
|
||||
from napalm_ubiquiti.sources import DUMP_COMMAND
|
||||
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, data: dict[str, list[Any]]) -> None:
|
||||
self.data = data
|
||||
self.asked: list[tuple[str, str]] = []
|
||||
self.session = FakeSession()
|
||||
|
||||
def classic_get(self, site: str, endpoint: str) -> list[Any]:
|
||||
self.asked.append((site, endpoint))
|
||||
return self.data.get(endpoint, [])
|
||||
|
||||
|
||||
class FakeSession:
|
||||
closed = False
|
||||
|
||||
def close(self) -> None:
|
||||
self.closed = True
|
||||
|
||||
|
||||
class FakeShell:
|
||||
def __init__(self, host: str, **kwargs: Any) -> None:
|
||||
self.host = host
|
||||
self.kwargs = kwargs
|
||||
self.answers: dict[str, str] = {}
|
||||
self.opened = False
|
||||
self.closed = False
|
||||
|
||||
def open(self) -> None:
|
||||
self.opened = True
|
||||
|
||||
def run(self, command: str) -> str:
|
||||
return self.answers[command]
|
||||
|
||||
def close(self) -> None:
|
||||
self.closed = True
|
||||
|
||||
|
||||
class Driver(UnifiDevice):
|
||||
"""The mixin alone, as a concrete driver puts it before its role base."""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def controller(monkeypatch: pytest.MonkeyPatch, us16: dict[str, Any]) -> dict[str, Any]:
|
||||
opened: dict[str, Any] = {}
|
||||
mac = us16["mac"]
|
||||
|
||||
def fake_open(url: str, login: Any, args: Any, timeout: float) -> FakeClient:
|
||||
opened.update(url=url, login=login, timeout=timeout)
|
||||
opened["client"] = FakeClient({f"stat/device/{mac}": [us16], "stat/device": [us16]})
|
||||
return opened["client"]
|
||||
|
||||
monkeypatch.setattr(device, "open_controller", fake_open)
|
||||
return opened
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def shells(monkeypatch: pytest.MonkeyPatch, us24_dump: dict[str, Any]) -> list[FakeShell]:
|
||||
made: list[FakeShell] = []
|
||||
|
||||
def factory(host: str, **kwargs: Any) -> FakeShell:
|
||||
shell = FakeShell(host, **kwargs)
|
||||
shell.answers[DUMP_COMMAND] = json.dumps(us24_dump)
|
||||
made.append(shell)
|
||||
return shell
|
||||
|
||||
monkeypatch.setattr(device, "SshShell", factory)
|
||||
return made
|
||||
|
||||
|
||||
class TestTransport:
|
||||
def test_a_controller_url_means_the_controller(
|
||||
self, controller: dict[str, Any], us16: dict[str, Any]
|
||||
) -> None:
|
||||
args = {"controller_url": "https://192.0.2.1", "token_value": "k", "mac": us16["mac"]}
|
||||
driver = Driver("192.0.2.20", "", "", optional_args=args)
|
||||
|
||||
driver.open()
|
||||
|
||||
assert controller["url"] == "https://192.0.2.1"
|
||||
assert controller["login"].api_key == "k"
|
||||
assert driver.get_facts()["model"] == "US16P150"
|
||||
|
||||
def test_without_a_mac_the_device_is_found_by_its_address(
|
||||
self, controller: dict[str, Any], us16: dict[str, Any]
|
||||
) -> None:
|
||||
args = {"controller_url": "https://192.0.2.1", "token_value": "k"}
|
||||
driver = Driver(us16["ip"], "", "", optional_args=args)
|
||||
|
||||
driver.open()
|
||||
|
||||
assert driver.get_facts()["serial_number"] == us16["serial"].upper()
|
||||
assert controller["client"].asked == [("default", "stat/device")]
|
||||
|
||||
def test_an_address_the_controller_does_not_know(self, controller: dict[str, Any]) -> None:
|
||||
args = {"controller_url": "https://192.0.2.1", "token_value": "k"}
|
||||
|
||||
with pytest.raises(UnifiError, match="192.0.2.99"):
|
||||
Driver("192.0.2.99", "", "", optional_args=args).open()
|
||||
|
||||
def test_another_site(self, controller: dict[str, Any], us16: dict[str, Any]) -> None:
|
||||
args = {
|
||||
"controller_url": "https://c",
|
||||
"token_value": "k",
|
||||
"site": "branch",
|
||||
"mac": us16["mac"],
|
||||
}
|
||||
driver = Driver("192.0.2.20", "", "", optional_args=args)
|
||||
driver.open()
|
||||
driver.get_facts()
|
||||
|
||||
assert controller["client"].asked == [("branch", f"stat/device/{us16['mac']}")]
|
||||
|
||||
def test_without_a_controller_the_device_is_read_over_ssh(
|
||||
self, shells: list[FakeShell]
|
||||
) -> None:
|
||||
driver = Driver("192.0.2.30", "ubnt", "pw")
|
||||
|
||||
driver.open()
|
||||
|
||||
assert shells[0].host == "192.0.2.30"
|
||||
assert shells[0].kwargs["username"] == "ubnt"
|
||||
assert shells[0].kwargs["password"] == "pw"
|
||||
assert shells[0].kwargs["port"] == 22
|
||||
assert driver.get_facts()["hostname"] == "usw-1"
|
||||
|
||||
def test_a_separate_ssh_profile_wins(self, shells: list[FakeShell]) -> None:
|
||||
args = {"ssh_username": "admin", "ssh_password": "pw2", "ssh_port": 2222}
|
||||
|
||||
Driver("192.0.2.30", "ubnt", "pw", optional_args=args).open()
|
||||
|
||||
assert shells[0].kwargs["username"] == "admin"
|
||||
assert shells[0].kwargs["password"] == "pw2"
|
||||
assert shells[0].kwargs["port"] == 2222
|
||||
|
||||
def test_an_ssh_key_from_a_file(self, shells: list[FakeShell], tmp_path: pathlib.Path) -> None:
|
||||
key = tmp_path / "id"
|
||||
key.write_text("KEY")
|
||||
|
||||
Driver("192.0.2.30", "ubnt", "", optional_args={"key_file": str(key)}).open()
|
||||
|
||||
assert shells[0].kwargs["private_key"] == "KEY"
|
||||
|
||||
def test_an_ssh_key_as_text(self, shells: list[FakeShell]) -> None:
|
||||
Driver("h", "u", "", optional_args={"ssh_private_key_str": "KEY"}).open()
|
||||
|
||||
assert shells[0].kwargs["private_key"] == "KEY"
|
||||
|
||||
def test_an_unknown_transport(self) -> None:
|
||||
with pytest.raises(ConnectionException, match="transport"):
|
||||
Driver("h", "u", "p", optional_args={"transport": "telnet"})
|
||||
|
||||
def test_the_controller_transport_needs_its_url(self) -> None:
|
||||
with pytest.raises(ConnectionException, match="controller_url"):
|
||||
Driver("h", "u", "p", optional_args={"transport": "controller"})
|
||||
|
||||
def test_a_controller_url_without_scheme_is_https(
|
||||
self, controller: dict[str, Any], us16: dict[str, Any]
|
||||
) -> None:
|
||||
Driver(
|
||||
"h", "", "", optional_args={"controller_url": "unifi.lan:8443", "mac": us16["mac"]}
|
||||
).open()
|
||||
|
||||
assert controller["url"] == "https://unifi.lan:8443"
|
||||
|
||||
|
||||
class TestSession:
|
||||
def test_open_reads_the_device_once(self, shells: list[FakeShell]) -> None:
|
||||
driver = Driver("h", "u", "p")
|
||||
driver.open()
|
||||
driver.get_facts()
|
||||
driver.get_interfaces()
|
||||
|
||||
assert driver.is_alive() == {"is_alive": True}
|
||||
|
||||
def test_a_device_that_cannot_be_read_fails_open_and_closes(
|
||||
self, shells: list[FakeShell], monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setattr(FakeShell, "run", lambda self, command: "not json")
|
||||
driver = Driver("h", "u", "p")
|
||||
|
||||
with pytest.raises(Exception, match="mca-dump"):
|
||||
driver.open()
|
||||
|
||||
assert shells[0].closed is True
|
||||
assert driver.is_alive() == {"is_alive": False}
|
||||
|
||||
def test_getters_before_open(self) -> None:
|
||||
with pytest.raises(ConnectionException, match="not open"):
|
||||
Driver("h", "u", "p").get_facts()
|
||||
|
||||
def test_close_closes_the_shell(self, shells: list[FakeShell]) -> None:
|
||||
driver = Driver("h", "u", "p")
|
||||
driver.open()
|
||||
|
||||
driver.close()
|
||||
|
||||
assert shells[0].closed is True
|
||||
assert driver.is_alive() == {"is_alive": False}
|
||||
|
||||
def test_close_closes_the_controller_session(
|
||||
self, controller: dict[str, Any], us16: dict[str, Any]
|
||||
) -> None:
|
||||
driver = Driver(
|
||||
"h", "", "", optional_args={"controller_url": "https://c", "mac": us16["mac"]}
|
||||
)
|
||||
driver.open()
|
||||
assert driver.is_alive() == {"is_alive": True}
|
||||
|
||||
driver.close()
|
||||
|
||||
assert controller["client"].session.closed is True
|
||||
|
||||
def test_close_without_open(self) -> None:
|
||||
Driver("h", "u", "p").close()
|
||||
|
||||
|
||||
class TestReadings:
|
||||
@pytest.fixture
|
||||
def opened(self, shells: list[FakeShell]) -> Driver:
|
||||
driver = Driver("192.0.2.30", "ubnt", "pw")
|
||||
driver.open()
|
||||
return driver
|
||||
|
||||
def test_interfaces_and_addresses(self, opened: Driver) -> None:
|
||||
assert "Port 1" in opened.get_interfaces()
|
||||
assert "Management" in opened.get_interfaces_ip()
|
||||
|
||||
def test_lldp_both_ways(self, opened: Driver) -> None:
|
||||
neighbours = opened.get_lldp_neighbors()
|
||||
detail = opened.get_lldp_neighbors_detail()
|
||||
|
||||
assert neighbours
|
||||
assert set(detail) == set(neighbours)
|
||||
|
||||
def test_lldp_for_one_port(self, opened: Driver) -> None:
|
||||
port = next(iter(opened.get_lldp_neighbors()))
|
||||
|
||||
assert set(opened.get_lldp_neighbors_detail(port)) == {port}
|
||||
|
||||
def test_mac_table(self, opened: Driver) -> None:
|
||||
assert isinstance(opened.get_mac_address_table(), list)
|
||||
|
||||
|
||||
def test_the_fixture_record_has_lldp() -> None:
|
||||
"""The SSH fixture carries LLDP neighbours, or the LLDP tests above prove nothing."""
|
||||
assert load("ssh/us24-7.1.26-mca-dump.json").get("lldp_table")
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Each NAPALM entry point names a driver of that name."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import pathlib
|
||||
import tomllib
|
||||
|
||||
PYPROJECT = pathlib.Path(__file__).parents[1] / "pyproject.toml"
|
||||
|
||||
|
||||
def test_every_entry_point_loads_the_driver_it_names() -> None:
|
||||
points = tomllib.loads(PYPROJECT.read_text())["project"]["entry-points"]["napalm.drivers"]
|
||||
|
||||
for name, target in points.items():
|
||||
module, attribute = target.split(":")
|
||||
driver = getattr(importlib.import_module(module), attribute)
|
||||
assert driver.DRIVER_NAME == name
|
||||
|
||||
assert set(points) == {"unifi_switch", "unifi_ap", "unifi_network"}
|
||||
@@ -0,0 +1,209 @@
|
||||
"""The UniFi Network controller as a device: what it is, and the devices it manages."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from conftest import load
|
||||
from napalm.base.exceptions import ConnectionException
|
||||
from napalm_device_types import NetworkControllerDriver
|
||||
from napalm_device_types.roles import primary_role_of
|
||||
|
||||
from napalm_ubiquiti import UnifiNetworkDriver, controller
|
||||
from napalm_ubiquiti.client import NotFound
|
||||
|
||||
SITE_ID = "88f7af54-98f8-306a-a1c7-c9349722b1f6"
|
||||
|
||||
|
||||
class FakeController:
|
||||
"""Integration API and classic API, as far as the recorded answers reach."""
|
||||
|
||||
def __init__(self, integration: dict[str, Any], classic: dict[tuple[str, str], list[Any]]):
|
||||
self.integration = integration
|
||||
self.classic = classic
|
||||
self.sites = [{"name": site} for site, _ in classic]
|
||||
self.session = type(
|
||||
"S", (), {"closed": False, "close": lambda s: setattr(s, "closed", True)}
|
||||
)()
|
||||
|
||||
def integration_get(self, endpoint: str, params: Any = None) -> Any:
|
||||
if endpoint not in self.integration:
|
||||
raise NotFound(endpoint)
|
||||
return self.integration[endpoint]
|
||||
|
||||
def integration_list(self, endpoint: str) -> list[Any]:
|
||||
return list(self.integration_get(endpoint)["data"])
|
||||
|
||||
def classic_sites(self) -> list[Any]:
|
||||
return [dict(s) for s in {s["name"]: s for s in self.sites}.values()]
|
||||
|
||||
def classic_get(self, site: str, endpoint: str) -> list[Any]:
|
||||
return self.classic.get((site, endpoint), [])
|
||||
|
||||
|
||||
def _integration(version: str = "10.6.106", pending: bool = True) -> dict[str, Any]:
|
||||
answers = {
|
||||
"info": {"applicationVersion": version},
|
||||
"sites": load("integration/v10.6.106-sites.json"),
|
||||
f"sites/{SITE_ID}/devices": load("integration/v10.6.106-devices.json"),
|
||||
}
|
||||
if pending:
|
||||
answers["pending-devices"] = load("integration/v10.6.106-pending-devices.json")
|
||||
return answers
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def opened(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:
|
||||
seen: dict[str, Any] = {}
|
||||
|
||||
def fake_open(url: str, login: Any, args: Any, timeout: float) -> FakeController:
|
||||
seen.update(url=url, login=login)
|
||||
return seen["controller"] # type: ignore[no-any-return]
|
||||
|
||||
monkeypatch.setattr(controller, "open_controller", fake_open)
|
||||
return seen
|
||||
|
||||
|
||||
def _driver(seen: dict[str, Any], fake: FakeController, **args: Any) -> UnifiNetworkDriver:
|
||||
seen["controller"] = fake
|
||||
driver = UnifiNetworkDriver("192.0.2.1", "", "", optional_args={"token_value": "k", **args})
|
||||
driver.open()
|
||||
return driver
|
||||
|
||||
|
||||
def test_its_role() -> None:
|
||||
assert issubclass(UnifiNetworkDriver, NetworkControllerDriver)
|
||||
assert primary_role_of(UnifiNetworkDriver) == "network_controller"
|
||||
assert UnifiNetworkDriver.DRIVER_NAME == "unifi_network"
|
||||
assert UnifiNetworkDriver.USES_SSH is False
|
||||
|
||||
|
||||
class TestConnection:
|
||||
def test_unifi_os_on_443(self, opened: dict[str, Any]) -> None:
|
||||
_driver(opened, FakeController(_integration(), {}))
|
||||
|
||||
assert opened["url"] == "https://192.0.2.1:443"
|
||||
assert opened["login"].api_key == "k"
|
||||
|
||||
def test_a_standalone_controller_on_8443(self, opened: dict[str, Any]) -> None:
|
||||
_driver(opened, FakeController({}, {}), port=8443)
|
||||
|
||||
assert opened["url"] == "https://192.0.2.1:8443"
|
||||
|
||||
def test_an_ipv6_controller(self, opened: dict[str, Any]) -> None:
|
||||
opened["controller"] = FakeController({}, {})
|
||||
UnifiNetworkDriver("2001:db8::1", "a", "b").open()
|
||||
|
||||
assert opened["url"] == "https://[2001:db8::1]:443"
|
||||
|
||||
def test_close(self, opened: dict[str, Any]) -> None:
|
||||
fake = FakeController({}, {})
|
||||
driver = _driver(opened, fake)
|
||||
assert driver.is_alive() == {"is_alive": True}
|
||||
|
||||
driver.close()
|
||||
|
||||
assert fake.session.closed is True
|
||||
assert driver.is_alive() == {"is_alive": False}
|
||||
|
||||
def test_reading_before_open(self) -> None:
|
||||
with pytest.raises(ConnectionException, match="not open"):
|
||||
UnifiNetworkDriver("h", "u", "p").get_managed_devices()
|
||||
|
||||
|
||||
class TestFacts:
|
||||
def test_the_application_version_from_the_integration_api(self, opened: dict[str, Any]) -> None:
|
||||
facts = _driver(opened, FakeController(_integration(), {})).get_facts()
|
||||
|
||||
assert facts["vendor"] == "Ubiquiti"
|
||||
assert facts["model"] == "UniFi Network"
|
||||
assert facts["os_version"] == "10.6.106"
|
||||
assert facts["hostname"] == "192.0.2.1"
|
||||
assert facts["interface_list"] == []
|
||||
|
||||
def test_a_standalone_controller_reports_its_version_in_sysinfo(
|
||||
self, opened: dict[str, Any]
|
||||
) -> None:
|
||||
fake = FakeController({}, {("default", "stat/sysinfo"): [{"version": "8.0.24"}]})
|
||||
|
||||
assert _driver(opened, fake).get_facts()["os_version"] == "8.0.24"
|
||||
|
||||
def test_its_own_interfaces_are_none_of_its_devices(self, opened: dict[str, Any]) -> None:
|
||||
driver = _driver(opened, FakeController(_integration(), {}))
|
||||
|
||||
assert driver.get_interfaces() == {}
|
||||
assert driver.get_interfaces_ip() == {}
|
||||
assert driver.get_lldp_neighbors() == {}
|
||||
|
||||
|
||||
class TestManagedDevices:
|
||||
def test_through_the_integration_api_with_pending_ones(self, opened: dict[str, Any]) -> None:
|
||||
devices = _driver(opened, FakeController(_integration(), {})).get_managed_devices()
|
||||
|
||||
pending = [d for d in devices if d["state"] == "pending"]
|
||||
assert {d["site"] for d in devices} == {"default"}
|
||||
assert [d["mac"] for d in pending] == ["f4:92:bf:00:00:aa"]
|
||||
assert len(devices) == len(load("integration/v10.6.106-devices.json")["data"]) + 1
|
||||
|
||||
def test_without_pending_devices_on_9_1(self, opened: dict[str, Any]) -> None:
|
||||
fake = FakeController(_integration("9.1.120", pending=False), {})
|
||||
|
||||
devices = _driver(opened, fake).get_managed_devices()
|
||||
|
||||
assert all(d["state"] != "pending" for d in devices)
|
||||
|
||||
def test_each_adopted_device_names_its_driver_and_the_way_in(
|
||||
self, opened: dict[str, Any]
|
||||
) -> None:
|
||||
devices = _driver(opened, FakeController(_integration(), {})).get_managed_devices()
|
||||
|
||||
switch = next(d for d in devices if d["role"] == "switch")
|
||||
ap = next(d for d in devices if d["role"] == "access_point" and d["state"] != "pending")
|
||||
assert switch["driver"] == "unifi_switch"
|
||||
assert ap["driver"] == "unifi_ap"
|
||||
assert switch["driver_args"] == {
|
||||
"transport": "controller",
|
||||
"controller_url": "https://192.0.2.1:443",
|
||||
"site": "default",
|
||||
"mac": switch["mac"],
|
||||
}
|
||||
|
||||
def test_no_driver_for_a_pending_device_or_a_gateway(
|
||||
self, opened: dict[str, Any], us16: dict[str, Any]
|
||||
) -> None:
|
||||
gateway = load("controller/ugw3-4.4.44-stat-device.json")
|
||||
fake = FakeController({}, {("default", "stat/device"): [gateway]})
|
||||
pending = _driver(opened, FakeController(_integration(), {})).get_managed_devices()
|
||||
|
||||
assert "driver" not in _driver(opened, fake).get_managed_devices()[0]
|
||||
assert all("driver" not in d for d in pending if d["state"] == "pending")
|
||||
|
||||
def test_one_site_only(self, opened: dict[str, Any]) -> None:
|
||||
driver = _driver(opened, FakeController(_integration(), {}), site="branch")
|
||||
|
||||
assert driver.get_managed_devices() == []
|
||||
|
||||
def test_through_the_classic_api_without_integration(
|
||||
self, opened: dict[str, Any], us16: dict[str, Any], uap: dict[str, Any]
|
||||
) -> None:
|
||||
fake = FakeController(
|
||||
{}, {("default", "stat/device"): [us16], ("branch", "stat/device"): [uap]}
|
||||
)
|
||||
|
||||
devices = _driver(opened, fake).get_managed_devices()
|
||||
|
||||
assert [(d["mac"], d["site"], d["role"]) for d in devices] == [
|
||||
(us16["mac"], "default", "switch"),
|
||||
(uap["mac"], "branch", "access_point"),
|
||||
]
|
||||
assert devices[0]["serial"] == us16["serial"].upper()
|
||||
|
||||
def test_classic_one_site(self, opened: dict[str, Any], us16: dict[str, Any]) -> None:
|
||||
fake = FakeController(
|
||||
{}, {("default", "stat/device"): [us16], ("branch", "stat/device"): []}
|
||||
)
|
||||
|
||||
devices = _driver(opened, fake, site="branch").get_managed_devices()
|
||||
|
||||
assert devices == []
|
||||
@@ -0,0 +1,274 @@
|
||||
"""Facts, ports, LLDP, MAC table and PoE from a device record.
|
||||
|
||||
A controller's ``stat/device`` entry and a device's own ``mca-dump`` carry the same
|
||||
record; each parser is run against both where the fixture allows.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_ubiquiti.parsers.device import (
|
||||
MANAGEMENT,
|
||||
parse_facts,
|
||||
parse_interfaces,
|
||||
parse_interfaces_ip,
|
||||
parse_lldp_rows,
|
||||
parse_mac_table,
|
||||
parse_poe,
|
||||
port_name,
|
||||
)
|
||||
|
||||
|
||||
class TestFacts:
|
||||
def test_controller_record(self, us16: dict[str, Any]) -> None:
|
||||
facts = parse_facts(us16)
|
||||
|
||||
assert facts["vendor"] == "Ubiquiti"
|
||||
assert facts["model"] == "US16P150"
|
||||
assert facts["hostname"] == "Switch 16"
|
||||
assert facts["fqdn"] == "Switch 16"
|
||||
assert facts["os_version"] == "4.0.66.10832"
|
||||
assert facts["serial_number"] == "FCECDA112233"
|
||||
assert facts["uptime"] == 3971865.0
|
||||
assert facts["interface_list"][:2] == ["Port 1", "Port 2"]
|
||||
assert facts["interface_list"][-1] == MANAGEMENT
|
||||
assert len(facts["interface_list"]) == 19
|
||||
|
||||
def test_mca_dump_prefers_the_product_name_and_upper_cases_the_serial(
|
||||
self, us24_dump: dict[str, Any]
|
||||
) -> None:
|
||||
facts = parse_facts(us24_dump)
|
||||
|
||||
assert facts["model"] == "US-24-G1"
|
||||
assert facts["hostname"] == "usw-1"
|
||||
assert facts["serial_number"] == "64F846000010"
|
||||
|
||||
def test_a_record_without_a_name_uses_its_mac(self) -> None:
|
||||
facts = parse_facts({"mac": "f4:92:bf:00:00:01", "model": "U6LR", "version": "6.6.55"})
|
||||
|
||||
assert facts["hostname"] == "f4:92:bf:00:00:01"
|
||||
assert facts["uptime"] == 0.0
|
||||
assert facts["serial_number"] == ""
|
||||
|
||||
|
||||
class TestInterfaces:
|
||||
def test_ports_are_named_by_index_and_keep_their_label(self, us16: dict[str, Any]) -> None:
|
||||
interfaces = parse_interfaces(us16)
|
||||
|
||||
assert interfaces["Port 1"] == {
|
||||
"is_up": True,
|
||||
"is_enabled": True,
|
||||
"description": "",
|
||||
"last_flapped": -1.0,
|
||||
"mtu": 1500,
|
||||
"speed": 1000.0,
|
||||
"mac_address": "",
|
||||
}
|
||||
assert interfaces["Port 2"]["is_up"] is False
|
||||
|
||||
def test_a_renamed_port_keeps_its_name_as_description(self, uap: dict[str, Any]) -> None:
|
||||
interfaces = parse_interfaces(uap)
|
||||
|
||||
assert interfaces["Port 1"]["description"] == "Main"
|
||||
|
||||
def test_management_carries_the_device_mac(self, us16: dict[str, Any]) -> None:
|
||||
mgmt = parse_interfaces(us16)[MANAGEMENT]
|
||||
|
||||
assert mgmt["mac_address"] == "fc:ec:da:11:22:33"
|
||||
assert mgmt["is_up"] is True
|
||||
|
||||
def test_a_disabled_port_and_jumbo_frames(self, us24_dump: dict[str, Any]) -> None:
|
||||
record = dict(us24_dump)
|
||||
record["port_table"] = [dict(us24_dump["port_table"][0], jumbo=True)]
|
||||
|
||||
port = parse_interfaces(record)["Port 1"]
|
||||
|
||||
assert port["is_enabled"] is False
|
||||
assert port["mtu"] == 9216
|
||||
|
||||
def test_a_port_without_an_index_is_left_out(self) -> None:
|
||||
record = {"mac": "78:8a:20:33:44:55", "port_table": [{"name": "wan", "up": True}]}
|
||||
|
||||
assert list(parse_interfaces(record)) == [MANAGEMENT]
|
||||
|
||||
def test_port_name(self) -> None:
|
||||
assert port_name(7) == "Port 7"
|
||||
|
||||
|
||||
class TestInterfacesIp:
|
||||
def test_controller_record_takes_the_netmask_of_its_uplink(self, us16: dict[str, Any]) -> None:
|
||||
assert parse_interfaces_ip(us16) == {
|
||||
MANAGEMENT: {"ipv4": {"192.168.0.57": {"prefix_length": 24}}}
|
||||
}
|
||||
|
||||
def test_mca_dump_has_its_own_netmask(self, us24_dump: dict[str, Any]) -> None:
|
||||
assert parse_interfaces_ip(us24_dump) == {
|
||||
MANAGEMENT: {"ipv4": {"10.0.0.10": {"prefix_length": 24}}}
|
||||
}
|
||||
|
||||
def test_no_address_no_entry(self) -> None:
|
||||
assert parse_interfaces_ip({"mac": "f4:92:bf:00:00:01"}) == {}
|
||||
|
||||
def test_an_unusable_netmask_leaves_32(self) -> None:
|
||||
record = {"ip": "192.0.2.5", "uplink": {"netmask": "0.0.0.0"}}
|
||||
|
||||
assert parse_interfaces_ip(record) == {
|
||||
MANAGEMENT: {"ipv4": {"192.0.2.5": {"prefix_length": 32}}}
|
||||
}
|
||||
|
||||
|
||||
class TestLldp:
|
||||
def test_old_firmware_lists_neighbours_per_port(self, us8: dict[str, Any]) -> None:
|
||||
rows = parse_lldp_rows(us8)
|
||||
|
||||
assert [(r["local_port"], r["system_name"], r["port_id"]) for r in rows] == [
|
||||
("Port 2", "USG", "eth1"),
|
||||
("Port 5", "Switch16", "0/1"),
|
||||
("Port 6", "UAPACPRO", "80:2A:A8:55:44:33"),
|
||||
]
|
||||
|
||||
def test_a_chassis_id_that_is_a_mac_is_typed_and_lower_cased(self, us8: dict[str, Any]) -> None:
|
||||
row = parse_lldp_rows(us8)[1]
|
||||
|
||||
assert row["chassis_id"] == "fc:ec:da:33:22:44"
|
||||
assert row["chassis_id_type"] == "mac"
|
||||
|
||||
def test_a_chassis_id_that_is_no_mac_stays_as_sent(self, us16: dict[str, Any]) -> None:
|
||||
"""The anonymised fixture carries a seven-octet id: not a MAC, kept verbatim."""
|
||||
row = parse_lldp_rows(us16)[0]
|
||||
|
||||
assert row["chassis_id"] == "F0:9F:C2:1A:2B:3C:4E"
|
||||
assert row["chassis_id_type"] == "local"
|
||||
|
||||
def test_new_firmware_lists_them_at_the_top(self, us24_dump: dict[str, Any]) -> None:
|
||||
rows = parse_lldp_rows(us24_dump)
|
||||
|
||||
assert rows == [
|
||||
{
|
||||
"local_port": "Port 22",
|
||||
"chassis_id": "f0:9f:c2:00:00:01",
|
||||
"chassis_id_type": "mac",
|
||||
"port_id": "Port 1",
|
||||
"port_id_type": "local",
|
||||
"port_description": "",
|
||||
"system_name": "",
|
||||
"system_description": "",
|
||||
"management_addresses": [],
|
||||
"capabilities": [],
|
||||
"enabled_capabilities": [],
|
||||
}
|
||||
]
|
||||
|
||||
def test_both_shapes_of_one_neighbour_count_once(self, usmini: dict[str, Any]) -> None:
|
||||
record = dict(usmini)
|
||||
record["port_table"] = [
|
||||
dict(
|
||||
usmini["port_table"][0],
|
||||
lldp_table=[
|
||||
{
|
||||
"lldp_chassis_id": "FC:EC:00:11:22:33",
|
||||
"lldp_port_id": "Port ",
|
||||
"lldp_system_name": "sw",
|
||||
}
|
||||
],
|
||||
)
|
||||
]
|
||||
|
||||
rows = parse_lldp_rows(record)
|
||||
|
||||
assert len(rows) == 1
|
||||
assert rows[0]["system_name"] == "sw"
|
||||
|
||||
def test_no_table_no_rows(self) -> None:
|
||||
assert parse_lldp_rows({"port_table": [{"port_idx": 1}]}) == []
|
||||
|
||||
|
||||
class TestMacTable:
|
||||
def test_mca_dump_lists_what_each_port_learned(self, us24_dump: dict[str, Any]) -> None:
|
||||
table = parse_mac_table(us24_dump)
|
||||
|
||||
assert len(table) == 12
|
||||
first = table[0]
|
||||
assert first["mac"] == "02:00:00:00:00:02"
|
||||
assert first["vlan"] == 8
|
||||
assert first["interface"].startswith("Port ")
|
||||
assert first["static"] is False
|
||||
assert first["active"] is True
|
||||
assert first["moves"] == 0
|
||||
assert first["last_move"] == -1.0
|
||||
|
||||
def test_a_controller_record_without_tables_is_empty(self, us16: dict[str, Any]) -> None:
|
||||
assert parse_mac_table(us16) == []
|
||||
|
||||
|
||||
class TestPoe:
|
||||
def test_controller_record(self, us16: dict[str, Any]) -> None:
|
||||
poe = parse_poe(us16)
|
||||
|
||||
assert poe["total_power_budget"] == 135.0
|
||||
assert len(poe["ports"]) == 16
|
||||
assert poe["ports"]["Port 1"] == {
|
||||
"enabled": True,
|
||||
"status": "searching",
|
||||
"poe_class": "unknown",
|
||||
"power_draw": 0.0,
|
||||
"power_budget": 0.0,
|
||||
"voltage": 0.0,
|
||||
"current": 0.0,
|
||||
}
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("port", "status"),
|
||||
[
|
||||
({"poe_mode": "off"}, "disabled"),
|
||||
({"poe_mode": "auto", "poe_good": True, "poe_power": "4.30"}, "delivering"),
|
||||
({"poe_mode": "pasv24", "poe_good": True}, "delivering"),
|
||||
({"poe_mode": "auto", "poe_good": False}, "searching"),
|
||||
],
|
||||
)
|
||||
def test_status(self, port: dict[str, Any], status: str) -> None:
|
||||
record = {"port_table": [dict(port, port_idx=1, port_poe=True)]}
|
||||
|
||||
assert parse_poe(record)["ports"]["Port 1"]["status"] == status
|
||||
|
||||
def test_drawn_power_adds_up(self) -> None:
|
||||
record = {
|
||||
"total_max_power": 60,
|
||||
"port_table": [
|
||||
{
|
||||
"port_idx": 1,
|
||||
"port_poe": True,
|
||||
"poe_mode": "auto",
|
||||
"poe_good": True,
|
||||
"poe_power": "4.30",
|
||||
"poe_class": "Class 2",
|
||||
"poe_voltage": "53.10",
|
||||
"poe_current": "81.00",
|
||||
},
|
||||
{
|
||||
"port_idx": 2,
|
||||
"port_poe": True,
|
||||
"poe_mode": "auto",
|
||||
"poe_good": True,
|
||||
"poe_power": "2.20",
|
||||
},
|
||||
{"port_idx": 3, "port_poe": False},
|
||||
],
|
||||
}
|
||||
|
||||
poe = parse_poe(record)
|
||||
|
||||
assert poe["total_power_draw"] == pytest.approx(6.5)
|
||||
assert poe["ports"]["Port 1"]["poe_class"] == "Class 2"
|
||||
assert poe["ports"]["Port 1"]["current"] == 81.0
|
||||
assert set(poe["ports"]) == {"Port 1", "Port 2"}
|
||||
|
||||
def test_unreadable_numbers_read_as_zero(self, us8: dict[str, Any]) -> None:
|
||||
port = parse_poe(us8)["ports"]["Port 8"]
|
||||
|
||||
assert port["power_draw"] == 0.0
|
||||
assert port["voltage"] == 48.0
|
||||
assert port["poe_class"] == "unknown"
|
||||
@@ -0,0 +1,160 @@
|
||||
"""The devices a UniFi controller manages, from either API, in the contract's words."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from conftest import load
|
||||
|
||||
from napalm_ubiquiti.parsers.managed import (
|
||||
managed_from_classic,
|
||||
managed_from_integration,
|
||||
managed_from_pending,
|
||||
)
|
||||
|
||||
|
||||
class TestIntegration:
|
||||
def test_an_adopted_switch(self) -> None:
|
||||
device = load("integration/v10.6.106-devices.json")["data"][0]
|
||||
|
||||
assert managed_from_integration(device, "default") == {
|
||||
"mac": "fc:ec:da:11:22:33",
|
||||
"name": "Switch 16",
|
||||
"model": "US16P150",
|
||||
"role": "switch",
|
||||
"state": "online",
|
||||
"site": "default",
|
||||
"ip": "192.168.0.57",
|
||||
"id": "5b5e2c17-0d3c-3c47-a0f1-6c1d2f1e0001",
|
||||
"firmware": "4.0.66.10832",
|
||||
}
|
||||
|
||||
def test_an_ap_and_a_gateway_that_also_switches(self) -> None:
|
||||
data = load("integration/v10.6.106-devices.json")["data"]
|
||||
|
||||
assert managed_from_integration(data[1], "default")["role"] == "access_point"
|
||||
assert managed_from_integration(data[3], "default")["role"] == "gateway"
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("state", "word"),
|
||||
[
|
||||
("ONLINE", "online"),
|
||||
("OFFLINE", "offline"),
|
||||
("CONNECTION_INTERRUPTED", "offline"),
|
||||
("ISOLATED", "offline"),
|
||||
("PENDING_ADOPTION", "pending"),
|
||||
("UPDATING", "busy"),
|
||||
("GETTING_READY", "busy"),
|
||||
("ADOPTING", "busy"),
|
||||
("DELETING", "busy"),
|
||||
("U5G_INCORRECT_TOPOLOGY", "offline"),
|
||||
("SOMETHING_NEW", "offline"),
|
||||
],
|
||||
)
|
||||
def test_states(self, state: str, word: str) -> None:
|
||||
device = {
|
||||
"macAddress": "f4:92:bf:00:00:01",
|
||||
"model": "U6LR",
|
||||
"state": state,
|
||||
"features": [],
|
||||
}
|
||||
|
||||
assert managed_from_integration(device, "default")["state"] == word
|
||||
|
||||
def test_a_device_without_features_or_address(self) -> None:
|
||||
device = {
|
||||
"macAddress": "F4:92:BF:00:00:01",
|
||||
"model": "UP1",
|
||||
"state": "ONLINE",
|
||||
"features": [],
|
||||
"name": "",
|
||||
}
|
||||
|
||||
managed = managed_from_integration(device, "default")
|
||||
|
||||
assert managed["role"] == "other"
|
||||
assert managed["ip"] is None
|
||||
assert managed["mac"] == "f4:92:bf:00:00:01"
|
||||
assert "firmware" not in managed and "id" not in managed
|
||||
|
||||
def test_a_pending_device(self) -> None:
|
||||
device = load("integration/v10.6.106-pending-devices.json")["data"][0]
|
||||
|
||||
assert managed_from_pending(device, "default") == {
|
||||
"mac": "f4:92:bf:00:00:aa",
|
||||
"name": "",
|
||||
"model": "U6LR",
|
||||
"role": "access_point",
|
||||
"state": "pending",
|
||||
"site": "default",
|
||||
"ip": "192.168.0.77",
|
||||
"firmware": "6.6.55",
|
||||
}
|
||||
|
||||
|
||||
class TestClassic:
|
||||
def test_a_switch(self, us16: dict[str, Any]) -> None:
|
||||
managed = managed_from_classic(us16, "default")
|
||||
|
||||
assert managed == {
|
||||
"mac": "fc:ec:da:11:22:33",
|
||||
"name": "Switch 16",
|
||||
"model": "US16P150",
|
||||
"role": "switch",
|
||||
"state": "online",
|
||||
"site": "default",
|
||||
"ip": "192.168.0.57",
|
||||
"id": us16["_id"],
|
||||
"serial": "FCECDA112233",
|
||||
"firmware": "4.0.66.10832",
|
||||
"firmware_available": "4.0.80.10875",
|
||||
}
|
||||
|
||||
def test_no_offer_when_it_is_not_upgradable(self, us16: dict[str, Any]) -> None:
|
||||
assert "firmware_available" not in managed_from_classic(
|
||||
dict(us16, upgradable=False), "default"
|
||||
)
|
||||
|
||||
def test_the_offered_firmware_and_the_product_name(self, us16: dict[str, Any]) -> None:
|
||||
record = dict(
|
||||
us16, upgradable=True, upgrade_to_firmware="7.1.26.15869", model_display="USW 16 PoE"
|
||||
)
|
||||
|
||||
managed = managed_from_classic(record, "default")
|
||||
|
||||
assert managed["firmware_available"] == "7.1.26.15869"
|
||||
assert managed["model_name"] == "USW 16 PoE"
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("kind", "role"),
|
||||
[
|
||||
("usw", "switch"),
|
||||
("uap", "access_point"),
|
||||
("ugw", "gateway"),
|
||||
("udm", "gateway"),
|
||||
("uxg", "gateway"),
|
||||
("uph", "other"),
|
||||
],
|
||||
)
|
||||
def test_roles(self, kind: str, role: str) -> None:
|
||||
assert managed_from_classic({"mac": "x", "type": kind, "state": 1}, "s")["role"] == role
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("state", "word"),
|
||||
[
|
||||
(1, "online"),
|
||||
(0, "offline"),
|
||||
(6, "offline"),
|
||||
(11, "offline"),
|
||||
(2, "pending"),
|
||||
(4, "busy"),
|
||||
(5, "busy"),
|
||||
(7, "busy"),
|
||||
(99, "offline"),
|
||||
],
|
||||
)
|
||||
def test_states(self, state: int, word: str) -> None:
|
||||
assert (
|
||||
managed_from_classic({"mac": "x", "type": "usw", "state": state}, "s")["state"] == word
|
||||
)
|
||||
@@ -0,0 +1,180 @@
|
||||
"""A switch's VLANs with their ports: the controller's view, and the switch's own config.
|
||||
|
||||
The controller cases follow docs/PORT_VLANS.md; the networks and profiles are written
|
||||
here with the fields the controller uses, so each rule is visible in its test.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_ubiquiti.parsers.vlans import (
|
||||
parse_running_cfg,
|
||||
parse_vlans_detail_classic,
|
||||
parse_vlans_detail_running_cfg,
|
||||
taggable_networks,
|
||||
)
|
||||
|
||||
NETWORKS: list[dict[str, Any]] = [
|
||||
{"_id": "wan", "name": "Primary (WAN1)", "purpose": "wan"},
|
||||
{"_id": "lan", "name": "Default", "purpose": "corporate", "attr_hidden_id": "LAN"},
|
||||
{"_id": "iot", "name": "IoT", "purpose": "vlan-only", "vlan_enabled": True, "vlan": 30},
|
||||
{"_id": "guest", "name": "Guest", "purpose": "guest", "vlan_enabled": True, "vlan": "40"},
|
||||
{"_id": "vpn", "name": "VPN", "purpose": "remote-user-vpn"},
|
||||
{"_id": "off", "name": "Off", "purpose": "corporate", "vlan_enabled": False, "vlan": 50},
|
||||
]
|
||||
|
||||
|
||||
def _switch(
|
||||
*ports: dict[str, Any], overrides: list[dict[str, Any]] | None = None
|
||||
) -> dict[str, Any]:
|
||||
return {"port_table": list(ports), "port_overrides": overrides or []}
|
||||
|
||||
|
||||
class TestTaggableNetworks:
|
||||
def test_switchable_purposes_with_their_vlan_ids(self) -> None:
|
||||
assert taggable_networks(NETWORKS) == {
|
||||
"lan": (1, "Default"),
|
||||
"iot": (30, "IoT"),
|
||||
"guest": (40, "Guest"),
|
||||
"off": (1, "Off"),
|
||||
}
|
||||
|
||||
|
||||
class TestClassic:
|
||||
def test_a_port_without_override_or_profile_carries_everything(self) -> None:
|
||||
vlans = parse_vlans_detail_classic(_switch({"port_idx": 1}), NETWORKS, [])
|
||||
|
||||
assert vlans["1"] == {"name": "Default", "tagged": [], "untagged": ["Port 1"]}
|
||||
assert vlans["30"] == {"name": "IoT", "tagged": ["Port 1"], "untagged": []}
|
||||
assert vlans["40"]["tagged"] == ["Port 1"]
|
||||
|
||||
def test_an_access_port_on_a_newer_controller(self) -> None:
|
||||
override = {"port_idx": 2, "native_networkconf_id": "iot", "tagged_vlan_mgmt": "block_all"}
|
||||
|
||||
vlans = parse_vlans_detail_classic(
|
||||
_switch({"port_idx": 2}, overrides=[override]), NETWORKS, []
|
||||
)
|
||||
|
||||
assert vlans["30"]["untagged"] == ["Port 2"]
|
||||
assert vlans["1"] == {"name": "Default", "tagged": [], "untagged": []}
|
||||
assert vlans["40"]["tagged"] == []
|
||||
|
||||
def test_a_custom_trunk_tags_all_but_the_excluded(self) -> None:
|
||||
override = {
|
||||
"port_idx": 3,
|
||||
"tagged_vlan_mgmt": "custom",
|
||||
"excluded_networkconf_ids": ["guest"],
|
||||
}
|
||||
|
||||
vlans = parse_vlans_detail_classic(
|
||||
_switch({"port_idx": 3}, overrides=[override]), NETWORKS, []
|
||||
)
|
||||
|
||||
assert vlans["1"]["untagged"] == ["Port 3"]
|
||||
assert vlans["30"]["tagged"] == ["Port 3"]
|
||||
assert vlans["40"]["tagged"] == []
|
||||
|
||||
def test_a_profile_from_an_older_controller(self) -> None:
|
||||
profile = {
|
||||
"_id": "p1",
|
||||
"forward": "customize",
|
||||
"native_networkconf_id": "guest",
|
||||
"tagged_networkconf_ids": ["iot", "guest"],
|
||||
}
|
||||
|
||||
vlans = parse_vlans_detail_classic(
|
||||
_switch({"port_idx": 4, "portconf_id": "p1"}), NETWORKS, [profile]
|
||||
)
|
||||
|
||||
assert vlans["40"]["untagged"] == ["Port 4"]
|
||||
assert vlans["40"]["tagged"] == []
|
||||
assert vlans["30"]["tagged"] == ["Port 4"]
|
||||
assert vlans["1"]["untagged"] == []
|
||||
|
||||
def test_the_override_names_the_profile_and_overrides_a_field(self) -> None:
|
||||
profile = {"_id": "p1", "forward": "native", "native_networkconf_id": "iot"}
|
||||
override = {"port_idx": 5, "portconf_id": "p1", "native_networkconf_id": "guest"}
|
||||
|
||||
vlans = parse_vlans_detail_classic(
|
||||
_switch({"port_idx": 5, "portconf_id": "other"}, overrides=[override]),
|
||||
NETWORKS,
|
||||
[profile],
|
||||
)
|
||||
|
||||
assert vlans["40"]["untagged"] == ["Port 5"]
|
||||
assert vlans["30"]["untagged"] == []
|
||||
assert vlans["30"]["tagged"] == []
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"field", [{"forward": "disabled"}, {"forward": "disabled", "tagged_vlan_mgmt": "auto"}]
|
||||
)
|
||||
def test_a_disabled_port_carries_nothing(self, field: dict[str, Any]) -> None:
|
||||
override = dict(field, port_idx=6)
|
||||
|
||||
vlans = parse_vlans_detail_classic(
|
||||
_switch({"port_idx": 6}, overrides=[override]), NETWORKS, []
|
||||
)
|
||||
|
||||
assert all(v["tagged"] == [] and v["untagged"] == [] for v in vlans.values())
|
||||
|
||||
def test_an_unknown_native_network_falls_back_to_the_default(self) -> None:
|
||||
override = {"port_idx": 7, "native_networkconf_id": "gone", "tagged_vlan_mgmt": "block_all"}
|
||||
|
||||
vlans = parse_vlans_detail_classic(
|
||||
_switch({"port_idx": 7}, overrides=[override]), NETWORKS, []
|
||||
)
|
||||
|
||||
assert vlans["1"]["untagged"] == ["Port 7"]
|
||||
|
||||
def test_ports_are_listed_in_order(self) -> None:
|
||||
vlans = parse_vlans_detail_classic(_switch({"port_idx": 10}, {"port_idx": 2}), NETWORKS, [])
|
||||
|
||||
assert vlans["1"]["untagged"] == ["Port 2", "Port 10"]
|
||||
|
||||
|
||||
class TestRunningCfg:
|
||||
def test_key_value_lines(self) -> None:
|
||||
assert parse_running_cfg("# c\nswitch.port.2.pvid=11\nbad line\nx=a=b\n") == {
|
||||
"switch.port.2.pvid": "11",
|
||||
"x": "a=b",
|
||||
}
|
||||
|
||||
def test_untagged_ports_by_pvid(self, us24_cfg: str) -> None:
|
||||
vlans = parse_vlans_detail_running_cfg(parse_running_cfg(us24_cfg), list(range(1, 27)))
|
||||
|
||||
assert sorted(vlans, key=int) == [
|
||||
"1",
|
||||
"2",
|
||||
"3",
|
||||
"4",
|
||||
"5",
|
||||
"6",
|
||||
"7",
|
||||
"8",
|
||||
"9",
|
||||
"10",
|
||||
"11",
|
||||
"12",
|
||||
"100",
|
||||
]
|
||||
assert vlans["11"] == {"name": "", "tagged": [], "untagged": ["Port 2"]}
|
||||
assert vlans["6"]["untagged"] == ["Port 12", "Port 15", "Port 16"]
|
||||
|
||||
def test_a_port_without_pvid_is_in_vlan_1_unless_disabled(self, us24_cfg: str) -> None:
|
||||
vlans = parse_vlans_detail_running_cfg(parse_running_cfg(us24_cfg), list(range(1, 27)))
|
||||
|
||||
assert "Port 1" not in vlans["1"]["untagged"]
|
||||
assert "Port 3" in vlans["1"]["untagged"]
|
||||
assert "Port 2" not in vlans["1"]["untagged"]
|
||||
|
||||
def test_a_disabled_vlan_is_left_out(self) -> None:
|
||||
cfg = {
|
||||
"switch.vlan.1.id": "1",
|
||||
"switch.vlan.2.id": "20",
|
||||
"switch.vlan.2.status": "disabled",
|
||||
}
|
||||
|
||||
assert list(parse_vlans_detail_running_cfg(cfg, [1])) == ["1"]
|
||||
@@ -0,0 +1,201 @@
|
||||
"""SSIDs, radios and wireless clients of a UniFi access point."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from conftest import load
|
||||
|
||||
from napalm_ubiquiti.parsers.wireless import (
|
||||
frequency_ghz,
|
||||
parse_radios,
|
||||
parse_ssids,
|
||||
parse_station_list,
|
||||
parse_vap_stations,
|
||||
)
|
||||
|
||||
AP_MAC = "80:2a:a8:00:01:02"
|
||||
|
||||
|
||||
class TestSsids:
|
||||
def test_one_ssid_on_two_bands_gets_a_key_per_band(self, uap: dict[str, Any]) -> None:
|
||||
ssids = parse_ssids(uap)
|
||||
|
||||
assert set(ssids) == {"PhG (5GHz)", "PhG (2.4GHz)"}
|
||||
assert ssids["PhG (5GHz)"] == {
|
||||
"enabled": True,
|
||||
"radio": "wifi1",
|
||||
"bssid": "80:2a:11:22:33:44",
|
||||
"encryption": "",
|
||||
"hidden": False,
|
||||
"clients": 9,
|
||||
}
|
||||
|
||||
def test_a_unique_ssid_keeps_its_name_and_the_wlan_config_fills_security(self) -> None:
|
||||
record = {
|
||||
"vap_table": [
|
||||
{
|
||||
"essid": "Lab",
|
||||
"radio": "na",
|
||||
"radio_name": "wifi1",
|
||||
"bssid": "f4:92:bf:00:00:02",
|
||||
"up": True,
|
||||
"num_sta": 2,
|
||||
"usage": "user",
|
||||
}
|
||||
]
|
||||
}
|
||||
wlans = [{"name": "Lab", "security": "wpapsk", "wpa_mode": "wpa2", "hide_ssid": True}]
|
||||
|
||||
ssid = parse_ssids(record, wlans)["Lab"]
|
||||
|
||||
assert ssid["encryption"] == "WPA2-PSK"
|
||||
assert ssid["hidden"] is True
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("wlan", "encryption"),
|
||||
[
|
||||
({"security": "open"}, "open"),
|
||||
({"security": "wpapsk", "wpa_mode": "wpa3"}, "WPA3-SAE"),
|
||||
({"security": "wpapsk", "wpa_mode": "wpa2", "wpa3_transition": True}, "WPA2/WPA3"),
|
||||
({"security": "wpaeap", "wpa_mode": "wpa2"}, "WPA2-Enterprise"),
|
||||
({"security": "wep"}, "WEP"),
|
||||
({"security": "osen"}, "osen"),
|
||||
],
|
||||
)
|
||||
def test_encryption_words(self, wlan: dict[str, Any], encryption: str) -> None:
|
||||
record = {"vap_table": [{"essid": "X", "radio": "ng", "usage": "user"}]}
|
||||
|
||||
assert parse_ssids(record, [dict(wlan, name="X")])["X"]["encryption"] == encryption
|
||||
|
||||
def test_mesh_and_scan_vaps_are_not_ssids(self) -> None:
|
||||
record = {
|
||||
"vap_table": [
|
||||
{"essid": "vwire-1", "radio": "na", "usage": "downlink"},
|
||||
{"essid": "", "radio": "na", "usage": "scan"},
|
||||
{"essid": "Lab", "radio": "ng"},
|
||||
]
|
||||
}
|
||||
|
||||
assert list(parse_ssids(record)) == ["Lab"]
|
||||
|
||||
|
||||
class TestRadios:
|
||||
def test_the_running_channel_comes_from_the_stats(self, uap: dict[str, Any]) -> None:
|
||||
radios = parse_radios(uap)
|
||||
|
||||
assert set(radios) == {"wifi0", "wifi1"}
|
||||
assert radios["wifi1"]["channel"] == 44
|
||||
assert radios["wifi1"]["band"] == "5GHz"
|
||||
assert radios["wifi1"]["channel_width"] == 40
|
||||
assert radios["wifi1"]["tx_power"] == 17
|
||||
assert radios["wifi1"]["frequency"] == pytest.approx(5.22)
|
||||
assert radios["wifi1"]["up"] is True
|
||||
assert radios["wifi0"]["band"] == "2.4GHz"
|
||||
assert radios["wifi0"]["frequency"] == pytest.approx(2.412)
|
||||
|
||||
def test_without_stats_the_configured_channel_and_no_runtime_state(self) -> None:
|
||||
record = {
|
||||
"radio_table": [
|
||||
{"name": "wifi2", "radio": "6e", "channel": 37, "ht": "320", "max_txpower": 23}
|
||||
]
|
||||
}
|
||||
|
||||
radio = parse_radios(record)["wifi2"]
|
||||
|
||||
assert radio == {
|
||||
"enabled": True,
|
||||
"band": "6GHz",
|
||||
"channel": 37,
|
||||
"channel_width": 320,
|
||||
"tx_power": 23,
|
||||
"frequency": pytest.approx(6.135),
|
||||
}
|
||||
assert "up" not in radio
|
||||
|
||||
def test_auto_channel_without_stats_reads_as_zero(self) -> None:
|
||||
record = {"radio_table": [{"name": "wifi1", "radio": "na", "channel": "auto", "ht": "80"}]}
|
||||
|
||||
radio = parse_radios(record)["wifi1"]
|
||||
|
||||
assert radio["channel"] == 0
|
||||
assert radio["frequency"] == 0.0
|
||||
|
||||
def test_a_disabled_radio(self) -> None:
|
||||
record = {"radio_table": [{"name": "wifi0", "radio": "ng", "channel": 6, "disabled": True}]}
|
||||
|
||||
assert parse_radios(record)["wifi0"]["enabled"] is False
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("channel", "band", "ghz"),
|
||||
[
|
||||
(1, "2.4GHz", 2.412),
|
||||
(14, "2.4GHz", 2.484),
|
||||
(36, "5GHz", 5.18),
|
||||
(5, "6GHz", 5.975),
|
||||
(0, "5GHz", 0.0),
|
||||
],
|
||||
)
|
||||
def test_frequency(self, channel: int, band: str, ghz: float) -> None:
|
||||
assert frequency_ghz(channel, band) == pytest.approx(ghz)
|
||||
|
||||
|
||||
class TestWirelessClients:
|
||||
def test_controller_clients_of_this_ap_only(self) -> None:
|
||||
clients = parse_station_list(load("controller/stat-sta.json"), AP_MAC)
|
||||
|
||||
assert clients == [
|
||||
{
|
||||
"mac": "00:00:00:00:00:01",
|
||||
"ssid": "SSID",
|
||||
"radio": "wifi1",
|
||||
"signal": -61,
|
||||
"noise": -106,
|
||||
"tx_rate": 216.0,
|
||||
"rx_rate": 400.0,
|
||||
"uptime": 11904,
|
||||
"ip": "192.168.0.1",
|
||||
"hostname": "client",
|
||||
}
|
||||
]
|
||||
|
||||
def test_another_aps_clients_are_left_out(self) -> None:
|
||||
assert parse_station_list(load("controller/stat-sta.json"), "f4:92:bf:00:00:99") == []
|
||||
|
||||
def test_a_devices_own_station_tables(self) -> None:
|
||||
"""``mca-dump`` lists the clients under each VAP; no AP filter needed."""
|
||||
record = {
|
||||
"vap_table": [
|
||||
{
|
||||
"essid": "Lab",
|
||||
"radio": "na",
|
||||
"radio_name": "wifi1",
|
||||
"sta_table": [
|
||||
{
|
||||
"mac": "AA:BB:CC:00:00:01",
|
||||
"signal": -55,
|
||||
"noise": -95,
|
||||
"tx_rate": 866700,
|
||||
"rx_rate": 780000,
|
||||
"uptime": 60,
|
||||
}
|
||||
],
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
clients = parse_vap_stations(record)
|
||||
|
||||
assert clients == [
|
||||
{
|
||||
"mac": "aa:bb:cc:00:00:01",
|
||||
"ssid": "Lab",
|
||||
"radio": "wifi1",
|
||||
"signal": -55,
|
||||
"noise": -95,
|
||||
"tx_rate": 866.7,
|
||||
"rx_rate": 780.0,
|
||||
"uptime": 60,
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,111 @@
|
||||
"""The switch and access point drivers: their role, and the readings their role adds.
|
||||
|
||||
A driver's source is set directly (opening one is tested in test_device_driver).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from conftest import load
|
||||
from fakes import FakeClient, FakeShell
|
||||
from napalm_device_types import AccessPointDriver, SwitchDriver
|
||||
from napalm_device_types.roles import primary_role_of
|
||||
|
||||
from napalm_ubiquiti import UnifiAccessPointDriver, UnifiSwitchDriver
|
||||
from napalm_ubiquiti.parsers.wireless import parse_radios, parse_ssids
|
||||
from napalm_ubiquiti.sources import CONFIG_COMMAND, DUMP_COMMAND, ControllerSource, SshSource
|
||||
|
||||
NETWORKS = [
|
||||
{"_id": "lan", "name": "Default", "purpose": "corporate", "attr_hidden_id": "LAN"},
|
||||
{"_id": "iot", "name": "IoT", "purpose": "corporate", "vlan_enabled": True, "vlan": 20},
|
||||
]
|
||||
|
||||
|
||||
def _through_controller(driver: Any, record: dict[str, Any], **data: list[Any]) -> FakeClient:
|
||||
client = FakeClient({f"stat/device/{record['mac']}": [record], **data})
|
||||
driver.source = ControllerSource(client, "default", record["mac"])
|
||||
return client
|
||||
|
||||
|
||||
class TestSwitch:
|
||||
def test_its_role(self) -> None:
|
||||
assert issubclass(UnifiSwitchDriver, SwitchDriver)
|
||||
assert primary_role_of(UnifiSwitchDriver) == "switch"
|
||||
assert UnifiSwitchDriver.DRIVER_NAME == "unifi_switch"
|
||||
assert "FC:EC:DA" in UnifiSwitchDriver.OUI_PREFIXES
|
||||
|
||||
def test_poe(self, us16: dict[str, Any]) -> None:
|
||||
driver = UnifiSwitchDriver("192.0.2.20", "", "")
|
||||
_through_controller(driver, us16)
|
||||
|
||||
poe = driver.get_poe_status()
|
||||
|
||||
assert poe["total_power_budget"] == 135.0
|
||||
assert len(poe["ports"]) == 16
|
||||
|
||||
def test_vlans_through_the_controller(self, us16: dict[str, Any]) -> None:
|
||||
driver = UnifiSwitchDriver("192.0.2.20", "", "")
|
||||
_through_controller(driver, us16, **{"rest/networkconf": NETWORKS, "rest/portconf": []})
|
||||
|
||||
detail = driver.get_vlans_detail()
|
||||
vlans = driver.get_vlans()
|
||||
|
||||
assert detail["1"]["name"] == "Default"
|
||||
assert vlans[1]["name"] == "Default"
|
||||
assert vlans[1]["interfaces"] == sorted(detail["1"]["untagged"] + detail["1"]["tagged"])
|
||||
assert vlans[20]["name"] == "IoT"
|
||||
|
||||
def test_vlans_over_ssh(self, us24_dump: dict[str, Any], us24_cfg: str) -> None:
|
||||
driver = UnifiSwitchDriver("192.0.2.30", "ubnt", "pw")
|
||||
shell = FakeShell({DUMP_COMMAND: json.dumps(us24_dump), CONFIG_COMMAND: us24_cfg})
|
||||
driver.source = SshSource(shell)
|
||||
|
||||
assert "Port 2" in driver.get_vlans()[11]["interfaces"]
|
||||
|
||||
|
||||
class TestAccessPoint:
|
||||
def test_its_role(self) -> None:
|
||||
assert issubclass(UnifiAccessPointDriver, AccessPointDriver)
|
||||
assert primary_role_of(UnifiAccessPointDriver) == "access_point"
|
||||
assert UnifiAccessPointDriver.DRIVER_NAME == "unifi_ap"
|
||||
|
||||
def test_ssids_carry_the_controllers_wlan_settings(self, uap: dict[str, Any]) -> None:
|
||||
wlans = load("controller/wlanconf.json")
|
||||
driver = UnifiAccessPointDriver("192.0.2.4", "", "")
|
||||
_through_controller(driver, uap, **{"rest/wlanconf": wlans})
|
||||
|
||||
assert driver.get_ssids() == parse_ssids(uap, wlans)
|
||||
|
||||
def test_radios(self, uap: dict[str, Any]) -> None:
|
||||
driver = UnifiAccessPointDriver("192.0.2.4", "", "")
|
||||
_through_controller(driver, uap)
|
||||
|
||||
assert driver.get_radio_status() == parse_radios(uap)
|
||||
|
||||
def test_clients_through_the_controller_are_this_aps_only(self, uap: dict[str, Any]) -> None:
|
||||
driver = UnifiAccessPointDriver("192.0.2.4", "", "")
|
||||
_through_controller(driver, uap, **{"stat/sta": load("controller/stat-sta.json")})
|
||||
|
||||
assert [c["mac"] for c in driver.get_wireless_clients()] == ["00:00:00:00:00:01"]
|
||||
|
||||
def test_over_ssh_clients_come_from_the_device(self) -> None:
|
||||
record = {
|
||||
"mac": "80:2a:a8:00:01:02",
|
||||
"vap_table": [
|
||||
{"essid": "Lab", "radio": "na", "sta_table": [{"mac": "aa:bb:cc:00:00:01"}]}
|
||||
],
|
||||
}
|
||||
driver = UnifiAccessPointDriver("192.0.2.4", "ubnt", "pw")
|
||||
driver.source = SshSource(FakeShell({DUMP_COMMAND: json.dumps(record)}))
|
||||
|
||||
assert [c["mac"] for c in driver.get_wireless_clients()] == ["aa:bb:cc:00:00:01"]
|
||||
assert list(driver.get_ssids()) == ["Lab"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("driver_class", [UnifiSwitchDriver, UnifiAccessPointDriver])
|
||||
def test_both_read_over_ssh_and_through_the_controller(driver_class: Any) -> None:
|
||||
assert driver_class.USES_SSH is True
|
||||
assert driver_class.VENDOR == "Ubiquiti"
|
||||
@@ -0,0 +1,63 @@
|
||||
"""The fixture sanitiser: no secret of a recorded device reaches the repository."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).parents[1] / "tools"))
|
||||
|
||||
from sanitize import REDACTED, anonymise_macs, redact, redact_cfg, sanitize # noqa: E402
|
||||
|
||||
|
||||
def test_controller_keys_are_redacted_at_any_depth() -> None:
|
||||
record = {"x_authkey": "abc", "vap_table": [{"x_passphrase": "pw", "essid": "Lab"}]}
|
||||
|
||||
assert redact(record) == {
|
||||
"x_authkey": REDACTED,
|
||||
"vap_table": [{"x_passphrase": REDACTED, "essid": "Lab"}],
|
||||
}
|
||||
|
||||
|
||||
def test_device_tokens_are_redacted() -> None:
|
||||
assert redact({"guest_token": "t", "anon_id": "a", "model": "US24"}) == {
|
||||
"guest_token": REDACTED,
|
||||
"anon_id": REDACTED,
|
||||
"model": "US24",
|
||||
}
|
||||
|
||||
|
||||
def test_running_cfg_secret_lines_are_redacted() -> None:
|
||||
text = "unifi.key=55da\nusers.1.password=x\nswitch.port.2.pvid=11\n# comment\n"
|
||||
|
||||
assert (
|
||||
redact_cfg(text)
|
||||
== "unifi.key=REDACTED\nusers.1.password=REDACTED\nswitch.port.2.pvid=11\n# comment\n"
|
||||
)
|
||||
|
||||
|
||||
def test_replacements_apply_after_redaction_in_both_formats() -> None:
|
||||
cfg = sanitize("resolv.host.1.name=usw-real\n", {"usw-real": "usw-1"})
|
||||
data = json.loads(sanitize('{"mac": "64:f8:46:45:57:f0"}', {"45:57:f0": "00:00:10"}))
|
||||
|
||||
assert cfg == "resolv.host.1.name=usw-1\n"
|
||||
assert data == {"mac": "64:f8:46:00:00:10"}
|
||||
|
||||
|
||||
def test_other_macs_map_consistently_to_local_ones() -> None:
|
||||
text = "aa:bb:cc:00:00:01 AA:BB:CC:00:00:01 f0:9f:c2:00:00:01 aa:bb:cc:00:00:02"
|
||||
|
||||
out = anonymise_macs(text, keep={"f0:9f:c2:00:00:01"})
|
||||
|
||||
assert out == "02:00:00:00:00:01 02:00:00:00:00:01 f0:9f:c2:00:00:01 02:00:00:00:00:02"
|
||||
|
||||
|
||||
def test_sanitize_keeps_the_replaced_macs() -> None:
|
||||
out = sanitize(
|
||||
'{"a": "64:f8:46:45:57:f0", "b": "1c:a8:46:7b:2f:55"}',
|
||||
{"64:f8:46:45:57:f0": "64:f8:46:00:00:10"},
|
||||
macs=True,
|
||||
)
|
||||
|
||||
assert json.loads(out) == {"a": "64:f8:46:00:00:10", "b": "02:00:00:00:00:01"}
|
||||
@@ -0,0 +1,170 @@
|
||||
"""The simulator's rules, asked directly: what a controller lets through and what not."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from unifi_sim import SimController, SimDevice
|
||||
from unifi_sim.api import Request, Response, handle
|
||||
from unifi_sim.model import integration_device
|
||||
|
||||
US16_ID = "5b8457a9e4b01dd29e9f1578"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sim() -> SimController:
|
||||
return SimController.from_fixtures()
|
||||
|
||||
|
||||
def _key(sim: SimController) -> dict[str, str]:
|
||||
return {"x-api-key": sim.api_key}
|
||||
|
||||
|
||||
def _login(sim: SimController) -> tuple[dict[str, str], str]:
|
||||
user, password = sim.admin
|
||||
reply = handle(
|
||||
sim, Request("POST", "/api/auth/login", body={"username": user, "password": password})
|
||||
)
|
||||
return {"TOKEN": reply.cookies["TOKEN"]}, reply.headers["X-CSRF-Token"]
|
||||
|
||||
|
||||
def _put(sim: SimController, **kwargs: Any) -> Response:
|
||||
path = f"/proxy/network/api/s/default/rest/device/{US16_ID}"
|
||||
return handle(sim, Request("PUT", path, body={"port_overrides": [{"port_idx": 1}]}, **kwargs))
|
||||
|
||||
|
||||
class TestWrites:
|
||||
def test_a_put_replaces_the_devices_keys(self, sim: SimController) -> None:
|
||||
reply = _put(sim, headers=_key(sim))
|
||||
|
||||
assert reply.status == 200
|
||||
assert sim.device_by_id("default", US16_ID)["port_overrides"] == [{"port_idx": 1}] # type: ignore[index]
|
||||
|
||||
def test_a_session_write_needs_its_csrf_token(self, sim: SimController) -> None:
|
||||
cookies, csrf = _login(sim)
|
||||
|
||||
assert _put(sim, cookies=cookies).status == 401
|
||||
assert _put(sim, cookies=cookies, headers={"x-csrf-token": csrf}).status == 200
|
||||
|
||||
def test_an_unknown_device(self, sim: SimController) -> None:
|
||||
path = "/proxy/network/api/s/default/rest/device/nope"
|
||||
reply = handle(sim, Request("PUT", path, headers=_key(sim), body={}))
|
||||
|
||||
assert reply.body["meta"]["msg"] == "api.err.IdInvalid"
|
||||
|
||||
def test_only_devices_are_written(self, sim: SimController) -> None:
|
||||
path = "/proxy/network/api/s/default/rest/networkconf/x"
|
||||
|
||||
assert handle(sim, Request("PUT", path, headers=_key(sim), body={})).status == 404
|
||||
assert handle(sim, Request("DELETE", path, headers=_key(sim))).status == 404
|
||||
|
||||
|
||||
class TestReads:
|
||||
def test_without_credentials(self, sim: SimController) -> None:
|
||||
reply = handle(sim, Request("GET", "/proxy/network/api/s/default/stat/device"))
|
||||
|
||||
assert reply.status == 401
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"path",
|
||||
["/nowhere", "/proxy/network/api/x", "/proxy/network/api/s/default/stat/nothing"],
|
||||
)
|
||||
def test_unknown_paths(self, sim: SimController, path: str) -> None:
|
||||
assert handle(sim, Request("GET", path, headers=_key(sim))).status == 404
|
||||
|
||||
def test_the_sysinfo_names_the_version(self, sim: SimController) -> None:
|
||||
path = "/proxy/network/api/s/default/stat/sysinfo"
|
||||
|
||||
assert (
|
||||
handle(sim, Request("GET", path, headers=_key(sim))).body["data"][0]["version"]
|
||||
== "10.6.106"
|
||||
)
|
||||
|
||||
|
||||
class TestIntegration:
|
||||
def test_pages(self, sim: SimController) -> None:
|
||||
site = sim.sites[0].id
|
||||
path = f"/proxy/network/integration/v1/sites/{site}/devices?offset=1&limit=1"
|
||||
|
||||
body = handle(sim, Request("GET", path, headers=_key(sim))).body
|
||||
|
||||
assert (body["offset"], body["count"], body["totalCount"]) == (1, 1, 3)
|
||||
|
||||
def test_a_session_is_not_enough(self, sim: SimController) -> None:
|
||||
cookies, _ = _login(sim)
|
||||
|
||||
reply = handle(sim, Request("GET", "/proxy/network/integration/v1/sites", cookies=cookies))
|
||||
|
||||
assert reply.status == 401
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("method", "path"),
|
||||
[
|
||||
("POST", "sites"),
|
||||
("GET", "sites/nosuch/devices"),
|
||||
("GET", "networks"),
|
||||
],
|
||||
)
|
||||
def test_what_it_does_not_offer(self, sim: SimController, method: str, path: str) -> None:
|
||||
reply = handle(
|
||||
sim, Request(method, f"/proxy/network/integration/v1/{path}", headers=_key(sim))
|
||||
)
|
||||
|
||||
assert reply.status == 404
|
||||
|
||||
def test_an_older_console_has_no_integration_api(self) -> None:
|
||||
sim = SimController.from_fixtures(version="8.6.9")
|
||||
|
||||
reply = handle(sim, Request("GET", "/proxy/network/integration/v1/info", headers=_key(sim)))
|
||||
|
||||
assert reply.status == 404
|
||||
|
||||
def test_the_device_states_and_features(self) -> None:
|
||||
device = integration_device({"mac": "m", "state": 0, "type": "udm"})
|
||||
|
||||
assert device["state"] == "OFFLINE"
|
||||
assert "gateway" in device["features"]
|
||||
|
||||
|
||||
class TestDeviceShell:
|
||||
def test_unknown_commands_exit_127(self) -> None:
|
||||
status, out, err = SimDevice(dump={}).answer("lldpcli show neighbors")
|
||||
|
||||
assert (status, out) == (127, "")
|
||||
assert "lldpcli: not found" in err
|
||||
|
||||
def test_extra_commands(self) -> None:
|
||||
device = SimDevice(dump={}, commands={"swctrl poe show": "Port OpMode"})
|
||||
|
||||
assert device.answer("swctrl poe show") == (0, "Port OpMode", "")
|
||||
|
||||
|
||||
class TestCommandLine:
|
||||
def test_both_servers_start_and_say_how_to_reach_them(self) -> None:
|
||||
from unifi_sim.__main__ import build, describe, parse
|
||||
|
||||
controller, switch = build(parse(["--port", "0", "--ssh-port", "0", "--api-key", "k3y"]))
|
||||
try:
|
||||
text = describe(controller, switch)
|
||||
finally:
|
||||
controller.stop()
|
||||
switch.stop()
|
||||
|
||||
assert f"https://127.0.0.1:{controller.port}" in text
|
||||
assert "API key k3y" in text
|
||||
assert f"-p {switch.port}" in text
|
||||
assert controller.fingerprint in text
|
||||
|
||||
def test_a_standalone_controller_has_no_key_to_show(self) -> None:
|
||||
from unifi_sim.__main__ import build, describe, parse
|
||||
|
||||
controller, switch = build(parse(["--port", "0", "--ssh-port", "0", "--standalone"]))
|
||||
try:
|
||||
text = describe(controller, switch)
|
||||
finally:
|
||||
controller.stop()
|
||||
switch.stop()
|
||||
|
||||
assert "standalone" in text
|
||||
assert "API key" not in text
|
||||
@@ -0,0 +1,212 @@
|
||||
"""The drivers against the simulator: real TLS, real SSH, real HTTP, nothing faked inside.
|
||||
|
||||
The simulator (``sim/unifi_sim``) plays a controller and its devices from the
|
||||
fixtures; these tests are what a first real controller will be held against.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from napalm.base.exceptions import ConnectionException
|
||||
from napalm_device_types.ssh_host_keys import SshHostKeyMismatch
|
||||
from napalm_device_types.tls_certificates import TlsCertificateMismatch
|
||||
from unifi_sim import SimController, SimDevice, serve_controller, serve_device
|
||||
|
||||
from napalm_ubiquiti import UnifiAccessPointDriver, UnifiNetworkDriver, UnifiSwitchDriver
|
||||
from napalm_ubiquiti.client import RateLimited, UnifiError
|
||||
|
||||
US16 = "fc:ec:da:11:22:33"
|
||||
UAP = "80:2a:a8:00:01:02"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_controller() -> Iterator[Any]:
|
||||
servers: list[Any] = []
|
||||
|
||||
def make(**kwargs: Any) -> Any:
|
||||
server = serve_controller(SimController.from_fixtures(**kwargs))
|
||||
servers.append(server)
|
||||
return server
|
||||
|
||||
yield make
|
||||
for server in servers:
|
||||
server.stop()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def unifi_os(make_controller: Any) -> Any:
|
||||
return make_controller()
|
||||
|
||||
|
||||
def _device_args(server: Any, **extra: Any) -> dict[str, Any]:
|
||||
return {"controller_url": server.url, "token_value": server.sim.api_key, **extra}
|
||||
|
||||
|
||||
class TestThroughAUnifiOsConsole:
|
||||
def test_a_switch_by_its_api_key(self, unifi_os: Any) -> None:
|
||||
seen: list[dict[str, Any]] = []
|
||||
args = _device_args(unifi_os, tls_certificate_observer=seen.append)
|
||||
|
||||
with UnifiSwitchDriver("192.168.0.57", "", "", optional_args=args) as switch:
|
||||
facts = switch.get_facts()
|
||||
vlans = switch.get_vlans_detail()
|
||||
|
||||
assert facts["hostname"] == "Switch 16"
|
||||
assert "Port 1" in vlans["1"]["untagged"]
|
||||
assert seen[0]["seen"]["fingerprint"] == unifi_os.fingerprint
|
||||
|
||||
def test_an_access_point_with_its_clients(self, unifi_os: Any) -> None:
|
||||
with UnifiAccessPointDriver(
|
||||
"ap", "", "", optional_args=_device_args(unifi_os, mac=UAP)
|
||||
) as ap:
|
||||
ssids = ap.get_ssids()
|
||||
clients = ap.get_wireless_clients()
|
||||
|
||||
assert ssids
|
||||
assert [c["mac"] for c in clients] == ["00:00:00:00:00:01"]
|
||||
|
||||
def test_a_local_admin_login(self, unifi_os: Any) -> None:
|
||||
user, password = unifi_os.sim.admin
|
||||
args = {"controller_url": unifi_os.url, "mac": US16}
|
||||
|
||||
with UnifiSwitchDriver("x", user, password, optional_args=args) as switch:
|
||||
assert switch.get_facts()["model"] == "US16P150"
|
||||
|
||||
def test_a_wrong_key(self, unifi_os: Any) -> None:
|
||||
args = {"controller_url": unifi_os.url, "token_value": "wrong", "mac": US16}
|
||||
|
||||
with pytest.raises(ConnectionException, match="API key"):
|
||||
UnifiSwitchDriver("x", "", "", optional_args=args).open()
|
||||
|
||||
def test_a_changed_certificate_is_refused(self, unifi_os: Any) -> None:
|
||||
args = _device_args(unifi_os, mac=US16, tls_fingerprints={str(unifi_os.port): "AB" * 32})
|
||||
|
||||
with pytest.raises(TlsCertificateMismatch):
|
||||
UnifiSwitchDriver("x", "", "", optional_args=args).open()
|
||||
|
||||
def test_a_cloud_account_with_mfa(self, unifi_os: Any) -> None:
|
||||
args = {"controller_url": unifi_os.url, "mac": US16}
|
||||
|
||||
with pytest.raises(ConnectionException, match="local admin"):
|
||||
UnifiSwitchDriver("x", "cloud@example.com", "pw", optional_args=args).open()
|
||||
|
||||
def test_too_many_failed_logins(self, unifi_os: Any) -> None:
|
||||
args = {"controller_url": unifi_os.url, "mac": US16}
|
||||
for _ in range(unifi_os.sim.max_failed_logins):
|
||||
with pytest.raises(ConnectionException):
|
||||
UnifiSwitchDriver("x", "admin", "wrong", optional_args=args).open()
|
||||
|
||||
with pytest.raises(RateLimited) as caught:
|
||||
UnifiSwitchDriver("x", "admin", "wrong", optional_args=args).open()
|
||||
|
||||
assert caught.value.retry_after == 300
|
||||
|
||||
def test_a_wrong_site(self, unifi_os: Any) -> None:
|
||||
with pytest.raises(UnifiError, match="no site"):
|
||||
UnifiSwitchDriver(
|
||||
"x", "", "", optional_args=_device_args(unifi_os, site="nosuch")
|
||||
).open()
|
||||
|
||||
def test_a_redirect_is_not_followed(self, make_controller: Any) -> None:
|
||||
server = make_controller(redirect=True)
|
||||
|
||||
with pytest.raises(UnifiError, match="redirect"):
|
||||
UnifiSwitchDriver("x", "", "", optional_args=_device_args(server, mac=US16)).open()
|
||||
|
||||
|
||||
class TestTheController:
|
||||
def test_its_devices_with_the_pending_one_on_10_6(self, unifi_os: Any) -> None:
|
||||
args = {"token_value": unifi_os.sim.api_key, "port": unifi_os.port}
|
||||
|
||||
with UnifiNetworkDriver("127.0.0.1", "", "", optional_args=args) as controller:
|
||||
facts = controller.get_facts()
|
||||
devices = controller.get_managed_devices()
|
||||
|
||||
assert facts["os_version"] == "10.6.106"
|
||||
assert {(d["site"], d["state"]) for d in devices} >= {("default", "pending")}
|
||||
assert {d["site"] for d in devices} == {"default", "branch"}
|
||||
assert UAP in {d["mac"] for d in devices}
|
||||
|
||||
def test_a_managed_device_opens_with_what_the_controller_says(self, unifi_os: Any) -> None:
|
||||
key = {"token_value": unifi_os.sim.api_key}
|
||||
with UnifiNetworkDriver(
|
||||
"127.0.0.1", "", "", optional_args={**key, "port": unifi_os.port}
|
||||
) as c:
|
||||
ap = next(d for d in c.get_managed_devices() if d.get("driver") == "unifi_ap")
|
||||
|
||||
with UnifiAccessPointDriver(
|
||||
ap["ip"], "", "", optional_args={**ap["driver_args"], **key}
|
||||
) as d:
|
||||
assert d.get_facts()["hostname"] == ap["name"]
|
||||
|
||||
def test_no_pending_devices_before_10(self, make_controller: Any) -> None:
|
||||
server = make_controller(version="9.1.120")
|
||||
args = {"token_value": server.sim.api_key, "port": server.port}
|
||||
|
||||
with UnifiNetworkDriver("127.0.0.1", "", "", optional_args=args) as controller:
|
||||
devices = controller.get_managed_devices()
|
||||
|
||||
assert devices
|
||||
assert all(d["state"] != "pending" for d in devices)
|
||||
|
||||
def test_a_standalone_controller(self, make_controller: Any) -> None:
|
||||
server = make_controller(unifi_os=False, version="8.0.24")
|
||||
user, password = server.sim.admin
|
||||
|
||||
with UnifiNetworkDriver(
|
||||
"127.0.0.1", user, password, optional_args={"port": server.port}
|
||||
) as c:
|
||||
facts = c.get_facts()
|
||||
devices = c.get_managed_devices()
|
||||
|
||||
assert facts["os_version"] == "8.0.24"
|
||||
assert US16 in {d["mac"] for d in devices}
|
||||
assert any(d.get("serial") for d in devices)
|
||||
|
||||
def test_one_site(self, unifi_os: Any) -> None:
|
||||
args = {"token_value": unifi_os.sim.api_key, "port": unifi_os.port, "site": "branch"}
|
||||
|
||||
with UnifiNetworkDriver("127.0.0.1", "", "", optional_args=args) as controller:
|
||||
assert {d["site"] for d in controller.get_managed_devices()} == {"branch"}
|
||||
|
||||
|
||||
class TestASwitchWithoutAController:
|
||||
@pytest.fixture
|
||||
def switch(self) -> Iterator[Any]:
|
||||
server = serve_device(SimDevice.us24())
|
||||
yield server
|
||||
server.stop()
|
||||
|
||||
def test_read_over_ssh(self, switch: Any) -> None:
|
||||
seen: list[dict[str, Any]] = []
|
||||
args = {"ssh_port": switch.port, "ssh_host_key_observer": seen.append}
|
||||
|
||||
with UnifiSwitchDriver("127.0.0.1", "ubnt", "ubnt", optional_args=args) as device:
|
||||
facts = device.get_facts()
|
||||
vlans = device.get_vlans()
|
||||
neighbours = device.get_lldp_neighbors()
|
||||
|
||||
assert facts["hostname"] == "usw-1"
|
||||
assert "Port 2" in vlans[11]["interfaces"]
|
||||
assert neighbours
|
||||
assert seen[0]["accepted"] is True
|
||||
|
||||
def test_a_wrong_password(self, switch: Any) -> None:
|
||||
with pytest.raises(ConnectionException):
|
||||
UnifiSwitchDriver(
|
||||
"127.0.0.1", "ubnt", "no", optional_args={"ssh_port": switch.port}
|
||||
).open()
|
||||
|
||||
def test_a_changed_host_key_is_refused(self, switch: Any) -> None:
|
||||
other = serve_device(SimDevice.us24())
|
||||
try:
|
||||
known = {str(switch.port): other.host_key}
|
||||
args = {"ssh_port": switch.port, "ssh_host_keys": known}
|
||||
|
||||
with pytest.raises(SshHostKeyMismatch):
|
||||
UnifiSwitchDriver("127.0.0.1", "ubnt", "ubnt", optional_args=args).open()
|
||||
finally:
|
||||
other.stop()
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Where a switch's or AP's readings come from: its controller, or the device itself."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from conftest import load
|
||||
from fakes import FakeClient, FakeShell
|
||||
from napalm.base.exceptions import CommandErrorException
|
||||
|
||||
from napalm_ubiquiti.client import UnifiError
|
||||
from napalm_ubiquiti.sources import (
|
||||
CONFIG_COMMAND,
|
||||
DUMP_COMMAND,
|
||||
ControllerSource,
|
||||
SshSource,
|
||||
)
|
||||
|
||||
MAC = "fc:ec:da:11:22:33"
|
||||
|
||||
|
||||
class TestController:
|
||||
def test_the_record_is_the_devices_entry_by_mac(self, us16: dict[str, Any]) -> None:
|
||||
client = FakeClient({f"stat/device/{MAC}": [us16]})
|
||||
|
||||
record = ControllerSource(client, "default", MAC).record()
|
||||
|
||||
assert record["model"] == "US16P150"
|
||||
assert client.asked == [("default", f"stat/device/{MAC}")]
|
||||
|
||||
def test_the_record_is_read_once_per_connection(self, us16: dict[str, Any]) -> None:
|
||||
client = FakeClient({f"stat/device/{MAC}": [us16]})
|
||||
source = ControllerSource(client, "default", MAC)
|
||||
|
||||
source.record()
|
||||
source.record()
|
||||
|
||||
assert len(client.asked) == 1
|
||||
|
||||
def test_a_device_the_controller_does_not_know(self) -> None:
|
||||
with pytest.raises(UnifiError, match="does not manage"):
|
||||
ControllerSource(FakeClient({}), "default", MAC).record()
|
||||
|
||||
def test_the_mac_is_normalised(self, us16: dict[str, Any]) -> None:
|
||||
client = FakeClient({f"stat/device/{MAC}": [us16]})
|
||||
|
||||
ControllerSource(client, "default", "FC-EC-DA-11-22-33").record()
|
||||
|
||||
assert client.asked == [("default", f"stat/device/{MAC}")]
|
||||
|
||||
def test_a_device_found_by_its_address_is_read_once(self, us16: dict[str, Any]) -> None:
|
||||
client = FakeClient({"stat/device": [{"ip": "192.0.2.1"}, us16]})
|
||||
|
||||
source = ControllerSource.find(client, "default", us16["ip"])
|
||||
|
||||
assert source.mac == us16["mac"]
|
||||
assert source.record()["serial"] == us16["serial"]
|
||||
assert client.asked == [("default", "stat/device")]
|
||||
|
||||
def test_no_device_at_that_address(self) -> None:
|
||||
with pytest.raises(UnifiError, match="192.0.2.9"):
|
||||
ControllerSource.find(FakeClient({}), "default", "192.0.2.9")
|
||||
|
||||
def test_vlans_come_from_networks_and_profiles(self, us16: dict[str, Any]) -> None:
|
||||
networks = [
|
||||
{"_id": "lan", "name": "Default", "purpose": "corporate", "attr_hidden_id": "LAN"}
|
||||
]
|
||||
client = FakeClient(
|
||||
{f"stat/device/{MAC}": [us16], "rest/networkconf": networks, "rest/portconf": []}
|
||||
)
|
||||
|
||||
vlans = ControllerSource(client, "default", MAC).vlans_detail()
|
||||
|
||||
assert len(vlans["1"]["untagged"]) == 18
|
||||
assert ("default", "rest/portconf") in client.asked
|
||||
|
||||
def test_clients_and_wlans(self) -> None:
|
||||
client = FakeClient(
|
||||
{
|
||||
"stat/sta": load("controller/stat-sta.json"),
|
||||
"rest/wlanconf": load("controller/wlanconf.json"),
|
||||
}
|
||||
)
|
||||
source = ControllerSource(client, "default", "80:2a:a8:00:01:02")
|
||||
|
||||
assert [c["mac"] for c in source.wireless_clients({})] == ["00:00:00:00:00:01"]
|
||||
assert [w["name"] for w in source.wlans()] == ["SSID 1", "SSID 2"]
|
||||
|
||||
|
||||
class TestSsh:
|
||||
def test_the_record_is_the_devices_own_dump(self, us24_dump: dict[str, Any]) -> None:
|
||||
shell = FakeShell({DUMP_COMMAND: json.dumps(us24_dump)})
|
||||
|
||||
record = SshSource(shell).record()
|
||||
|
||||
assert record["hostname"] == "usw-1"
|
||||
assert shell.ran == [DUMP_COMMAND]
|
||||
|
||||
def test_a_dump_that_is_no_json(self) -> None:
|
||||
with pytest.raises(CommandErrorException, match="mca-dump"):
|
||||
SshSource(FakeShell({DUMP_COMMAND: "sh: mca-dump: not found"})).record()
|
||||
|
||||
def test_vlans_from_the_running_config(self, us24_dump: dict[str, Any], us24_cfg: str) -> None:
|
||||
shell = FakeShell({DUMP_COMMAND: json.dumps(us24_dump), CONFIG_COMMAND: us24_cfg})
|
||||
|
||||
vlans = SshSource(shell).vlans_detail()
|
||||
|
||||
assert vlans["11"]["untagged"] == ["Port 2"]
|
||||
|
||||
def test_clients_come_from_the_vap_tables_and_there_are_no_wlans(self) -> None:
|
||||
record = {
|
||||
"vap_table": [
|
||||
{"essid": "Lab", "radio": "ng", "sta_table": [{"mac": "aa:bb:cc:00:00:01"}]}
|
||||
]
|
||||
}
|
||||
source = SshSource(FakeShell({}))
|
||||
|
||||
assert [c["mac"] for c in source.wireless_clients(record)] == ["aa:bb:cc:00:00:01"]
|
||||
assert source.wlans() == []
|
||||
@@ -0,0 +1,194 @@
|
||||
"""The SSH shell to a UniFi device: verified host key, one command at a time.
|
||||
|
||||
paramiko's client is replaced by a fake; no test opens a socket.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
from typing import Any
|
||||
|
||||
import paramiko
|
||||
import pytest
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
||||
from napalm.base.exceptions import CommandErrorException, ConnectionException
|
||||
from napalm_device_types.ssh_host_keys import HostKeyObservation, SshHostKey, SshHostKeyMismatch
|
||||
|
||||
from napalm_ubiquiti.ssh import SshShell, load_private_key
|
||||
|
||||
|
||||
class FakeKey:
|
||||
def get_name(self) -> str:
|
||||
return "ssh-ed25519"
|
||||
|
||||
def get_base64(self) -> str:
|
||||
return "AAAAC3NzaC1lZDI1NTE5AAAAIGZha2U="
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
def get_remote_server_key(self) -> FakeKey:
|
||||
return FakeKey()
|
||||
|
||||
|
||||
class FakeChannel:
|
||||
def __init__(self, status: int) -> None:
|
||||
self.status = status
|
||||
|
||||
def recv_exit_status(self) -> int:
|
||||
return self.status
|
||||
|
||||
|
||||
class FakeStream(io.BytesIO):
|
||||
def __init__(self, data: bytes, status: int = 0) -> None:
|
||||
super().__init__(data)
|
||||
self.channel = FakeChannel(status)
|
||||
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, answers: dict[str, tuple[int, str, str]] | None = None) -> None:
|
||||
self.answers = answers or {}
|
||||
self.connected: dict[str, Any] = {}
|
||||
self.closed = False
|
||||
self.policy: Any = None
|
||||
|
||||
def set_missing_host_key_policy(self, policy: Any) -> None:
|
||||
self.policy = policy
|
||||
|
||||
def get_host_keys(self) -> Any:
|
||||
return paramiko.HostKeys()
|
||||
|
||||
def connect(self, **kwargs: Any) -> None:
|
||||
if kwargs.get("password") == "wrong":
|
||||
raise paramiko.AuthenticationException("Authentication failed.")
|
||||
if kwargs.get("password") == "down":
|
||||
raise TimeoutError("timed out")
|
||||
self.connected = kwargs
|
||||
|
||||
def get_transport(self) -> FakeTransport:
|
||||
return FakeTransport()
|
||||
|
||||
def exec_command(self, command: str, timeout: float | None = None) -> tuple[Any, Any, Any]:
|
||||
status, out, err = self.answers.get(command, (127, "", f"sh: {command}: not found"))
|
||||
return None, FakeStream(out.encode(), status), FakeStream(err.encode())
|
||||
|
||||
def close(self) -> None:
|
||||
self.closed = True
|
||||
|
||||
|
||||
def _shell(client: FakeClient, **kwargs: Any) -> SshShell:
|
||||
return SshShell("192.0.2.10", username="ubnt", client_factory=lambda: client, **kwargs)
|
||||
|
||||
|
||||
class TestConnect:
|
||||
def test_a_password_login_without_agent_or_key_files(self) -> None:
|
||||
client = FakeClient()
|
||||
|
||||
_shell(client, password="pw").open()
|
||||
|
||||
assert client.connected["hostname"] == "192.0.2.10"
|
||||
assert client.connected["port"] == 22
|
||||
assert client.connected["username"] == "ubnt"
|
||||
assert client.connected["password"] == "pw"
|
||||
assert client.connected["allow_agent"] is False
|
||||
assert client.connected["look_for_keys"] is False
|
||||
|
||||
def test_the_host_key_seen_is_reported(self) -> None:
|
||||
seen: list[dict[str, Any]] = []
|
||||
client = FakeClient()
|
||||
|
||||
_shell(client, password="pw", optional_args={"ssh_host_key_observer": seen.append}).open()
|
||||
|
||||
assert seen[0]["seen"]["key_type"] == "ssh-ed25519"
|
||||
assert seen[0]["accepted"] is True
|
||||
|
||||
def test_a_refused_login_is_a_connection_error(self) -> None:
|
||||
with pytest.raises(ConnectionException, match="192.0.2.10"):
|
||||
_shell(FakeClient(), password="wrong").open()
|
||||
|
||||
def test_an_unreachable_device_is_a_connection_error(self) -> None:
|
||||
client = FakeClient()
|
||||
|
||||
with pytest.raises(ConnectionException, match="timed out"):
|
||||
_shell(client, password="down").open()
|
||||
|
||||
assert client.closed is True
|
||||
|
||||
def test_a_changed_host_key_is_refused_and_nothing_stays_open(self) -> None:
|
||||
class Refusing(FakeClient):
|
||||
def connect(self, **kwargs: Any) -> None:
|
||||
raise SshHostKeyMismatch(
|
||||
HostKeyObservation("192.0.2.10", 22, SshHostKey("ssh-rsa", "AAAA"), None)
|
||||
)
|
||||
|
||||
client = Refusing()
|
||||
|
||||
with pytest.raises(SshHostKeyMismatch):
|
||||
_shell(client, password="pw").open()
|
||||
|
||||
assert client.closed is True
|
||||
|
||||
def test_no_password_and_no_key(self) -> None:
|
||||
with pytest.raises(ConnectionException, match="password or a private key"):
|
||||
_shell(FakeClient()).open()
|
||||
|
||||
def test_running_before_opening(self) -> None:
|
||||
with pytest.raises(ConnectionException, match="not open"):
|
||||
_shell(FakeClient(), password="pw").run("mca-dump")
|
||||
|
||||
def test_close_closes_the_client_once(self) -> None:
|
||||
client = FakeClient()
|
||||
shell = _shell(client, password="pw")
|
||||
shell.open()
|
||||
|
||||
shell.close()
|
||||
shell.close()
|
||||
|
||||
assert client.closed is True
|
||||
|
||||
|
||||
class TestRun:
|
||||
def test_the_output_of_a_command(self) -> None:
|
||||
client = FakeClient({"mca-dump": (0, '{"mac": "x"}', "")})
|
||||
shell = _shell(client, password="pw")
|
||||
shell.open()
|
||||
|
||||
assert shell.run("mca-dump") == '{"mac": "x"}'
|
||||
|
||||
def test_a_failing_command_names_its_status_and_error(self) -> None:
|
||||
shell = _shell(FakeClient(), password="pw")
|
||||
shell.open()
|
||||
|
||||
with pytest.raises(CommandErrorException, match="127.*not found"):
|
||||
shell.run("lldpcli show neighbors")
|
||||
|
||||
|
||||
class TestPrivateKey:
|
||||
def test_an_ed25519_key(self) -> None:
|
||||
text = Ed25519PrivateKey.generate().private_bytes(
|
||||
serialization.Encoding.PEM,
|
||||
serialization.PrivateFormat.OpenSSH,
|
||||
serialization.NoEncryption(),
|
||||
)
|
||||
|
||||
assert load_private_key(text.decode()).get_name() == "ssh-ed25519"
|
||||
|
||||
def test_an_rsa_key(self) -> None:
|
||||
text = io.StringIO()
|
||||
paramiko.RSAKey.generate(1024).write_private_key(text)
|
||||
|
||||
assert load_private_key(text.getvalue()).get_name() == "ssh-rsa"
|
||||
|
||||
def test_garbage_is_a_connection_error(self) -> None:
|
||||
with pytest.raises(ConnectionException, match="private key"):
|
||||
load_private_key("not a key")
|
||||
|
||||
def test_a_key_login_hands_paramiko_the_key(self) -> None:
|
||||
text = io.StringIO()
|
||||
paramiko.RSAKey.generate(1024).write_private_key(text)
|
||||
client = FakeClient()
|
||||
|
||||
_shell(client, private_key=text.getvalue()).open()
|
||||
|
||||
assert client.connected["pkey"].get_name() == "ssh-rsa"
|
||||
assert client.connected["password"] is None
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Anonymise recorded UniFi output before it becomes a test fixture.
|
||||
|
||||
python tools/sanitize.py IN OUT [--replace OLD=NEW ...]
|
||||
|
||||
JSON input (controller responses, ``mca-dump``): every value under a secret key is
|
||||
replaced -- the ``x_*`` keys a controller keeps (authkeys, passphrases, SSH host key
|
||||
fingerprints) and the tokens a device carries. ``running.cfg`` input: the value of
|
||||
every line whose key names a key, password or token. ``--replace`` swaps a string
|
||||
everywhere, in the same way in every file, so that a MAC address or serial stays
|
||||
consistent between the fixtures that mention it. ``--macs`` then maps every other
|
||||
MAC address to a locally administered one (``02:00:00:00:..``), the same input to
|
||||
the same output.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
REDACTED = "REDACTED"
|
||||
SECRET_KEYS = frozenset(
|
||||
{"guest_token", "syslog_key", "anon_id", "hash_id", "stream_token", "x_passphrase"}
|
||||
)
|
||||
MAC = re.compile(r"\b[0-9a-f]{2}(?::[0-9a-f]{2}){5}\b", re.IGNORECASE)
|
||||
KEEP_PREFIX = "02:00:00:00:"
|
||||
CFG_SECRET = re.compile(r"(?:^|\.)(key|password|authkey|token|passphrase|x_[a-z_]+)$")
|
||||
|
||||
|
||||
def _is_secret(key: str) -> bool:
|
||||
return key.startswith("x_") or key in SECRET_KEYS
|
||||
|
||||
|
||||
def redact(value: Any) -> Any:
|
||||
"""*value* with every secret key's value replaced, at any depth."""
|
||||
if isinstance(value, dict):
|
||||
return {k: (REDACTED if _is_secret(k) else redact(v)) for k, v in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [redact(item) for item in value]
|
||||
return value
|
||||
|
||||
|
||||
def redact_cfg(text: str) -> str:
|
||||
"""A ``running.cfg`` with the value of every secret line replaced."""
|
||||
lines = []
|
||||
for line in text.splitlines():
|
||||
key, sep, _ = line.partition("=")
|
||||
lines.append(f"{key}={REDACTED}" if sep and CFG_SECRET.search(key) else line)
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def anonymise_macs(text: str, keep: set[str]) -> str:
|
||||
"""Every MAC address in *text* not in *keep* mapped to a locally administered one."""
|
||||
mapping: dict[str, str] = {}
|
||||
|
||||
def _swap(match: re.Match[str]) -> str:
|
||||
mac = match.group(0).lower()
|
||||
if mac in keep or mac.startswith(KEEP_PREFIX):
|
||||
return match.group(0)
|
||||
if mac not in mapping:
|
||||
n = len(mapping) + 1
|
||||
mapping[mac] = f"{KEEP_PREFIX}{n >> 8:02x}:{n & 0xFF:02x}"
|
||||
return mapping[mac]
|
||||
|
||||
return MAC.sub(_swap, text)
|
||||
|
||||
|
||||
def sanitize(text: str, replacements: dict[str, str], *, macs: bool = False) -> str:
|
||||
"""*text* redacted (JSON or ``running.cfg``), then with *replacements* applied.
|
||||
|
||||
With *macs*, every MAC address the replacements did not set is anonymised.
|
||||
"""
|
||||
try:
|
||||
out = json.dumps(redact(json.loads(text)), indent=1, sort_keys=True) + "\n"
|
||||
except json.JSONDecodeError:
|
||||
out = redact_cfg(text)
|
||||
for old, new in replacements.items():
|
||||
out = out.replace(old, new)
|
||||
if macs:
|
||||
out = anonymise_macs(out, {new.lower() for new in replacements.values()})
|
||||
return out
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("source", type=pathlib.Path)
|
||||
parser.add_argument("target", type=pathlib.Path)
|
||||
parser.add_argument("--replace", action="append", default=[], metavar="OLD=NEW")
|
||||
parser.add_argument("--macs", action="store_true", help="anonymise every other MAC")
|
||||
args = parser.parse_args()
|
||||
replacements = dict(item.split("=", 1) for item in args.replace)
|
||||
text = sanitize(args.source.read_text(), replacements, macs=args.macs)
|
||||
args.target.write_text(text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user