Files
napalm-proxmox/napalm_proxmox/driver.py
T
Christian Manivong f554e2cc79
driver / standard (pull_request) Failing after 17s
driver / lint (pull_request) Successful in 18s
driver / types (pull_request) Successful in 56s
driver / lowest (pull_request) Successful in 37s
driver / test (3.12) (pull_request) Successful in 1m6s
driver / test (3.13) (pull_request) Successful in 1m3s
driver / security (pull_request) Successful in 53s
driver / build (pull_request) Successful in 49s
CI / driver (pull_request) Failing after 2m8s
driver / publish (pull_request) Skipped
feat(login): get_web_login_auth on PVE and PBS, a source per realm, 0.20.0 (NetOrk/netork#662)
A Proxmox login names its realm, so each realm with someone who can log in
is a source of napalm-device-types' WebLoginAuthDict. It asks for a password
and a one-time code when the PVE realm's own tfa is set, or when every
enabled, unexpired user of it has an enabled second factor (/access/tfa);
a password alone when one user has none; OpenID is external.

Both servers list only the caller in /access/users and /access/tfa when the
login may not see the others, so the driver checks /access/permissions
first: Sys.Audit or User.Modify on /access/groups on PVE, Sys.Audit on
/access/users on PBS. Without it the read raises PermissionError rather
than judge the server by one account.

Needs napalm-device-types 4.50.0.
2026-11-29 00:19:52 +01:00

270 lines
9.8 KiB
Python

"""NAPALM driver for Proxmox VE.
Supports:
- Classic Linux networking (/etc/network/interfaces via Proxmox API)
- Software-Defined Networking (SDN): zones, VNets, subnets
- Open vSwitch (OVS) bridges, bonds, and internal ports
Connection is made via the Proxmox REST API (``proxmoxer`` library).
The driver targets the *node* level: each Proxmox node is treated as a
network device. Cluster-wide SDN information is also exposed where the
NAPALM API allows it.
Optional args
-------------
The connection's are the shared base's (``napalm_proxmox._base``; the API port
defaults to 8006 here). In addition:
node : str
Override the target node name (default: auto-detected from hostname).
"""
from __future__ import annotations
import logging
from typing import Any
from napalm.base.exceptions import ConnectionException
from napalm_device_types import (
AptProxyMixin,
EnsurePackageMixin,
FingerprintRule,
HardeningMixin,
HostFirewallMixin,
HostStatusMixin,
HypervisorDriver,
KernelFactsMixin,
LicenseMixin,
ListeningSocketsMixin,
LogSourcesMixin,
OpenSshServerMixin,
PortSpec,
ServicePackagesMixin,
ServicesRestartMixin,
SnmpAgentMixin,
SystemdServicesMixin,
SystemIdentityMixin,
)
try:
from proxmoxer import ProxmoxAPI
except ImportError as exc:
raise ImportError("proxmoxer is required: pip install proxmoxer") from exc
from napalm_proxmox._base import ProxmoxBase
from napalm_proxmox.certificates import ProxmoxCertificatesMixin
from napalm_proxmox.cluster_mixin import ProxmoxClusterMixin
from napalm_proxmox.config_mixin import ProxmoxConfigMixin
from napalm_proxmox.credential_expiry import ProxmoxCredentialExpiryMixin
from napalm_proxmox.firewall_mixin import ProxmoxFirewallMixin
from napalm_proxmox.host_mixin import ProxmoxHostMixin
from napalm_proxmox.interfaces_mixin import ProxmoxInterfaceMixin
from napalm_proxmox.lldp_mixin import ProxmoxLLDPMixin
from napalm_proxmox.routing_mixin import ProxmoxRoutingMixin
from napalm_proxmox.running_backups import ProxmoxRunningBackupsMixin
from napalm_proxmox.scheduled_jobs import PVE_PLATFORM_SOURCES, ProxmoxScheduledJobsMixin
from napalm_proxmox.sdn_mixin import ProxmoxSDNMixin
from napalm_proxmox.system_mixin import ProxmoxSystemMixin
from napalm_proxmox.time_sync import ProxmoxTimeSyncMixin
from napalm_proxmox.update_history import ProxmoxUpdateHistoryMixin
from napalm_proxmox.vm_contract_mixin import ProxmoxVMContractMixin
from napalm_proxmox.vm_migrate_mixin import ProxmoxVMMigrateMixin
from napalm_proxmox.vm_mixin import ProxmoxVMMixin
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
from napalm_proxmox.vm_snapshot_mixin import ProxmoxVMSnapshotMixin
from napalm_proxmox.web_login import ProxmoxWebLoginMixin
from napalm_proxmox.zabbix_agent import ProxmoxZabbixAgentMixin
logger = logging.getLogger(__name__)
# --------------------------------------------------------------------------- #
# Type aliases
# --------------------------------------------------------------------------- #
_JsonDict = dict[str, Any]
# --------------------------------------------------------------------------- #
# Driver
# --------------------------------------------------------------------------- #
class ProxmoxDriver(
ProxmoxBase,
ProxmoxInterfaceMixin,
ProxmoxSDNMixin,
ProxmoxLLDPMixin,
ProxmoxConfigMixin,
ProxmoxVMMixin,
ProxmoxVMContractMixin,
ProxmoxVMSnapshotMixin,
ProxmoxVMProvisionMixin,
ProxmoxClusterMixin,
ProxmoxVMMigrateMixin,
ProxmoxRoutingMixin,
ProxmoxSystemMixin,
ProxmoxHostMixin,
ProxmoxFirewallMixin,
KernelFactsMixin,
HostFirewallMixin,
HardeningMixin,
ServicePackagesMixin,
ListeningSocketsMixin,
LogSourcesMixin,
ServicesRestartMixin,
SystemIdentityMixin,
SystemdServicesMixin,
ProxmoxScheduledJobsMixin,
ProxmoxRunningBackupsMixin,
ProxmoxTimeSyncMixin,
ProxmoxCertificatesMixin,
ProxmoxCredentialExpiryMixin,
ProxmoxWebLoginMixin,
ProxmoxUpdateHistoryMixin,
HostStatusMixin,
LicenseMixin,
SnmpAgentMixin,
ProxmoxZabbixAgentMixin,
EnsurePackageMixin,
AptProxyMixin,
OpenSshServerMixin,
HypervisorDriver,
):
"""NAPALM driver for Proxmox VE nodes."""
VENDOR = "Proxmox"
DRIVER_NAME = "proxmox"
# netOrk reaches the node through the REST API and does not log in over SSH
# itself; the driver's own SSH session (_node_ssh) runs the node's shell.
USES_SSH = False
# A PVE node reboots through a full init sequence plus storage checks.
REBOOT_SETTLE_SECONDS = 90
#: "Upgrade everything" must be a full upgrade on Proxmox VE: a plain
#: ``apt-get upgrade`` holds back what needs new or removed packages and can
#: leave the node half updated. netOrk reads this when it upgrades the host.
FULL_UPGRADE = True
#: Proxmox VE's own timers and cron file are ``platform``.
PLATFORM_SOURCES = PVE_PLATFORM_SOURCES
#: Shows every user and their second factors (``web_login``).
WEB_LOGIN_PRIVILEGE = ("/access/groups", ("Sys.Audit", "User.Modify"))
#: ``/etc/cron.d/vzdump`` links into ``/etc/pve`` (pmxcfs); its lines are only run.
RUN_ONLY_SOURCES = ("/etc/cron.d/vzdump",)
PORT_SPECS = [
PortSpec("https", 8006, weight=8.0),
]
SSH_FINGERPRINT = [
FingerprintRule("debian", weight=3.0),
]
HTTP_FINGERPRINT = [
FingerprintRule("proxmox virtual environment", weight=9.0, mandatory=True),
FingerprintRule("proxmox", weight=5.0),
FingerprintRule("pve", weight=2.0),
]
platform = "proxmox"
def __init__(
self,
hostname: str,
username: str,
password: str,
timeout: int = 60,
optional_args: _JsonDict | None = None,
) -> None:
super().__init__(hostname, username, password, timeout, optional_args)
self._node: str | None = self.optional_args.get("node")
# Candidate config (merge/replace)
self._candidate_config: str = ""
self._running_config: str = ""
# ------------------------------------------------------------------ #
# Connection management
# ------------------------------------------------------------------ #
def _proxmox_api(self, **kwargs: Any) -> Any:
return ProxmoxAPI(**kwargs)
def _resolve_node(self) -> str:
"""Resolve the PVE node this connection talks to.
In a cluster, ``GET /nodes`` lists every member, so its first entry is
just some node, not necessarily the one at ``self.hostname``. That used
to be taken blindly, and a device then reported another node's name and
VMs. ``GET /cluster/status`` marks the node the session landed on with
``local: 1``; failing that, the node is matched by IP or name.
API errors propagate so that ``open()`` fails with the real cause (e.g.
a TLS verification error) rather than succeeding on a guessed name.
"""
if self._node:
self._node_name = self._node
return self._node_name
members = [s for s in (self._api.cluster.status.get() or []) if s.get("type") == "node"]
short_host = self.hostname.split(".")[0]
for pick in (
lambda s: s.get("local"),
lambda s: s.get("ip") == self.hostname,
lambda s: s.get("name") in (self.hostname, short_host),
):
match = next((s for s in members if pick(s)), None)
if match:
self._node_name = match["name"]
return self._node_name
names = [n.get("node") for n in (self._api.nodes.get() or []) if n.get("node")]
if len(names) == 1:
self._node_name = names[0]
return self._node_name
raise ConnectionException(
f"Cannot tell which PVE node {self.hostname} is among {names}; "
f"set the 'node' driver argument"
)
# ------------------------------------------------------------------ #
# NAPALM getters kept in driver
# ------------------------------------------------------------------ #
def get_facts(self) -> _JsonDict:
"""Return basic facts about the Proxmox node.
Hardware vendor, model and serial are read from the Linux DMI sysfs
entries (``/sys/class/dmi/id/``) via SSH so they reflect the physical
machine, not the Proxmox software layer.
"""
status = self._get_node_status()
version = self._get_version_info()
network = self._get_node_network()
dns = self._get_node_dns()
uptime = float(status.get("uptime", 0))
dns_search = dns.get("search", "")
fqdn = f"{self._node_name}.{dns_search}" if dns_search else self.hostname
iface_list = sorted(iface["iface"] for iface in network if iface.get("iface"))
pve_version = version.get("version", "")
release = version.get("release", "")
os_version = f"Proxmox VE {pve_version}" if pve_version else f"Proxmox VE {release}"
vendor, model, serial = self._hardware()
# Currently-booted kernel release (uname -r) — distinct from any newer
# kernel that is merely installed and pending a reboot.
running_kernel = ""
try:
running_kernel = self._exec_ssh_command("uname -r").strip()
except Exception as exc:
logger.debug("Failed to read running kernel via SSH: %s", exc)
return {
"uptime": uptime,
"vendor": vendor or "Proxmox Server Solutions GmbH",
"model": model or status.get("model") or "Proxmox VE Node",
"hostname": self._node_name,
"fqdn": fqdn or self.hostname,
"os_version": os_version,
"serial_number": serial,
"interface_list": iface_list,
"running_kernel": running_kernel,
}