From a97e59c1e2d4442748a44385626da40494212b2d Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Tue, 1 Dec 2026 12:49:17 +0100 Subject: [PATCH] feat(processes): running processes from Win32_Process and Get-Process (NetOrk/netork#2889) --- napalm_windows/_reading.py | 18 +++ napalm_windows/host_basics.py | 4 +- napalm_windows/processes.py | 159 ++++++++++++++++++++++++ napalm_windows/system_identity.py | 11 +- tests/fixtures/synthetic/processes.json | 1 + tests/test_processes.py | 125 +++++++++++++++++++ 6 files changed, 311 insertions(+), 7 deletions(-) create mode 100644 napalm_windows/_reading.py create mode 100644 napalm_windows/processes.py create mode 100644 tests/fixtures/synthetic/processes.json create mode 100644 tests/test_processes.py diff --git a/napalm_windows/_reading.py b/napalm_windows/_reading.py new file mode 100644 index 0000000..8d5daba --- /dev/null +++ b/napalm_windows/_reading.py @@ -0,0 +1,18 @@ +"""One reading script's JSON object, which the host readings of this driver share.""" + +from __future__ import annotations + +import json +from typing import Any + + +def json_object(out: str, what: str) -> dict[str, Any]: + """*out*, a script's ``ConvertTo-Json`` of one object, parsed. + + :raises ValueError: when it is empty or no object, naming *what* was read. + """ + out = out.strip() + raw = json.loads(out) if out else None + if not isinstance(raw, dict): + raise ValueError(f"the {what} reading came back empty") + return raw diff --git a/napalm_windows/host_basics.py b/napalm_windows/host_basics.py index 694e6d0..c520468 100644 --- a/napalm_windows/host_basics.py +++ b/napalm_windows/host_basics.py @@ -3,12 +3,14 @@ One mixin made of one module per reading, so the driver names a single base: * :mod:`napalm_windows.system_identity` -- ``get_system_identity`` +* :mod:`napalm_windows.processes` -- ``get_processes`` """ from __future__ import annotations +from napalm_windows.processes import WindowsProcessesMixin from napalm_windows.system_identity import WindowsSystemIdentityMixin -class WindowsHostBasicsMixin(WindowsSystemIdentityMixin): +class WindowsHostBasicsMixin(WindowsSystemIdentityMixin, WindowsProcessesMixin): """The readings napalm-linux has as a matter of course; each module documents its own.""" diff --git a/napalm_windows/processes.py b/napalm_windows/processes.py new file mode 100644 index 0000000..b607e0c --- /dev/null +++ b/napalm_windows/processes.py @@ -0,0 +1,159 @@ +"""Running processes on Windows, shaped like ``ps`` output (NetOrk/netork#2889). + +:class:`WindowsProcessesMixin` gives the driver napalm-device-types' ``get_processes`` +(``ProcessDict``). One script reads two sources and the join happens here: + +* ``Win32_Process``: PID, parent, command line, start (``CreationDate``), the CPU time + (``KernelModeTime`` + ``UserModeTime``, in 100 ns), ``WorkingSetSize`` and + ``VirtualSize``. Read first: it is the list. +* ``Get-Process -IncludeUserName``: the owner, one call for all processes instead of a + ``GetOwner()`` per process. It needs an elevated session, which netOrk's WinRM + administrator has; without one the script falls back to ``Get-Process`` and the owner + is unknown (empty). + +A process is reported only when both saw it with the same start: one that exited between +the two reads is dropped rather than half-filled, and a PID reused in between is another +process. PID 0, the System Idle Process, is no process and is left out, as ``ps`` leaves +it out. + +The values follow ``ps``: ``cpu`` is the CPU time over the time since the start, per +logical processor, so 0-100; ``memory`` the working set over the visible memory; +``vsz`` and ``rss`` in KiB; ``started`` as ``lstart`` prints it, in the host's local +time. Windows has no controlling terminal and no process state of that kind: ``tty`` +and ``state`` are empty. A process without a readable command line (``System``, +protected processes) shows its image name. Command lines are reported as the host +gives them, as ``ps`` does on Linux. +""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta +from typing import TYPE_CHECKING, Any + +from napalm_device_types.models import ProcessDict + +from napalm_windows._powershell import _as_list +from napalm_windows._reading import json_object + +_PS_PROCESSES = r""" +$ErrorActionPreference = 'Stop' +function Unix($t) { if ($t) { ([DateTimeOffset]$t).ToUnixTimeSeconds() } else { $null } } +function Offset($t) { if ($t) { [int]([DateTimeOffset]$t).Offset.TotalMinutes } else { 0 } } +$os = Get-CimInstance -ClassName Win32_OperatingSystem +$cs = Get-CimInstance -ClassName Win32_ComputerSystem +$processes = @(Get-CimInstance -ClassName Win32_Process | ForEach-Object { + [pscustomobject]@{ + pid = [int]$_.ProcessId + ppid = [int]$_.ParentProcessId + name = [string]$_.Name + command = [string]$_.CommandLine + started = Unix $_.CreationDate + offset = Offset $_.CreationDate + cpu = [int64]$_.KernelModeTime + [int64]$_.UserModeTime + ws = [int64]$_.WorkingSetSize + vsz = [int64]$_.VirtualSize + } +}) +try { $running = @(Get-Process -IncludeUserName) } catch { $running = @(Get-Process) } +$owners = @($running | ForEach-Object { + $start = $null + try { $start = Unix $_.StartTime } catch { } + [pscustomobject]@{ pid = [int]$_.Id; user = [string]$_.UserName; started = $start } +}) +ConvertTo-Json -Compress -Depth 3 -InputObject ([pscustomobject]@{ + now = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds() + cores = [int]$cs.NumberOfLogicalProcessors + memory_kib = [int64]$os.TotalVisibleMemorySize + processes = $processes + owners = $owners +}) +""" + +#: How far the two sources' starts of one process may differ: they round differently. +_SAME_START = 2 +_DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") +_MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") + + +def _lstart(started: int | None, offset_minutes: int) -> str: + """Unix time in the host's local time, as ``ps -o lstart`` prints it in the C locale.""" + if started is None: + return "" + t = datetime.fromtimestamp(started, UTC) + timedelta(minutes=offset_minutes) + return f"{_DAYS[t.weekday()]} {_MONTHS[t.month - 1]} {t.day:2d} {t:%H:%M:%S} {t.year}" + + +class _Host: + """What the reading says about the host as a whole.""" + + def __init__(self, raw: dict[str, Any]) -> None: + self.now = int(raw.get("now") or 0) + self.cores = max(int(raw.get("cores") or 1), 1) + self.memory_kib = int(raw.get("memory_kib") or 0) + + def cpu(self, cpu_100ns: int, started: int | None) -> float: + if started is None: + return 0.0 + elapsed = max(self.now - started, 1) + return round(min(cpu_100ns / 10_000_000 / elapsed / self.cores * 100, 100.0), 1) + + def memory(self, rss_kib: int) -> float: + return round(rss_kib * 100 / self.memory_kib, 1) if self.memory_kib else 0.0 + + +def _started(entry: dict[str, Any]) -> int | None: + value = entry.get("started") + return int(value) if value is not None else None + + +def _same_process(entry: dict[str, Any], owner: dict[str, Any]) -> bool: + """False when ``Get-Process`` saw another start under this PID: it was reused.""" + ours, theirs = _started(entry), _started(owner) + return ours is None or theirs is None or abs(ours - theirs) <= _SAME_START + + +def _process(entry: dict[str, Any], owner: dict[str, Any], host: _Host) -> ProcessDict: + started = _started(entry) + rss = int(entry.get("ws") or 0) // 1024 + return { + "pid": int(entry["pid"]), + "ppid": int(entry.get("ppid") or 0), + "user": str(owner.get("user") or ""), + "cpu": host.cpu(int(entry.get("cpu") or 0), started), + "memory": host.memory(rss), + "vsz": int(entry.get("vsz") or 0) // 1024, + "rss": rss, + "tty": "", + "state": "", + "started": _lstart(started, int(entry.get("offset") or 0)), + "command": str(entry.get("command") or entry.get("name") or ""), + } + + +def parse_processes(raw: dict[str, Any]) -> list[ProcessDict]: + """``_PS_PROCESSES``'s JSON as ``ProcessDict``s by PID; see the module for the join.""" + host = _Host(raw) + owners = {int(o["pid"]): o for o in _as_list(raw.get("owners"))} + processes = [] + for entry in _as_list(raw.get("processes")): + owner = owners.get(int(entry["pid"])) + if not entry["pid"] or owner is None or not _same_process(entry, owner): + continue + processes.append(_process(entry, owner, host)) + return sorted(processes, key=lambda p: p["pid"]) + + +class WindowsProcessesMixin: + """``get_processes`` from ``Win32_Process`` and ``Get-Process``; the driver carries + the script.""" + + if TYPE_CHECKING: # pragma: no cover - declared for type checkers only + + def _run_raw(self, script: str) -> str: ... + + def get_processes(self) -> list[ProcessDict]: + """A snapshot of the running processes, shaped like ``ps``; see the module. + + :raises ValueError: when the reading came back empty. + """ + return parse_processes(json_object(self._run_raw(_PS_PROCESSES), "process")) diff --git a/napalm_windows/system_identity.py b/napalm_windows/system_identity.py index f2c85a6..aeb6827 100644 --- a/napalm_windows/system_identity.py +++ b/napalm_windows/system_identity.py @@ -18,13 +18,14 @@ Vendor placeholders ("To be filled by O.E.M.", all-F UUIDs) read as empty from __future__ import annotations -import json from datetime import UTC, datetime from typing import TYPE_CHECKING, Any from napalm_device_types import clean_system_identity from napalm_device_types.system_identity import SystemIdentityDict +from napalm_windows._reading import json_object + _PS_SYSTEM_IDENTITY = r""" $ErrorActionPreference = 'Stop' $product = Get-CimInstance -ClassName Win32_ComputerSystemProduct @@ -79,8 +80,6 @@ class WindowsSystemIdentityMixin: :raises ValueError: when the reading came back empty. """ - out = self._run_raw(_PS_SYSTEM_IDENTITY).strip() - raw = json.loads(out) if out else None - if not isinstance(raw, dict): - raise ValueError("the system identity reading came back empty") - return parse_system_identity(raw) + return parse_system_identity( + json_object(self._run_raw(_PS_SYSTEM_IDENTITY), "system identity") + ) diff --git a/tests/fixtures/synthetic/processes.json b/tests/fixtures/synthetic/processes.json new file mode 100644 index 0000000..f7eeb34 --- /dev/null +++ b/tests/fixtures/synthetic/processes.json @@ -0,0 +1 @@ +{"now":1764590400,"cores":4,"memory_kib":8388608,"processes":[{"pid":0,"ppid":0,"name":"System Idle Process","command":"","started":null,"offset":0,"cpu":4000000000000,"ws":8192,"vsz":8192},{"pid":4,"ppid":0,"name":"System","command":"","started":null,"offset":0,"cpu":12000000000,"ws":143360,"vsz":3997696},{"pid":812,"ppid":640,"name":"svchost.exe","command":"C:\\Windows\\system32\\svchost.exe -k DcomLaunch -p","started":1764504000,"offset":60,"cpu":3456000000,"ws":31457280,"vsz":2203318222848},{"pid":4312,"ppid":3988,"name":"powershell.exe","command":"\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -NoLogo","started":1764589800,"offset":60,"cpu":1200000000,"ws":104857600,"vsz":2203500000000},{"pid":5120,"ppid":812,"name":"WmiPrvSE.exe","command":"C:\\Windows\\system32\\wbem\\wmiprvse.exe","started":1764590395,"offset":60,"cpu":1000000,"ws":10485760,"vsz":2203400000000},{"pid":6000,"ppid":812,"name":"conhost.exe","command":"\\??\\C:\\Windows\\system32\\conhost.exe 0x4","started":1764590370,"offset":60,"cpu":0,"ws":4194304,"vsz":2203300000000}],"owners":[{"pid":0,"user":null,"started":null},{"pid":4,"user":"NT AUTHORITY\\SYSTEM","started":null},{"pid":812,"user":"NT AUTHORITY\\SYSTEM","started":1764504000},{"pid":4312,"user":"WIN01\\admin","started":1764589800},{"pid":6000,"user":"WIN01\\admin","started":1764590398},{"pid":7777,"user":"WIN01\\admin","started":1764590399}]} diff --git a/tests/test_processes.py b/tests/test_processes.py new file mode 100644 index 0000000..60a3881 --- /dev/null +++ b/tests/test_processes.py @@ -0,0 +1,125 @@ +"""Processes on Windows: ``Win32_Process`` joined with ``Get-Process`` (NetOrk/netork#2889). + +One script reads both; a fake transport answers it from +tests/fixtures/synthetic/processes.json. ``Win32_Process`` gives the parent, the command +line, the start and the CPU and memory counters, ``Get-Process -IncludeUserName`` the +owner. The fixture holds the cases the join decides: + +* 0, the System Idle Process: no process, left out as ``ps`` leaves it out; +* 5120, gone by the time ``Get-Process`` ran: dropped, not half-filled; +* 6000, a PID ``Get-Process`` reports with another start: a new process under a PID + that was reused between the two reads, dropped; +* 7777, started after ``Win32_Process`` was read: not part of the reading. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from napalm_windows import WindowsDriver +from napalm_windows import processes as mod + +FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "processes.json" + + +class FakeTransport: + def __init__(self, answer: str) -> None: + self.answer = answer + self.sent: list[str] = [] + self.is_open = True + + def run(self, script: str) -> str: + self.sent.append(script) + return self.answer + + +def _reading() -> dict[str, Any]: + return json.loads(FIXTURE.read_text()) + + +def _driver(reading: dict[str, Any] | None = None) -> WindowsDriver: + d = WindowsDriver("win01", "admin", "secret") + d._transport = FakeTransport(json.dumps(reading if reading is not None else _reading())) + return d + + +def _by_pid(reading: dict[str, Any] | None = None) -> dict[int, Any]: + return {p["pid"]: p for p in _driver(reading).get_processes()} + + +def test_the_join_keeps_the_processes_both_reads_saw(): + assert sorted(_by_pid()) == [4, 812, 4312] + + +def test_a_process_reads_like_ps(): + assert _by_pid()[4312] == { + "pid": 4312, + "ppid": 3988, + "user": "WIN01\\admin", + # 120 CPU seconds in 600 s on 4 logical processors + "cpu": 5.0, + # 100 MiB of 8 GiB + "memory": 1.2, + "vsz": 2203500000000 // 1024, + "rss": 102400, + "tty": "", + "state": "", + # 11:50 UTC, an hour east of it + "started": "Mon Dec 1 12:50:00 2025", + "command": '"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" -NoLogo', + } + + +def test_a_process_without_a_command_line_shows_its_name(): + system = _by_pid()[4] + assert system["command"] == "System" + assert system["started"] == "" + assert system["cpu"] == 0.0 + + +def test_a_start_one_second_apart_is_the_same_process(): + # Get-Process and CIM round the start differently. + reading = _reading() + reading["owners"][2]["started"] += 1 + assert 812 in _by_pid(reading) + + +def test_without_elevation_the_owner_is_unknown(): + # Get-Process -IncludeUserName needs an elevated session; the script falls back. + reading = _reading() + for owner in reading["owners"]: + owner.pop("user") + assert {p["user"] for p in _by_pid(reading).values()} == {""} + + +def test_cpu_stays_within_a_hundred_percent(): + reading = _reading() + reading["processes"][3]["cpu"] = 10**13 + assert _by_pid(reading)[4312]["cpu"] == 100.0 + + +def test_a_single_process_survives_powershells_unwrapping(): + reading = _reading() + reading["processes"] = reading["processes"][2] + reading["owners"] = reading["owners"][2] + assert sorted(_by_pid(reading)) == [812] + + +def test_one_script_reads_both_sources(): + d = _driver() + d.get_processes() + (script,) = d._transport.sent # type: ignore[union-attr] + assert script == mod._PS_PROCESSES + assert "Win32_Process" in script + assert "Get-Process -IncludeUserName" in script + + +def test_an_empty_answer_is_no_reading(): + d = WindowsDriver("win01", "admin", "secret") + d._transport = FakeTransport("") + with pytest.raises(ValueError): + d.get_processes()