fix(interfaces): read interfaces and addresses from the gateway's status page
driver / standard (pull_request) Failing after 15s
driver / lint (pull_request) Successful in 13s
driver / types (pull_request) Successful in 59s
driver / test (3.13) (pull_request) Successful in 52s
driver / test (3.12) (pull_request) Successful in 56s
driver / lowest (pull_request) Successful in 25s
driver / build (pull_request) Successful in 27s
driver / security (pull_request) Successful in 54s
CI / driver (pull_request) Failing after 2m1s
driver / publish (pull_request) Skipped

get_interfaces reported a fixed set: wan, lan and two Wi-Fi radios, all
up at 1000 Mbit/s, the LAN with the WAN's MAC. get_interfaces_ip gave
both a /24, the LAN's address being the hostname the driver connected
to. getBasicInformation carries none of WanIp, LanIp or MacAddress on a
VMG4005-B50A, a VDSL bridge without Wi-Fi whose LAN is a /29, and the
gateway showed all of the invented values.

Both now read the DAL's cardpage_status, which a GET answers sealed like
a PUT: the IP interfaces in WanLanInfo (br0, atm0.1, ptm0.2) with their
status, MAC and netmask, the Ethernet ports in LanInfo (eth1) with their
speed. A speed or MTU the gateway does not report is 0, unknown. IPv6
addresses are not read yet: no gateway seen so far had IPv6 on.
This commit is contained in:
Christian Manivong committed 2026-11-12 16:14:25 +01:00
1 parent 63f92561eb
commit ec76c1d6e8
4 files changed
+262 -56

No files matched your search

+69 -38
View File
@@ -7,6 +7,7 @@ payloads through the Zyxel DAL protocol.
from __future__ import annotations
import base64
import ipaddress
import json
import logging
import os
@@ -323,52 +324,82 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
"interface_list": iface_list,
}
def _status_page(self) -> dict[str, Any]:
"""The DAL's ``cardpage_status``, decrypted; raises when it cannot be read.
A GET of the DAL answers sealed, ``{"content", "iv"}``, like the PUT does.
"""
text = self._fetch_page("cgi-bin/DAL?oid=cardpage_status")
if self._crypto is None:
raise ConnectionClosedException("Not connected")
try:
answer = json.loads(text)
if isinstance(answer, dict) and {"content", "iv"} <= answer.keys():
answer = self._crypto.decrypt_response(answer)
except (ValueError, TypeError, KeyError) as exc:
raise RuntimeError(f"DAL cardpage_status on {self._base_url}: {exc}") from exc
result = answer.get("result") if isinstance(answer, dict) else None
objects = answer.get("Object") if result == "ZCFG_SUCCESS" else None
if not objects or not isinstance(objects[0], dict):
raise RuntimeError(f"DAL cardpage_status on {self._base_url} answered {result!r}")
return objects[0]
def get_interfaces(self) -> dict[str, dict[str, Any]]:
"""Return WAN, LAN, and WiFi interfaces from device info."""
"""The gateway's IP interfaces (``WanLanInfo``) and Ethernet ports (``LanInfo``).
Keyed by the gateway's own interface name (``br0``, ``ptm0.2``, ``eth1``). A
speed or MTU the gateway does not report is 0: unknown.
"""
page = self._status_page()
ifaces: dict[str, dict[str, Any]] = {}
info = self._device_info or {}
wan_ip = info.get("WanIp", "")
mac = info.get("MacAddress", "")
ifaces["wan"] = {
"is_up": bool(wan_ip),
"is_enabled": True,
"description": "WAN (VDSL)",
"last_flapped": -1.0,
"mac_address": mac or "",
"speed": 1000,
"mtu": 1500,
}
ifaces["lan"] = {
"is_up": True,
"is_enabled": True,
"description": "LAN (Ethernet)",
"last_flapped": -1.0,
"mac_address": mac or "",
"speed": 1000,
"mtu": 1500,
}
for band in ("2.4GHz", "5GHz"):
key = f"wlan_{band.lower().replace('.', '_').replace('ghz', 'ghz')}"
ifaces[key] = {
"is_up": True,
"is_enabled": True,
"description": f"WiFi {band}",
for entry in page.get("WanLanInfo") or []:
name = entry.get("X_ZYXEL_IfName")
if not name:
continue
label = entry.get("Name") or name
service = entry.get("X_ZYXEL_SrvName") or ""
ifaces[name] = {
"is_up": entry.get("Status") == "Up",
"is_enabled": bool(entry.get("Enable")),
"description": f"{label} ({service})"
if entry.get("X_ZYXEL_Type") == "WAN" and service
else label,
"last_flapped": -1.0,
"mac_address": "",
"speed": 0,
"mtu": 1500,
"mac_address": entry.get("MACAddress") or "",
"speed": 0.0,
"mtu": 0,
}
for port in page.get("LanInfo") or []:
name = port.get("Name")
if not name:
continue
ifaces[name] = {
"is_up": port.get("Status") == "Up",
"is_enabled": bool(port.get("Enable")),
"description": port.get("X_ZYXEL_LanPort") or name,
"last_flapped": -1.0,
"mac_address": port.get("MACAddress") or "",
"speed": float(port.get("MaxBitRate") or 0),
"mtu": 0,
}
return ifaces
def get_interfaces_ip(self) -> dict[str, dict[str, Any]]:
"""Return IP addresses of WAN and LAN interfaces."""
info = self._device_info or {}
wan_ip = info.get("WanIp", "")
lan_ip = info.get("LanIp", self.hostname)
"""The IPv4 addresses of the gateway's IP interfaces, with their netmask.
IPv6 addresses are not read yet: no gateway seen so far had IPv6 on.
"""
result: dict[str, dict[str, Any]] = {}
if wan_ip:
result["wan"] = {"ipv4": {wan_ip: {"prefix_length": 24}}, "ipv6": {}}
result["lan"] = {"ipv4": {lan_ip: {"prefix_length": 24}}, "ipv6": {}}
for entry in self._status_page().get("WanLanInfo") or []:
name = entry.get("X_ZYXEL_IfName")
ipv4: dict[str, dict[str, int]] = {}
for addr in entry.get("IPv4Address") or []:
ip, mask = addr.get("IPAddress"), addr.get("SubnetMask")
if not addr.get("Enable") or not ip or not mask:
continue
ipv4[ip] = {"prefix_length": ipaddress.IPv4Network(f"0.0.0.0/{mask}").prefixlen}
if name and ipv4:
result[name] = {"ipv4": ipv4, "ipv6": {}}
return result
def get_arp_table(self, vrf: str = "") -> list[dict[str, Any]]:
-4
View File
@@ -140,10 +140,6 @@ def test_a_gateway_that_lists_no_hosts_has_none():
assert driver.get_hosts() == []
def test_get_facts_lists_the_interfaces():
assert _driver({}).get_facts()["interface_list"] == ["wan", "lan", "wlan_2_4ghz", "wlan_5ghz"]
def test_get_facts_raises_when_the_interfaces_cannot_be_read():
driver = _driver({})
driver.get_interfaces = MagicMock(side_effect=RuntimeError("no interfaces"))
+192
View File
@@ -0,0 +1,192 @@
"""Interfaces and their addresses come from the gateway's own status page.
``get_interfaces`` used to report a fixed set: ``wan``, ``lan`` and two Wi-Fi radios,
all up, at 1000 Mbit/s, with the WAN's MAC on the LAN. ``get_interfaces_ip`` gave
both a /24. A VMG4005-B50A, a VDSL bridge without Wi-Fi whose LAN is a /29, showed
all of that. Both now read the DAL's ``cardpage_status``: the IP interfaces in
``WanLanInfo`` and the Ethernet ports in ``LanInfo``. IPv6 addresses are not read
yet: the gateway this was taken from has IPv6 off and so shows none to learn from.
``CARDPAGE`` is that answer from a VMG4005-B50A (V5.17(ABQA.3.1)C0), cut down to the
fields the driver reads.
"""
from __future__ import annotations
import json
from typing import Any
from unittest.mock import MagicMock
import pytest
import requests
from napalm_zyxel import ZyxelVMGDriver
CARDPAGE: dict[str, Any] = {
"result": "ZCFG_SUCCESS",
"Object": [
{
"WanLanInfo": [
{
"Enable": True,
"X_ZYXEL_Type": "LAN",
"MACAddress": "6c:4f:89:6a:bf:50",
"Status": "Up",
"X_ZYXEL_SrvName": "Default",
"Name": "LAN",
"X_ZYXEL_IfName": "br0",
"IPv4Address": [
{
"Enable": True,
"IPAddress": "192.168.1.1",
"SubnetMask": "255.255.255.248",
"Status": "Enabled",
}
],
"IPv6Address": [],
},
{
# No "Status" at all: the gateway leaves it out for this bridge.
"Enable": True,
"X_ZYXEL_Type": "WAN",
"MACAddress": "",
"X_ZYXEL_SrvName": "Bridge_ATM",
"Name": "WAN",
"X_ZYXEL_IfName": "atm0.1",
"IPv4Address": [],
"IPv6Address": [],
},
{
"Enable": True,
"X_ZYXEL_Type": "WAN",
"MACAddress": "",
"Status": "LowerLayerDown",
"X_ZYXEL_SrvName": "Bridge_PTM",
"Name": "WAN",
"X_ZYXEL_IfName": "ptm0.2",
"IPv4Address": [],
"IPv6Address": [],
},
],
"LanInfo": [
{
"Enable": True,
"Status": "Up",
"Name": "eth1",
"MACAddress": "6c:4f:89:6a:bf:53",
"MaxBitRate": 1000,
"X_ZYXEL_LanPort": "LAN1",
}
],
}
],
}
def _response(status: int, text: str = "") -> requests.Response:
resp = requests.Response()
resp.status_code = status
resp._content = text.encode()
resp.url = "http://192.168.1.1/"
return resp
def _driver(answer: dict[str, Any] | requests.Response) -> ZyxelVMGDriver:
"""A logged-in driver whose gateway answers ``cardpage_status`` with *answer*,
encrypted the way the gateway sends it."""
driver = ZyxelVMGDriver("192.168.1.1", "admin", "password")
# NAPALM's __del__ asks is_alive(), which opens a TCP connection: not in a test.
driver.is_alive = lambda: {"is_alive": False} # type: ignore[method-assign]
sealed = {"content": "SEALED", "iv": "IV"}
reply = answer if isinstance(answer, requests.Response) else _response(200, json.dumps(sealed))
def get(url: str, params: dict[str, Any] | None = None, **_: Any) -> requests.Response:
if url.endswith("cgi-bin/DAL?oid=cardpage_status"):
return reply
return _response(404)
session = MagicMock(spec=requests.Session)
session.get.side_effect = get
driver._session = session
driver._sessionkey = "1"
driver._crypto = MagicMock()
driver._crypto.decrypt_response.side_effect = lambda data: (
answer if data == sealed else pytest.fail(f"decrypted {data!r}")
)
driver._device_info = {"ModelName": "VMG4005-B50A"}
return driver
# --- get_interfaces -------------------------------------------------------------------
def test_reports_the_gateways_interfaces_and_nothing_else():
assert set(_driver(CARDPAGE).get_interfaces()) == {"br0", "atm0.1", "ptm0.2", "eth1"}
def test_an_ip_interface_is_up_only_when_the_gateway_says_so():
ifaces = _driver(CARDPAGE).get_interfaces()
assert ifaces["br0"]["is_up"] is True
assert ifaces["ptm0.2"]["is_up"] is False
assert ifaces["atm0.1"]["is_up"] is False # no status reported
def test_an_ip_interface_carries_its_own_mac_and_name():
br0 = _driver(CARDPAGE).get_interfaces()["br0"]
assert br0["mac_address"] == "6c:4f:89:6a:bf:50"
assert br0["description"] == "LAN"
assert br0["is_enabled"] is True
def test_a_wan_bridge_is_named_after_its_service():
assert _driver(CARDPAGE).get_interfaces()["ptm0.2"]["description"] == "WAN (Bridge_PTM)"
def test_an_ethernet_port_carries_its_speed_mac_and_label():
eth1 = _driver(CARDPAGE).get_interfaces()["eth1"]
assert eth1["speed"] == 1000.0
assert eth1["mac_address"] == "6c:4f:89:6a:bf:53"
assert eth1["description"] == "LAN1"
assert eth1["is_up"] is True
def test_a_speed_or_mtu_the_gateway_does_not_report_is_left_unknown():
br0 = _driver(CARDPAGE).get_interfaces()["br0"]
assert br0["speed"] == 0.0
assert br0["mtu"] == 0
def test_a_gateway_without_wifi_has_no_wifi_interfaces():
assert not [n for n in _driver(CARDPAGE).get_interfaces() if "wlan" in n]
def test_get_facts_lists_the_gateways_interfaces():
names = _driver(CARDPAGE).get_facts()["interface_list"]
assert sorted(names) == ["atm0.1", "br0", "eth1", "ptm0.2"]
# --- get_interfaces_ip ----------------------------------------------------------------
def test_the_lan_address_keeps_the_gateways_netmask():
ips = _driver(CARDPAGE).get_interfaces_ip()
assert ips == {"br0": {"ipv4": {"192.168.1.1": {"prefix_length": 29}}, "ipv6": {}}}
def test_a_disabled_address_is_not_reported():
page = json.loads(json.dumps(CARDPAGE))
page["Object"][0]["WanLanInfo"][0]["IPv4Address"][0]["Enable"] = False
assert _driver(page).get_interfaces_ip() == {}
# --- a status page that cannot be read ------------------------------------------------
def test_a_refused_status_page_raises():
with pytest.raises(RuntimeError, match="cardpage_status"):
_driver({"result": "ZCFG_NO_SUCH_OBJECT", "Object": []}).get_interfaces()
def test_a_failed_request_raises():
with pytest.raises(RuntimeError, match="500"):
_driver(_response(500)).get_interfaces()
+1 -14
View File
@@ -176,6 +176,7 @@ class TestZyxelVMGDriver:
def test_get_facts(self):
self._setup_mocked_http()
self.driver.get_interfaces = lambda: {} # type: ignore[method-assign] # tests/test_interfaces.py
facts = self.driver.get_facts()
assert facts["vendor"] == "Zyxel"
assert facts["model"] == "VMG4005-B50A"
@@ -183,20 +184,6 @@ class TestZyxelVMGDriver:
assert facts["os_version"] == "V5.13(ABKS.1)C0"
assert facts["hostname"] == "ZyxelVMG"
def test_get_interfaces(self):
self._setup_mocked_http()
ifaces = self.driver.get_interfaces()
assert "wan" in ifaces
assert "lan" in ifaces
assert "wlan_2_4ghz" in ifaces
assert "wlan_5ghz" in ifaces
def test_get_interfaces_ip(self):
self._setup_mocked_http()
ips = self.driver.get_interfaces_ip()
assert "85.2.34.56" in ips["wan"]["ipv4"]
assert "192.168.1.1" in ips["lan"]["ipv4"]
def test_get_wan_status(self):
self._setup_mocked_http()
status = self.driver.get_wan_status()