Author SHA1 Message Date
Christian Manivong 4108581580 feat(updates): Windows Update -- search, pending updates, install in a SYSTEM task, history (NetOrk/netork#2892)
refresh_available_updates runs the Windows Update Agent's search against the
configured source and keeps its reading under HKLM\SOFTWARE\napalm-windows;
get_available_updates reads it back without a search, leaving out what the
history shows installed since, and raises PackageIndexMissing before the
first search. Each update carries its title, KB articles, CveIDs and
MsrcSeverity, and is named by its title without month, KB and version, so
next month's cumulative update keeps the name. Previews, feature upgrades and
drivers are left out.

apply_updates installs in a one-shot task running as SYSTEM, since Windows
refuses downloads and installs to a network logon. The task's script and the
exact UpdateID:revision chosen travel in the run's registry key; it searches
again, refuses what no longer matches exactly, what asks for input or has
unaccepted licence terms, installs nothing while a restart is pending and
never restarts. Its log is followed line by line; the next run sweeps what a
dead run left. get_scheduled_jobs shows these tasks as an application's.

get_update_history reads QueryHistory, one transaction per entry, with the
ClientApplicationID as requested_by.
2026-12-01 12:57:20 +01:00
23 changed files with 1533 additions and 1187 deletions

No files matched your search

+13 -17
View File
@@ -7,23 +7,19 @@ All notable changes to this driver. The format follows
## [Unreleased]
### Added
- What the event log recorded that says something is wrong with the host
(NetOrk/netork#2897): `get_host_events(since=None)`, napalm-device-types'
`HostEventsMixin`. Unexpected shutdowns (Kernel-Power 41, EventLog 6008), bugchecks
with their stop code (1001), fatal and corrected hardware errors (WHEA-Logger 18, 19,
47), disk and file system errors (disk 7 and 153, Ntfs 55), crashing programs
(Application Error 1000) and services that ended unexpectedly (Service Control
Manager 7031, 7034), over the last seven days by default, in one script of three
queries bounded by time and count. An empty log is no events, not an error
(`NoMatchingEventsFound` is caught); a query that fails names its kinds `unread`.
- The event channels as the host's log sources: `get_log_sources()` lists every channel
that is switched on and holds records as a source of kind `eventlog`, named by its
channel, with its `.evtx` file, size and last write (`Get-WinEvent -ListLog *`).
Analytic and debug channels are left out.
- `get_services()` says how each service's last run ended (`result`, `exit_code`, from
`Win32_Service.ExitCode` and `ServiceSpecificExitCode`), whether a trigger starts it
(`trigger_start`) and the account it runs as (`account`), so that an automatic service
that died is told from one stopped on purpose. It moves into `WindowsServicesMixin`.
- Windows Update (NetOrk/netork#2892). A refresh searches the update source the host is
configured for (Windows Update or its WSUS server) and keeps what it found on the host;
the pending updates are read from that, so a poll never waits minutes for a search.
Each pending update carries its title, KB articles, the CVEs it fixes and Microsoft's
severity rating, and is named so that next month's cumulative update keeps the same
name. Optional previews, feature upgrades and drivers are left out.
- Installing Windows updates (NetOrk/netork#2892): Windows does not let a remote session
install updates, so each run is a one-shot task running as SYSTEM. It installs only the
exact updates chosen, refuses one that is no longer offered, asks for input or has
licence terms not yet accepted, installs nothing while a restart is pending, and never
restarts the host. Its output arrives line by line; the task is deleted afterwards.
- The update history: what Windows Update installed or removed, when, which component
asked for it, and why it failed.
- Restarting and shutting the host down (NetOrk/netork#2841): `reboot_host()` and
`shutdown_host()` from napalm-device-types' `HostRebootMixin` and `HostShutdownMixin`
run `Restart-Computer` and `Stop-Computer` over the PSRP connection, neither with
+42 -33
View File
@@ -36,14 +36,15 @@ handshake once.
| `get_interfaces_ip` | `Get-NetIPAddress` (loopback dropped, IPv6 zone index stripped) |
| `get_arp_table` | `Get-NetNeighbor -AddressFamily IPv4` (broadcast, multicast, unreachable dropped) |
| `get_route_to` | `Get-NetRoute` (multicast, broadcast, loopback dropped) |
| `get_services` / `manage_service` | `Win32_Service` (with `ExitCode`, `StartName`) and the services' `TriggerInfo` registry keys, `Start-/Stop-/Restart-Service`, `Set-Service -StartupType`. See *Services* |
| `get_services` / `manage_service` | `Win32_Service`, `Start-/Stop-/Restart-Service`, `Set-Service -StartupType` |
| `reboot_host` / `shutdown_host` | `Restart-Computer`, `Stop-Computer`, neither with `-Force`: programs are asked to close, and Windows refuses while other users are logged on. A connection the host drops before answering counts as accepted |
| `get_listening_sockets` | `Get-NetTCPConnection -State Listen`, `Get-NetUDPEndpoint`, `Get-Process`, `Win32_Service` (a shared svchost names no service) |
| `get_scheduled_jobs` | `Get-ScheduledTask` + `Get-ScheduledTaskInfo`, one script; `\Microsoft\*` is `platform`, other tasks `admin`, the root task an application wrote `application`; time zone mapped to IANA for the common zones |
| `manage_scheduled_job` | `Enable-`/`Disable-ScheduledTask`, `Start-ScheduledTask` (returns once started; the result shows in the next reading) |
| `put_scheduled_job` / `delete_scheduled_job` | `Register-ScheduledTask -Xml -Force` in the root folder, `Unregister-ScheduledTask`; an application's tasks only |
| `get_host_events` | `Get-WinEvent -FilterXPath`, three bounded queries over the System and Application logs. See *Host events* |
| `get_log_sources` | `Get-WinEvent -ListLog *`: every event channel switched on and holding records, as kind `eventlog` |
| `refresh_available_updates` / `get_available_updates` | The Windows Update Agent's search (`Microsoft.Update.Session`), kept in the registry for the poll; the host's update history leaves out what was installed since. See *Windows Update* |
| `apply_updates` | A one-shot SYSTEM scheduled task that searches again and installs only the exact updates chosen; never restarts. See *Windows Update* |
| `get_update_history` | `IUpdateSearcher.QueryHistory`, the newest 300 entries |
| `get_time_sync` / `configure_time_sync` | w32time's registry values (group policy first), `w32tm /query /status`, the registry's `TimeZoneInformation`; writes `NtpServer`/`Type` + `w32tm /config /update`, `Set-TimeZone`. See *Time sync* |
`running_kernel` carries the full build including the update revision
@@ -99,39 +100,47 @@ napalm-device-types' `TimeSyncMixin`; both the servers and the zone are written.
zone with summer time switched off reads as `None`; writing the zone switches it
back on.
### Services
### Windows Update
How a service's last run ended is `Win32_Service.ExitCode`, said in systemd's words
(napalm-device-types' `ServiceDict.result`): `0` is `success`, `1077` (never started
since boot: a demand-start service, or a delayed one in the minutes after boot) is no
result, `1066` is `exit-code` with the service's own `ServiceSpecificExitCode`, any
other code `exit-code` with that code (`1067`: the process ended without being
stopped). Both codes leave the host as `[int64]`: they are UInt32, and an HRESULT
would not fit `[int]`. `trigger_start` is a `TriggerInfo` key under the service, read
once for all of them; `account` is `StartName`.
napalm-device-types' `UpdateMixin`, through the Windows Update Agent's COM API.
### Host events
* **The search is the refresh.** `refresh_available_updates` searches the source the
host is configured for -- Windows Update, or the WSUS server group policy names --
for `IsInstalled=0 and IsHidden=0 and Type='Software'`: no drivers. A search takes
minutes, so the poll never runs one. It keeps its reading under
`HKLM\SOFTWARE\napalm-windows\WindowsUpdate` (only administrators and SYSTEM may write
there), and `get_available_updates` reads that back, leaving out what the host's
history shows installed since. Before the first search it raises
`PackageIndexMissing`, which a refresh cures.
* **Names.** An update is named by what it keeps from month to month: its title without
the month, the KB article and the version, as a package name
(`Cumulative-Update-for-Microsoft-server-operating-system-version-21H2-for-x64-based-Systems`).
Next month's cumulative update takes this one's place under the same name, so the time
a host has waited for it is not reset each month. `new_version` and `advisories` are
its KB articles, `cves` its `CveIDs`, `vendor_severity` its `MsrcSeverity`, `title`
its title. A security update, a definition update or one naming CVEs is `security`;
another classified one is not.
* **Not pending:** optional updates (`BrowseOnly`: previews Windows does not install by
itself) and feature upgrades -- this path installs neither.
* **Installing** (`apply_updates`). Windows refuses a download or an install to a
network logon (`E_ACCESSDENIED`), so a run is a one-shot task
`\napalm-windows\update-run-<id>` running as SYSTEM. Its script and the exact updates
chosen (`<UpdateID>:<revision>`, those the last search found under each name) go into
the run's registry key; no file is written. The task searches again and refuses, by
name, an update no longer offered under that ID and revision, one offered twice, one
that asks for input while it installs (`CanRequestUserInput`), and one whose licence
terms the host has not accepted; while a restart is pending it installs nothing. It
never restarts the host. The driver follows the run's log every 5 seconds and hands each
line to `log`, then deletes the task and the key. The tasks and keys of runs whose
connection died are deleted by the next run, which refuses to start while one is still
installing; a run followed for 25 minutes is left to finish on the host. The task names
itself to Windows Update as `napalm-windows`, which the history's `requested_by`
shows. `get_scheduled_jobs` reports these tasks as an application's, offering nothing.
* **History** (`get_update_history`): `QueryHistory`, newest 300 entries, one transaction
each; `requested_by` is the `ClientApplicationID` (`UpdateOrchestrator`,
`AutomaticUpdates`, `napalm-windows`), `error` the result and its HRESULT.
napalm-device-types' `HostEventsMixin`: what the event log recorded that says
something is wrong with the host, over the last seven days unless the caller names a
start. One script, three queries, each an XPath filter from the start on, newest
first and bounded by count:
| Query | Events | Bound |
|---|---|---|
| System, with messages | Kernel-Power 41 and EventLog 6008 (unexpected shutdown; 41's `BugcheckCode` as the stop code), WER-SystemErrorReporting 1001 (bugcheck, its stop code), WHEA-Logger 18 (fatal hardware error), disk 7 (bad block), Ntfs 55 (corruption, its volume) | 100 |
| System, without messages | WHEA-Logger 19 and 47 (corrected hardware errors), disk 153 (retried I/O, its disk), Service Control Manager 7031 and 7034 (a service that ended unexpectedly, its display name) | 500 |
| Application, without messages | Application Error 1000 (a program that crashed, its path) | 200 |
`Get-WinEvent` throws `NoMatchingEventsFound` when nothing matches; each query
catches it as no events, and any other failure costs only that query, whose kinds the
reading names `unread`. A query that returned its bound names its kinds `capped`.
What an event is about comes from its properties, never from its message, which is in
the host's language; messages are read only for the rare events (Windows formats them
slowly) and cut to 300 characters. Which of them is worth a warning is the
application's to say.
Not yet: packages, Windows Update, health metrics, Hyper-V.
Not yet: packages, health metrics, Hyper-V.
See netork#300 for the plan.
## Preparing a host
-85
View File
@@ -1,85 +0,0 @@
"""The event channels as the host's log sources (NetOrk/netork#2897).
:class:`WindowsLogSourcesMixin` gives the driver ``get_log_sources`` in napalm-device-types'
shape (``LogSourcesDict``). A Windows host keeps no journal and its programs hold no log
files a reader could name: its logs are its event channels, each a source of kind
``eventlog`` named by its channel -- the name CrowdSec (``event_channel``) and Wazuh
(``eventchannel``) read it by -- with its ``.evtx`` file as ``path``.
One script, ``Get-WinEvent -ListLog *``: every channel that is switched on and holds
records, with its file (``%SystemRoot%`` expanded), size, last write and type. A channel
the account may not open is skipped, not the reading. Analytic and debug channels are
trace sessions written to ``.etl`` files, which a log reader cannot follow, and are left
out. WinRM needs an administrator, who may open every other channel, the Security log
included, so the reading is ``attributed``. Where the logs go beyond the host (Windows
Event Forwarding, an agent) is not read: ``forwarding`` is None.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from napalm_device_types import LogSourceDict, LogSourcesDict, eventlog_source
from napalm_windows._powershell import _as_list
_PS_EVENT_CHANNELS = r"""
$ErrorActionPreference = 'Stop'
ConvertTo-Json -Compress -Depth 3 -InputObject @(
Get-WinEvent -ListLog * -ErrorAction SilentlyContinue |
Where-Object { $_.IsEnabled -and $_.RecordCount } |
ForEach-Object {
[pscustomobject]@{
channel = $_.LogName
path = [Environment]::ExpandEnvironmentVariables([string]$_.LogFilePath)
size = $_.FileSize
modified = if ($_.LastWriteTime) {
([DateTimeOffset]$_.LastWriteTime).ToUnixTimeSeconds()
} else { $null }
records = $_.RecordCount
type = [string]$_.LogType
}
}
)
"""
#: Trace sessions, not logs: written to .etl files a reader cannot follow.
_TRACE_TYPES = frozenset({"analytic", "debug"})
def _is_log(raw: dict[str, Any]) -> bool:
return (
bool(raw.get("channel"))
and int(raw.get("records") or 0) > 0
and str(raw.get("type") or "").lower() not in _TRACE_TYPES
)
def _source(raw: dict[str, Any]) -> LogSourceDict:
size, modified = raw.get("size"), raw.get("modified")
return eventlog_source(
str(raw["channel"]),
str(raw["path"]) if raw.get("path") else None,
None if size is None else int(size),
None if modified is None else float(modified),
)
class WindowsLogSourcesMixin:
"""``get_log_sources``: the host's event channels; the driver carries the script."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_ps(self, script: str) -> Any: ...
def get_log_sources(self) -> LogSourcesDict:
"""Every event channel that is switched on and holds records, sorted by name.
* attributed (bool) - always True: an administrator opens every channel
* journald (bool) - always False: Windows keeps event channels, not a journal
* sources (list) - one ``eventlog`` source per channel
* forwarding - None: where the logs go beyond the host is not read
"""
channels = [c for c in _as_list(self._run_ps(_PS_EVENT_CHANNELS)) if _is_log(c)]
sources = sorted((_source(c) for c in channels), key=lambda s: s.get("channel", ""))
return {"attributed": True, "journald": False, "sources": sources, "forwarding": None}
-254
View File
@@ -1,254 +0,0 @@
"""What the event log recorded that says something is wrong with the host (NetOrk/netork#2897).
:class:`WindowsHostEventsMixin` implements napalm-device-types'
:class:`~napalm_device_types.host_events.HostEventsMixin` for the driver, which carries
the script across ``PsrpTransport.run``.
**One script, three queries**, each an XPath filter over a fixed set of providers and
event IDs, from the reading's start (``TimeCreated[@SystemTime>=…]``), newest first and
bounded by count:
* *rare*, the System log, with each event's message: Kernel-Power 41 and EventLog 6008
(an unexpected shutdown; 41's first property is the bugcheck code, 0 for a power loss),
WER-SystemErrorReporting 1001 (a bugcheck, its stop code first), WHEA-Logger 18 (a
fatal hardware error), disk 7 (a bad block) and Ntfs 55 (a corruption);
* *frequent*, the System log without messages, which Windows formats slowly: WHEA-Logger
19 and 47 (corrected hardware errors), disk 153 (a retried I/O) and Service Control
Manager 7031 and 7034 (a service that ended unexpectedly);
* *apps*, the Application log without messages: Application Error 1000 (a program that
crashed, its path the eleventh property).
``Get-WinEvent`` throws ``NoMatchingEventsFound`` when nothing matches, and under
``$ErrorActionPreference = 'Stop'`` that would fail the whole reading: each query
catches it as no events. Any other failure costs only that query, whose kinds the
reading names ``unread``; a query that returned its bound names its kinds ``capped``.
**What an event is about** is taken from its properties, which do not depend on the
host's language, never from its message, which does: the stop code, the disk or volume,
the program's path (its name on a Windows that records no path), the service's display
name. The message is kept as the host wrote it, cut short.
"""
from __future__ import annotations
import time
from collections.abc import Callable
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
from napalm_device_types import HOST_EVENT_KINDS, HostEventDict, HostEventsDict, HostEventsMixin
from napalm_device_types import host_event as _event
from napalm_device_types.host_events import (
APP_CRASH,
DISK_ERROR,
HARDWARE_ERROR_CORRECTED,
HARDWARE_ERROR_FATAL,
HOST_EVENT_MESSAGE_CHARS,
HOST_EVENT_WINDOW_DAYS,
SERVICE_CRASH,
SYSTEM_CRASH,
UNEXPECTED_SHUTDOWN,
)
from napalm_windows._powershell import _as_list
_KERNEL_POWER = "Microsoft-Windows-Kernel-Power"
_BUGCHECK = "Microsoft-Windows-WER-SystemErrorReporting"
_WHEA = "Microsoft-Windows-WHEA-Logger"
_SCM = "Service Control Manager"
_APP_ERROR = "Application Error"
def _bugcheck(props: list[str]) -> str | None:
"""Kernel-Power 41's ``BugcheckCode``, a decimal number, as a stop code; 0 is none."""
word = props[0].strip() if props else ""
return f"0x{int(word):08x}" if word.isdigit() and int(word) else None
def _stop_code(props: list[str]) -> str | None:
"""1001's first property: ``0x0000009f (0x…, 0x…, 0x…, 0x…)``."""
word = props[0].split(maxsplit=1)[0] if props and props[0].strip() else ""
return word or None
def _first(props: list[str]) -> str | None:
return props[0] if props else None
def _program(props: list[str]) -> str | None:
"""Application Error 1000: its path where the host records one, else its name."""
path = props[10] if len(props) > 10 else ""
return path.strip() or _first(props)
def _none(props: list[str]) -> str | None:
return None
_Subject = Callable[[list[str]], str | None]
#: (provider, event ID) -> the kind and what the event is about.
_EVENTS: dict[tuple[str, int], tuple[str, _Subject]] = {
(_KERNEL_POWER, 41): (UNEXPECTED_SHUTDOWN, _bugcheck),
("EventLog", 6008): (UNEXPECTED_SHUTDOWN, _none),
(_BUGCHECK, 1001): (SYSTEM_CRASH, _stop_code),
(_WHEA, 18): (HARDWARE_ERROR_FATAL, _none),
(_WHEA, 19): (HARDWARE_ERROR_CORRECTED, _none),
(_WHEA, 47): (HARDWARE_ERROR_CORRECTED, _none),
("disk", 7): (DISK_ERROR, _first),
("disk", 153): (DISK_ERROR, _first),
("Microsoft-Windows-Ntfs", 55): (DISK_ERROR, _first),
("Ntfs", 55): (DISK_ERROR, _first),
(_SCM, 7031): (SERVICE_CRASH, _first),
(_SCM, 7034): (SERVICE_CRASH, _first),
(_APP_ERROR, 1000): (APP_CRASH, _program),
}
#: Each query's log, its events, its bound and whether it reads their messages.
_QUERIES: dict[str, tuple[str, tuple[tuple[str, int], ...], int, bool]] = {
"rare": (
"System",
(
(_KERNEL_POWER, 41),
("EventLog", 6008),
(_BUGCHECK, 1001),
(_WHEA, 18),
("disk", 7),
("Microsoft-Windows-Ntfs", 55),
("Ntfs", 55),
),
100,
True,
),
"frequent": (
"System",
((_WHEA, 19), (_WHEA, 47), ("disk", 153), (_SCM, 7031), (_SCM, 7034)),
500,
False,
),
"apps": ("Application", ((_APP_ERROR, 1000),), 200, False),
}
#: The kinds each query reads, in the order of HOST_EVENT_KINDS.
_PART_KINDS: dict[str, tuple[str, ...]] = {
part: tuple(k for k in HOST_EVENT_KINDS if k in {_EVENTS[e][0] for e in events})
for part, (_log, events, _max, _message) in _QUERIES.items()
}
# Q runs one query: its events with their properties as strings, or why not.
# $_ inside catch is the error; NoMatchingEventsFound is an empty log, not a failure.
_PS_QUERY = rf"""
$ErrorActionPreference = 'Stop'
function Q($log, $xpath, $max, $withMessage) {{
try {{
$rows = @(Get-WinEvent -LogName $log -FilterXPath $xpath -MaxEvents $max | ForEach-Object {{
$m = $null
if ($withMessage) {{
try {{ $m = [string]$_.Message }} catch {{ $m = $null }}
if ($m.Length -gt {HOST_EVENT_MESSAGE_CHARS}) {{
$m = $m.Substring(0, {HOST_EVENT_MESSAGE_CHARS})
}}
}}
[pscustomobject]@{{
provider = $_.ProviderName
id = [int]$_.Id
time = ([DateTimeOffset]$_.TimeCreated).ToUnixTimeSeconds()
props = @($_.Properties | Select-Object -First 11 |
ForEach-Object {{ [string]$_.Value }})
message = $m
}}
}})
[pscustomobject]@{{ ok = $true; capped = ($rows.Count -ge $max); events = $rows }}
}} catch {{
if ([string]$_.FullyQualifiedErrorId -like 'NoMatchingEventsFound*') {{
[pscustomobject]@{{ ok = $true; capped = $false; events = @() }}
}} else {{
[pscustomobject]@{{
ok = $false; capped = $false; events = @(); error = [string]$_.Exception.Message
}}
}}
}}
}}
"""
def _xpath(events: tuple[tuple[str, int], ...], since: str) -> str:
which = " or ".join(f"(Provider[@Name='{p}'] and EventID={i})" for p, i in events)
return f"*[System[TimeCreated[@SystemTime>='{since}'] and ({which})]]"
def host_events_script(since: float) -> str:
"""The reading's script, from *since* (unix seconds) on."""
start = datetime.fromtimestamp(since, UTC).strftime("%Y-%m-%dT%H:%M:%S.000Z")
lines = [_PS_QUERY]
parts = []
for part, (log, events, bound, message) in _QUERIES.items():
lines.append(f'${part} = "{_xpath(events, start)}"')
parts.append(f" {part} = (Q '{log}' ${part} {bound} ${str(message).lower()})")
lines.append("[pscustomobject]@{ parts = [pscustomobject]@{")
lines.extend(parts)
lines.append("} } | ConvertTo-Json -Compress -Depth 6")
return "\n".join(lines) + "\n"
def _parse_event(raw: dict[str, Any], source_log: str) -> HostEventDict | None:
known = _EVENTS.get((str(raw.get("provider") or ""), int(raw.get("id") or 0)))
if known is None:
return None
kind, subject = known
props = [str(p) for p in _as_list(raw.get("props"))]
source = f"{source_log}: {raw.get('provider')} {raw.get('id')}"
return _event(kind, float(raw.get("time") or 0), source, subject(props), raw.get("message"))
def _part(answer: Any, log: str) -> list[HostEventDict] | None:
"""One query's events; None when it was not read."""
if not isinstance(answer, dict) or not answer.get("ok"):
return None
found = (_parse_event(e, log) for e in _as_list(answer.get("events")))
return [e for e in found if e is not None]
def _in_order(kinds: set[str]) -> list[str]:
return [k for k in HOST_EVENT_KINDS if k in kinds]
def _reading(raw: Any, since: float) -> HostEventsDict:
if not isinstance(raw, dict) or not isinstance(raw.get("parts"), dict):
raise ValueError("the host events reading came back without a report")
events: list[HostEventDict] = []
capped: set[str] = set()
unread: set[str] = set()
for part, (log, _events, _bound, _message) in _QUERIES.items():
answer = raw["parts"].get(part)
found = _part(answer, log)
if found is None:
unread.update(_PART_KINDS[part])
continue
if answer.get("capped"):
capped.update(_PART_KINDS[part])
events.extend(found)
events.sort(key=lambda e: e["time"], reverse=True)
return {
"since": datetime.fromtimestamp(since, UTC).isoformat(),
"events": events,
"capped": _in_order(capped),
"unread": _in_order(unread),
}
class WindowsHostEventsMixin(HostEventsMixin):
"""The event log's warnings-worthy events; the driver carries the script."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_ps(self, script: str) -> Any: ...
def get_host_events(self, since: float | None = None) -> HostEventsDict:
"""The events of ``HOST_EVENT_KINDS`` since *since* (unix seconds), by default
over the last ``HOST_EVENT_WINDOW_DAYS`` days; one round trip, see the module.
:raises ValueError: when the reading came back without a report.
"""
start = time.time() - HOST_EVENT_WINDOW_DAYS * 86400 if since is None else since
return _reading(self._run_ps(host_events_script(start)), start)
+19 -5
View File
@@ -9,9 +9,11 @@ says of its runs (``Get-ScheduledTaskInfo``), projected onto flat fields, and th
host's time zone; Python only normalises. Every task is a job ``task:<path><name>``
whose schedule is a summary of its triggers. A task under ``\\Microsoft\\`` is the
``platform``'s, any other the ``admin``'s -- Windows does not say which software
installed a task -- and a task in the root folder whose description starts with
``napalm-scheduled-job: <its name>`` is an ``application``'s, read back as the cron
expression and command it was written with (:mod:`napalm_windows.task_xml`). Its
installed a task -- except the driver's own Windows Update runs under
``\\napalm-windows\\``, an ``application``'s that offer nothing; and a task in the root
folder whose description starts with ``napalm-scheduled-job: <its name>`` is an
``application``'s, read back as the cron expression and command it was written with
(:mod:`napalm_windows.task_xml`). Its
digest covers its triggers as well, so triggers changed by hand are a change. A
reading whose task count does not match, or whose JSON is cut short, raises.
@@ -52,6 +54,7 @@ from napalm_windows._powershell import _as_list, _ps_quote
from napalm_windows.task_xml import JOB_MARKER, SCHEDULE_LINE, own_command, task_xml
from napalm_windows.time_zones import iana_time_zone
from napalm_windows.transport import PowerShellError
from napalm_windows.windows_update_run import TASK_PATH
# Every task with its run info. Times leave the host as ISO 8601 in UTC; a task
# whose run info cannot be read keeps its definition and loses only its times.
@@ -280,6 +283,8 @@ def _own(path: str, name: str, task: dict[str, Any]) -> _Own | None:
def _verbs(task: dict[str, Any], enabled: bool, own: bool) -> list[str]:
if str(task.get("path") or "").lower() == TASK_PATH.lower():
return [] # an update run's task: deleted when its run ends
verbs = ["enable", "disable"]
if enabled and task.get("on_demand") is not False:
verbs.append("run")
@@ -303,16 +308,25 @@ def _definition(path: str, task: dict[str, Any], triggers: str, own: _Own | None
return _Definition(
own.schedule or triggers, kind, own.command or command, "application", own.description
)
platform = path.lower().startswith("\\microsoft\\")
return _Definition(
triggers,
"triggers",
command,
"platform" if platform else "admin",
_owner(path),
str(task.get("description") or "").strip(),
)
def _owner(path: str) -> str:
"""Who a task that no application wrote as a job belongs to, by its folder: the
platform's under ``\\Microsoft\\``, the driver's own update runs' under
:data:`~napalm_windows.windows_update_run.TASK_PATH`, any other the admin's."""
folder = path.lower()
if folder == TASK_PATH.lower():
return "application"
return "platform" if folder.startswith("\\microsoft\\") else "admin"
def _task_job(task: dict[str, Any]) -> ScheduledJobDict:
path, name = str(task.get("path") or _ROOT), str(task.get("name") or "")
triggers = "; ".join(_trigger(t) for t in _as_list(task.get("triggers")))
-98
View File
@@ -1,98 +0,0 @@
"""The host's services, and how each one's last run ended (NetOrk/netork#2897).
:class:`WindowsServicesMixin` reads ``get_services`` for the driver, which carries
the script across ``PsrpTransport.run``.
One script: every ``Win32_Service`` with its state, start mode and process, the
account it runs as (``StartName``) and the code its last run ended with
(``ExitCode``). Both exit codes are UInt32 and leave the host as ``[int64]``, since
``[int]`` would throw on an HRESULT and fail the reading. Which services a trigger
starts (a device arriving, a network change, a request) is one registry read for all
of them: the ``TriggerInfo`` keys under ``HKLM:\\SYSTEM\\CurrentControlSet\\Services``.
**How the last run ended** is said in systemd's words (napalm-device-types'
``ServiceDict.result``), so that one rule reads it for every host:
* ``0`` is ``success``: running, or stopped on purpose.
* ``1077`` (``ERROR_SERVICE_NEVER_STARTED``) is no result: not started since the
host booted -- a demand-start service, or a delayed one in the minutes after boot.
* ``1066`` (``ERROR_SERVICE_SPECIFIC_ERROR``) is ``exit-code`` with the service's own
code, ``ServiceSpecificExitCode``.
* Any other code is ``exit-code`` with that code: ``1067`` is a process that ended
without being stopped.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from napalm_device_types import SERVICE_RESULT_EXIT_CODE, SERVICE_RESULT_SUCCESS, ServiceDict
from napalm_windows._powershell import _as_list
_PS_SERVICES = r"""
$ErrorActionPreference = 'Stop'
$triggered = @{}
$keys = 'HKLM:\SYSTEM\CurrentControlSet\Services\*\TriggerInfo'
Get-Item -Path $keys -ErrorAction SilentlyContinue |
ForEach-Object { $triggered[(Split-Path -Path $_.PSParentPath -Leaf)] = $true }
ConvertTo-Json -Compress -Depth 3 -InputObject @(
Get-CimInstance -ClassName Win32_Service | ForEach-Object {
[pscustomobject]@{
name = $_.Name
state = [string]$_.State
start_mode = [string]$_.StartMode
pid = [int]$_.ProcessId
exit_code = [int64]$_.ExitCode
service_code = [int64]$_.ServiceSpecificExitCode
account = $_.StartName
trigger_start = [bool]$triggered[$_.Name]
}
}
)
"""
_ENABLED_START_MODES = {"auto", "boot", "system"}
#: ``ERROR_SERVICE_NEVER_STARTED``: no attempt to start it since the host booted.
_NEVER_STARTED = 1077
#: ``ERROR_SERVICE_SPECIFIC_ERROR``: the code is the service's own.
_SERVICE_SPECIFIC = 1066
def _result(raw: dict[str, Any]) -> tuple[str | None, int | None]:
"""How the last run ended, and its code where that was not success."""
code = raw.get("exit_code")
if code is None or int(code) == _NEVER_STARTED:
return None, None
if int(code) == 0:
return SERVICE_RESULT_SUCCESS, None
if int(code) == _SERVICE_SPECIFIC and raw.get("service_code"):
return SERVICE_RESULT_EXIT_CODE, int(raw["service_code"])
return SERVICE_RESULT_EXIT_CODE, int(code)
def _service(raw: dict[str, Any]) -> ServiceDict:
running = str(raw.get("state") or "").lower() == "running"
result, exit_code = _result(raw)
return {
"name": str(raw["name"]),
"running": running,
"enabled": str(raw.get("start_mode") or "").lower() in _ENABLED_START_MODES,
"pid": int(raw.get("pid") or 0) if running else 0,
"result": result,
"exit_code": exit_code,
"trigger_start": bool(raw.get("trigger_start")),
"account": str(raw["account"]) if raw.get("account") else None,
}
class WindowsServicesMixin:
"""``get_services`` from ``Win32_Service``; the driver carries the script."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_ps(self, script: str) -> Any: ...
def get_services(self) -> list[ServiceDict]:
"""Every service with whether it runs, starts at boot, and how its last run ended."""
return [_service(s) for s in _as_list(self._run_ps(_PS_SERVICES))]
+32 -12
View File
@@ -24,15 +24,13 @@ from typing import Any
from napalm.base.exceptions import ConnectionClosedException
from napalm_device_types import FingerprintRule, OSDriver, PortSpec
from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict
from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict, ServiceDict
from napalm_windows._powershell import _as_list, _ps_quote
from napalm_windows.event_channels import WindowsLogSourcesMixin
from napalm_windows.host_events import WindowsHostEventsMixin
from napalm_windows.scheduled_tasks import WindowsScheduledJobsMixin
from napalm_windows.services import WindowsServicesMixin
from napalm_windows.time_sync import WindowsTimeSyncMixin
from napalm_windows.transport import PowerShellError, PsrpTransport
from napalm_windows.windows_update import WindowsUpdateMixin
logger = logging.getLogger(__name__)
@@ -126,6 +124,20 @@ ConvertTo-Json -Compress -Depth 3 -InputObject @(
)
"""
_PS_SERVICES = r"""
$ErrorActionPreference = 'Stop'
ConvertTo-Json -Compress -Depth 3 -InputObject @(
Get-CimInstance -ClassName Win32_Service | ForEach-Object {
[pscustomobject]@{
name = $_.Name
state = [string]$_.State
start_mode = [string]$_.StartMode
pid = [int]$_.ProcessId
}
}
)
"""
# Every listening TCP and bound UDP socket, the processes holding them and the
# services those processes run. Sockets owned by http.sys (WinRM, IIS) belong to
# the System process; a shared svchost runs several services in one process.
@@ -190,6 +202,7 @@ _ROUTE_PROTOCOLS = {
"rip": "rip",
}
_ENABLED_START_MODES = {"auto", "boot", "system"}
_DEAD_NEIGHBOUR_STATES = {"unreachable", "incomplete"}
@@ -249,14 +262,7 @@ def _is_noise_route(destination: str) -> bool:
# ---------------------------------------------------------------------------
class WindowsDriver(
WindowsScheduledJobsMixin,
WindowsTimeSyncMixin,
WindowsServicesMixin,
WindowsHostEventsMixin,
WindowsLogSourcesMixin,
OSDriver,
):
class WindowsDriver(WindowsScheduledJobsMixin, WindowsTimeSyncMixin, WindowsUpdateMixin, OSDriver):
"""NAPALM driver for Windows Server 2016+ and Windows 10/11.
``optional_args``:
@@ -484,6 +490,20 @@ class WindowsDriver(
# Services
# ------------------------------------------------------------------
def get_services(self) -> list[ServiceDict]:
services: list[ServiceDict] = []
for s in _as_list(self._run_ps(_PS_SERVICES)):
running = (s.get("state") or "").lower() == "running"
services.append(
{
"name": s["name"],
"running": running,
"enabled": (s.get("start_mode") or "").lower() in _ENABLED_START_MODES,
"pid": int(s.get("pid") or 0) if running else 0,
}
)
return services
def get_listening_sockets(self) -> ListeningSocketsDict:
"""Every listening TCP and bound UDP socket, with the process and the
Windows service behind it (``Get-NetTCPConnection``, ``Get-NetUDPEndpoint``,
+445
View File
@@ -0,0 +1,445 @@
"""Windows Update over PowerShell Remoting: search, pending updates, history (netork#2892).
:class:`WindowsUpdateMixin` implements napalm-device-types'
:class:`~napalm_device_types.updates.UpdateMixin` for the driver with the Windows Update
Agent's COM API (``Microsoft.Update.Session``).
**The search is the refresh.** ``refresh_available_updates`` searches the source the
host is configured for (Windows Update, or its WSUS server) for what is not installed
and not hidden, software only -- no drivers. A search takes minutes, so the poll never
runs one: the search keeps its reading in the registry (:data:`STORE`, under
``HKLM\\SOFTWARE``, where only administrators and SYSTEM may write), and
``get_available_updates`` reads it back, leaving out what the host's own history shows
installed since. Before the first search there is nothing to read from, which is
napalm-device-types' :exc:`PackageIndexMissing`: a refresh cures it.
**An update is named by what it keeps from month to month** (:func:`update_name`): its
title without the month, the KB article and the version. Next month's cumulative update
takes this one's place under the same name, so "pending since" is not reset every
month. The KB articles are the update's ``new_version`` and ``advisories``; its
``CveIDs`` and ``MsrcSeverity`` go along as ``cves`` and ``vendor_severity``. A security
update, a definition update or one naming CVEs is ``security``. Optional updates
(previews Windows does not install by itself) and feature upgrades are not pending:
this path installs neither.
**The history** is ``QueryHistory``, its newest 300 entries, one transaction each;
``requested_by`` is the ``ClientApplicationID`` that asked (``UpdateOrchestrator``,
``AutomaticUpdates``, ``napalm-windows`` for the driver's own runs).
**Installing** is :mod:`napalm_windows.windows_update_run`: Windows refuses a download
or an install over a network logon, so it runs in a one-shot SYSTEM task.
"""
from __future__ import annotations
import json
import re
import unicodedata
from collections.abc import Callable
from typing import TYPE_CHECKING, Any, NamedTuple
from napalm_device_types import PackageIndexMissing
from napalm_device_types.models import ApplyUpdatesResultDict, UpdateDict
from napalm_device_types.updates import UpdateHistoryDict, UpdateHistoryPackageDict, UpdateMixin
from napalm_windows._powershell import _as_list
from napalm_windows.transport import PowerShellError
from napalm_windows.windows_update_run import install
#: Where the search keeps its reading, and the runs theirs.
STORE = "HKLM:\\SOFTWARE\\napalm-windows\\WindowsUpdate"
#: What every search asks: not installed, not hidden, no drivers.
_CRITERIA = "IsInstalled=0 and IsHidden=0 and Type='Software'"
# The search, kept in STORE for the poll, and printed for the refresh. Its times are
# unix seconds; the WSUS server is named where group policy points the host at one.
_PS_WU_SEARCH = r"""
$ErrorActionPreference = 'Stop'
$started = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
$session = New-Object -ComObject Microsoft.Update.Session
$session.ClientApplicationID = 'napalm-windows'
$found = $session.CreateUpdateSearcher().Search("__CRITERIA__")
$rows = @(foreach ($u in $found.Updates) {
[pscustomobject]@{
id = [string]$u.Identity.UpdateID
revision = [int]$u.Identity.RevisionNumber
title = [string]$u.Title
kb = @(foreach ($k in $u.KBArticleIDs) { [string]$k })
cves = @(foreach ($c in $u.CveIDs) { [string]$c })
severity = [string]$u.MsrcSeverity
classifications = @(foreach ($c in $u.Categories) {
if ([string]$c.Type -eq 'UpdateClassification') { [string]$c.CategoryID }
})
browse_only = [bool]$u.BrowseOnly
interactive = [bool]$u.InstallationBehavior.CanRequestUserInput
reboot = [int]$u.InstallationBehavior.RebootBehavior
eula_accepted = [bool]$u.EulaAccepted
downloaded = [bool]$u.IsDownloaded
}
})
$policy = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate'
$wsus = $null
if ((Get-ItemProperty -ErrorAction SilentlyContinue -LiteralPath "$policy\AU").UseWUServer -eq 1) {
$wsus = [string](Get-ItemProperty -ErrorAction SilentlyContinue -LiteralPath $policy).WUServer
}
$reading = ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
searched_at = $started
finished_at = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
result = [int]$found.ResultCode
wsus = $wsus
updates = $rows
})
$store = '__STORE__'
if (-not (Test-Path -LiteralPath $store)) { New-Item -Path $store -Force | Out-Null }
Set-ItemProperty -LiteralPath $store -Name Search -Value $reading
$reading
""".replace("__CRITERIA__", _CRITERIA).replace("__STORE__", STORE)
# What the last search found, and what the host installed (by its history) -- no search.
_PS_WU_PENDING = r"""
$ErrorActionPreference = 'Stop'
$search = (Get-ItemProperty -ErrorAction SilentlyContinue -LiteralPath '__STORE__').Search
$installed = @()
$history_error = $null
if ($search) {
try {
$searcher = (New-Object -ComObject Microsoft.Update.Session).CreateUpdateSearcher()
$count = $searcher.GetTotalHistoryCount()
if ($count -gt 0) {
$installed = @(foreach ($h in $searcher.QueryHistory(0, [Math]::Min($count, 300))) {
if ($h.Operation -eq 1 -and ($h.ResultCode -eq 2 -or $h.ResultCode -eq 3)) {
[pscustomobject]@{
id = [string]$h.UpdateIdentity.UpdateID
revision = [int]$h.UpdateIdentity.RevisionNumber
at = [int64]($h.Date - [datetime]'1970-01-01').TotalSeconds
}
}
})
}
} catch {
$history_error = $_.Exception.Message
}
}
ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
search = $search
installed = $installed
history_error = $history_error
})
""".replace("__STORE__", STORE)
# The newest 300 entries of the host's update history; times are UTC, as unix seconds.
_PS_WU_HISTORY = r"""
$ErrorActionPreference = 'Stop'
$searcher = (New-Object -ComObject Microsoft.Update.Session).CreateUpdateSearcher()
$count = $searcher.GetTotalHistoryCount()
ConvertTo-Json -Compress -Depth 3 -InputObject @(if ($count -gt 0) {
foreach ($h in $searcher.QueryHistory(0, [Math]::Min($count, 300))) {
[pscustomobject]@{
id = [string]$h.UpdateIdentity.UpdateID
revision = [int]$h.UpdateIdentity.RevisionNumber
title = [string]$h.Title
at = [int64]($h.Date - [datetime]'1970-01-01').TotalSeconds
operation = [int]$h.Operation
result = [int]$h.ResultCode
hresult = [int64]$h.HResult
client = [string]$h.ClientApplicationID
}
}
})
"""
#: The update classifications (``ICategory.CategoryID``, the same in every language).
_SECURITY_UPDATES = "0fa1201d-4330-4fa8-8ae9-b877473b6441"
_DEFINITION_UPDATES = "e0789628-ce08-4437-be74-2495b842f43b"
_UPGRADES = "3689bdc8-b205-4af4-8d4a-a63924c5e9d5"
#: napalm-device-types' package name rule (``UpdateMixin.apply_updates``).
NAME = re.compile(r"[a-zA-Z0-9_\-+.]+")
#: Short enough for a store that keeps a package name in 255 characters.
NAME_MAX = 200
_DATE_PREFIX = re.compile(r"^\s*\d{4}-\d{2}\s+")
_VERSIONED = re.compile(r"\([^()]*\d+\.\d+[^()]*\)") # "(Version 1.441.120.0)", "(26100.2894)"
_KB = re.compile(r"\(?\bKB\d+\b\)?", re.IGNORECASE)
_V_SUFFIX = re.compile(r"\s+-?\s*v\d+(?:\.\d+)+", re.IGNORECASE) # "- v5.141"
_NOT_NAME = re.compile(r"[^A-Za-z0-9._+-]+")
_DASHES = re.compile(r"-{2,}")
_KB_IN_TITLE = re.compile(r"\bKB(\d+)\b", re.IGNORECASE)
#: MsrcSeverity, lowest first.
_SEVERITIES = ("Low", "Moderate", "Important", "Critical")
#: IUpdateHistoryEntry.ResultCode: what a finished entry other than success says.
_RESULTS = {3: "succeeded with errors", 4: "failed", 5: "aborted"}
_IN_PROGRESS = 1
_UNINSTALL = 2
def update_name(title: str, kbs: list[str], update_id: str) -> str:
"""The name of an update: its title without month, KB article and version, as a
package name (:data:`NAME`); its KB article or its ID when nothing is left."""
text = unicodedata.normalize("NFKD", title).encode("ascii", "ignore").decode()
for pattern in (_DATE_PREFIX, _VERSIONED, _KB, _V_SUFFIX):
text = pattern.sub(" ", text)
name = _DASHES.sub("-", _NOT_NAME.sub("-", text)).strip("-.")
name = name[:NAME_MAX].rstrip("-.")
if name:
return name
return f"KB{kbs[0]}" if kbs else update_id
class Offer(NamedTuple):
"""One update the search offers: its exact identity and what it is."""
identity: str # "<UpdateID>:<RevisionNumber>"
name: str
title: str
advisories: list[str]
cves: list[str]
severity: str | None
security: bool | None
def _security(classifications: list[str], cves: list[str], severity: str | None) -> bool | None:
if cves or severity or {_SECURITY_UPDATES, _DEFINITION_UPDATES} & set(classifications):
return True
return False if classifications else None
def _strings(value: Any) -> list[str]:
return [str(v) for v in _as_list(value)]
def _text(value: Any) -> str | None:
"""A string the host may have left empty or out; None then."""
return str(value or "") or None
def _identity(entry: dict[str, Any]) -> str:
return f"{entry['id']}:{int(entry.get('revision') or 0)}"
def _offer(update: dict[str, Any]) -> Offer | None:
"""The offer *update* is; None for one this path does not install."""
classifications = [c.lower() for c in _strings(update.get("classifications"))]
if update.get("browse_only") or _UPGRADES in classifications:
return None
kbs, cves = _strings(update.get("kb")), _strings(update.get("cves"))
severity = _text(update.get("severity"))
title = str(update.get("title") or "")
return Offer(
identity=_identity(update),
name=update_name(title, kbs, str(update["id"])),
title=title,
advisories=[f"KB{k}" for k in kbs],
cves=cves,
severity=severity,
security=_security(classifications, cves, severity),
)
class Search(NamedTuple):
"""What one search found."""
searched_at: int
seconds: int
origin: str
offers: list[Offer]
def parse_search(raw: Any) -> Search:
"""The search :data:`_PS_WU_SEARCH` printed, or kept.
:raises ValueError: when *raw* is no search.
"""
if not isinstance(raw, dict) or "updates" not in raw:
raise ValueError("not a Windows Update search")
started = int(raw.get("searched_at") or 0)
wsus = raw.get("wsus")
offers = [o for u in _as_list(raw["updates"]) if (o := _offer(u)) is not None]
return Search(
searched_at=started,
seconds=max(int(raw.get("finished_at") or started) - started, 0),
origin=f"WSUS {wsus}" if wsus else "Windows Update",
offers=offers,
)
def _higher(first: str | None, second: str | None) -> str | None:
def rank(s: str | None) -> int:
return _SEVERITIES.index(s) if s in _SEVERITIES else -1
return first if rank(first) >= rank(second) else second
def _merged(into: UpdateDict, offer: Offer) -> None:
into["advisories"] = [*into.get("advisories", []), *offer.advisories]
into["new_version"] = " ".join(into["advisories"]) or into["new_version"]
into["cves"] = [*into.get("cves", []), *(c for c in offer.cves if c not in into["cves"])]
into["vendor_severity"] = _higher(into.get("vendor_severity"), offer.severity)
first, second = into.get("security"), offer.security
if first or second:
into["security"] = True
elif first is None or second is None:
into["security"] = None
def pending_updates(search: Search) -> list[UpdateDict]:
"""One update per name: offers of the same name are one, their KBs and CVEs together."""
by_name: dict[str, UpdateDict] = {}
for offer in search.offers:
if offer.name in by_name:
_merged(by_name[offer.name], offer)
continue
by_name[offer.name] = {
"name": offer.name,
"current_version": "",
"new_version": " ".join(offer.advisories) or f"rev {offer.identity.split(':')[-1]}",
"origin": search.origin,
"security": offer.security,
"title": offer.title,
"advisories": list(offer.advisories),
"cves": list(offer.cves),
"vendor_severity": offer.severity,
}
return list(by_name.values())
def _installed_since(reading: dict[str, Any], since: int) -> set[str]:
return {
_identity(h) for h in _as_list(reading.get("installed")) if int(h.get("at") or 0) >= since
}
def parse_pending(output: str) -> Search:
"""The last search :data:`_PS_WU_PENDING` printed, without what was installed since.
:raises PackageIndexMissing: before the first search.
:raises ValueError: when the kept reading is no search.
"""
reading = json.loads(output) if output.strip() else {}
if not reading.get("search"):
raise PackageIndexMissing("Windows Update has not been searched yet; a refresh searches it")
search = parse_search(json.loads(reading["search"]))
done = _installed_since(reading, search.searched_at)
return search._replace(offers=[o for o in search.offers if o.identity not in done])
def _hresult(value: Any) -> str:
return f"0x{int(value or 0) & 0xFFFFFFFF:08X}"
def _error(entry: dict[str, Any]) -> str | None:
word = _RESULTS.get(int(entry.get("result") or 0))
if word is None:
return None
return f"{word} ({_hresult(entry['hresult'])})" if entry.get("hresult") else word
def _package(title: str, update_id: str, removed: bool) -> UpdateHistoryPackageDict:
"""What one history entry changed; the history names no KB but in the title."""
kb = [m.upper() for m in _KB_IN_TITLE.findall(title)]
version = f"KB{kb[0]}" if kb else None
return {
"name": update_name(title, kb, update_id),
"action": "remove" if removed else "install",
"old_version": version if removed else None,
"new_version": None if removed else version,
"title": title,
}
def _transaction(entry: dict[str, Any]) -> UpdateHistoryDict:
operation = int(entry.get("operation") or 1)
at = int(entry["at"])
title = str(entry.get("title") or "")
return {
"id": f"{_identity(entry)}:{operation}:{at}",
"start": at,
"end": None if int(entry.get("result") or 0) == _IN_PROGRESS else at,
"packages": [_package(title, str(entry["id"]), operation == _UNINSTALL)],
"requested_by": _text(entry.get("client")),
"command": None,
"error": _error(entry),
}
def parse_history(output: str, since: int | None) -> list[UpdateHistoryDict]:
"""The transactions :data:`_PS_WU_HISTORY` printed that started at or after *since*,
newest first."""
entries = _as_list(json.loads(output)) if output.strip() else []
found = [_transaction(e) for e in entries if since is None or int(e["at"]) >= since]
return sorted(found, key=lambda t: t["start"], reverse=True)
# ---------------------------------------------------------------------------
# The mixin
# ---------------------------------------------------------------------------
class WindowsUpdateMixin(UpdateMixin):
"""Windows Update as napalm-device-types' updates; the driver carries the scripts."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def refresh_available_updates(self) -> dict[str, Any]:
"""Search the host's update source, and keep what it found for the poll.
A search takes minutes. One that Windows refuses (no connection to the source)
is a failed refresh, and the reading from the last search stays.
"""
try:
search = parse_search(json.loads(self._run_raw(_PS_WU_SEARCH)))
except PowerShellError as exc:
return {"success": False, "output": str(exc)}
updates = pending_updates(search)
security = sum(1 for u in updates if u.get("security"))
return {
"success": True,
"output": (
f"{search.origin} offers {len(updates)} updates, {security} of them for "
f"security, searched in {search.seconds} s."
),
}
def _wu_search(self) -> Search:
return parse_pending(self._run_raw(_PS_WU_PENDING))
def get_available_updates(self) -> list[UpdateDict]:
"""What the last search found, without what the host installed since.
:raises PackageIndexMissing: before the first search; a refresh searches.
"""
return pending_updates(self._wu_search())
def get_update_history(self, since: int | None = None) -> list[UpdateHistoryDict]:
"""The host's update history since *since* (unix seconds), newest first."""
return parse_history(self._run_raw(_PS_WU_HISTORY), since)
def apply_updates(
self,
packages: list[str],
*,
log: Callable[[str], None] | None = None,
) -> ApplyUpdatesResultDict:
"""Install the updates named *packages* -- every pending one when empty -- in a
one-shot SYSTEM task, line by line to *log*; the host is never restarted.
Each name stands for the exact updates (ID and revision) the last search found
under it; the task searches again and installs only those
(:mod:`napalm_windows.windows_update_run`).
:raises ValueError: for a name that is no package name.
:raises PackageIndexMissing: before the first search.
"""
bad = [p for p in packages if not NAME.fullmatch(p or "")]
if bad:
raise ValueError(f"Invalid update name {bad[0]!r}")
offers = self._wu_search().offers
wanted = set(packages)
chosen = [o for o in offers if not packages or o.name in wanted]
missing = sorted(wanted - {o.name for o in offers})
return install(self._run_raw, {o.identity: o.title for o in chosen}, missing, log)
+341
View File
@@ -0,0 +1,341 @@
"""Installing Windows updates in a one-shot SYSTEM task (netork#2892).
Windows refuses a download or an install through the update agent to a network logon
(``E_ACCESSDENIED``), which a WinRM session is. A scheduled task running as SYSTEM is
not one, so a run is such a task (as PSWindowsUpdate's ``Invoke-WUJob`` does it):
1. **Sweep.** The tasks of earlier runs and their registry keys are deleted -- runs
whose connection died left them behind. A run still installing refuses this one.
2. **Start.** The run's key under :data:`RUNS` (``HKLM\\SOFTWARE``, where only
administrators and SYSTEM may write) gets the exact updates chosen
(``<UpdateID>:<revision>``) and the script; the task ``\\napalm-windows\\update-run-<id>``
runs that script from the key, as SYSTEM, and is started. No file is written.
3. **Follow.** Every few seconds the key's log is read and each new line handed on,
until the script writes its result, or the task ends without one.
4. **Clean up.** The task and the key are deleted.
The task searches again and installs nothing it cannot match exactly: an update no
longer offered under that ID and revision (installed, replaced or withdrawn since the
reading), one offered twice, one that asks for input while it installs, and one whose
licence terms the host has not accepted are refused, by name. While a restart is
pending, nothing is installed. The run never restarts the host: what follows a run is
the caller's. An update Windows installs with a result of its own is reported with it,
and the task names itself to Windows Update as ``napalm-windows``, as the host's
history shows.
A run the follower gives up on (:data:`FOLLOW_SECONDS`) carries on on the host: its
task is left for the next run's sweep, and what it installed shows in the history.
"""
from __future__ import annotations
import json
import time
import uuid
from collections.abc import Callable
from typing import Any
from napalm_device_types.models import ApplyUpdatesResultDict
from napalm_windows._powershell import _as_list, _ps_quote
#: Each run's own registry key lives here.
RUNS = "HKLM:\\SOFTWARE\\napalm-windows\\WindowsUpdate\\Runs"
#: The task folder of the runs; the scheduled-jobs reading shows them as an application's.
TASK_PATH = "\\napalm-windows\\"
TASK_PREFIX = "update-run-"
#: How often the follower looks, and how long it follows a run at most.
POLL_SECONDS = 5
FOLLOW_SECONDS = 25 * 60
# Runs as SYSTEM, from the run's key: search again, refuse what does not match exactly,
# download, install, report. Never restarts. __KEY__ is the run's key.
_PS_RUN = r"""
$ErrorActionPreference = 'Stop'
$key = '__KEY__'
$log = New-Object System.Collections.Generic.List[string]
$outcome = [ordered]@{
reboot_required = $false; installed = @(); refused = @(); failed = @(); error = $null
}
function Say([string]$line) {
$log.Add($line)
Set-ItemProperty -LiteralPath $key -Name Log -Value ($log -join "`n")
}
function Named($u) { '{0} ({1}:{2})' -f $u.Title, $u.Identity.UpdateID, $u.Identity.RevisionNumber }
function IdOf($u) { '{0}:{1}' -f $u.Identity.UpdateID, $u.Identity.RevisionNumber }
function Failed($u, $step, $r) {
$code = [int]$r.ResultCode
$outcome.failed += [pscustomobject]@{
id = (IdOf $u); step = $step; result = $code; hresult = [int64]$r.HResult
}
Say ('{0} failed: {1} (result {2}, 0x{3:X8})' -f $step, (Named $u), $code, [int]$r.HResult)
}
try {
$requested = @((Get-ItemProperty -LiteralPath $key -Name Requested).Requested)
$session = New-Object -ComObject Microsoft.Update.Session
$session.ClientApplicationID = 'napalm-windows'
$installer = $session.CreateUpdateInstaller()
$pending = (New-Object -ComObject Microsoft.Update.SystemInfo).RebootRequired
if ($pending -or $installer.RebootRequiredBeforeInstallation) {
throw 'A restart is pending on the host: nothing is installed until it has restarted.'
}
Say 'Searching Windows Update again for the chosen updates'
$offered = @{}
$searcher = $session.CreateUpdateSearcher()
foreach ($u in $searcher.Search("IsInstalled=0 and IsHidden=0 and Type='Software'").Updates) {
$id = IdOf $u
if ($offered.ContainsKey($id)) { $offered[$id] += @($u) } else { $offered[$id] = @($u) }
}
$chosen = New-Object -ComObject Microsoft.Update.UpdateColl
foreach ($id in $requested) {
$u = $null
$why = $null
if (-not $offered.ContainsKey($id)) {
$why = 'no longer offered: installed, replaced or withdrawn since it was read'
} elseif ($offered[$id].Count -ne 1) {
$why = 'offered more than once'
} else {
$u = $offered[$id][0]
if ($u.InstallationBehavior.CanRequestUserInput) {
$why = 'it asks for input while it installs'
} elseif (-not $u.EulaAccepted) {
$why = 'its licence terms have not been accepted on the host'
}
}
if ($why) {
$outcome.refused += [pscustomobject]@{ id = $id; reason = $why }
Say ('Refused {0}: {1}' -f $(if ($u) { Named $u } else { $id }), $why)
} else {
[void]$chosen.Add($u)
}
}
$ready = New-Object -ComObject Microsoft.Update.UpdateColl
if ($chosen.Count -gt 0) {
Say ('Downloading {0} update(s)' -f $chosen.Count)
$downloader = $session.CreateUpdateDownloader()
$downloader.Updates = $chosen
$fetched = $downloader.Download()
for ($i = 0; $i -lt $chosen.Count; $i++) {
$u = $chosen.Item($i)
if ($u.IsDownloaded) { [void]$ready.Add($u) }
else { Failed $u 'Download' ($fetched.GetUpdateResult($i)) }
}
}
if ($ready.Count -gt 0) {
Say ('Installing {0} update(s); the host is not restarted' -f $ready.Count)
$installer.Updates = $ready
$installer.AllowSourcePrompts = $false
try { $installer.ForceQuiet = $true } catch { }
$done = $installer.Install()
for ($i = 0; $i -lt $ready.Count; $i++) {
$u = $ready.Item($i)
$r = $done.GetUpdateResult($i)
if ($r.ResultCode -eq 2 -or $r.ResultCode -eq 3) {
$outcome.installed += (IdOf $u)
Say ('Installed: ' + (Named $u))
} else { Failed $u 'Install' $r }
if ($r.RebootRequired) { $outcome.reboot_required = $true }
}
if ($done.RebootRequired) { $outcome.reboot_required = $true }
if ($outcome.reboot_required) { Say 'A restart finishes the installation.' }
}
} catch {
$outcome.error = [string]$_.Exception.Message
if (-not $outcome.error) { $outcome.error = [string]$_ }
Say $outcome.error
}
$result = ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]$outcome)
Set-ItemProperty -LiteralPath $key -Name Result -Value $result
"""
# Deletes what earlier runs left -- unless one is still running, which it names.
_PS_SWEEP = r"""
$ErrorActionPreference = 'Stop'
$tasks = @(Get-ScheduledTask -TaskPath '__PATH__' -ErrorAction SilentlyContinue |
Where-Object { $_.TaskName -like '__PREFIX__*' })
$busy = @($tasks | Where-Object { [string]$_.State -eq 'Running' } | ForEach-Object { $_.TaskName })
$swept = @()
if ($busy.Count -eq 0) {
foreach ($t in $tasks) {
Unregister-ScheduledTask -TaskPath '__PATH__' -TaskName $t.TaskName -Confirm:$false
$swept += $t.TaskName
}
if (Test-Path -LiteralPath '__RUNS__') {
foreach ($k in @(Get-ChildItem -LiteralPath '__RUNS__')) {
Remove-Item -LiteralPath $k.PSPath -Recurse
$swept += $k.PSChildName
}
}
}
ConvertTo-Json -Compress -InputObject ([pscustomobject]@{ busy = $busy; swept = $swept })
"""
_PS_START = r"""
$ErrorActionPreference = 'Stop'
$key = '__RUNS__\' + __RUN__
New-Item -Path $key -Force | Out-Null
$requested = [string[]]@(__REQUESTED__)
New-ItemProperty -LiteralPath $key -Name Requested -PropertyType MultiString -Value $requested |
Out-Null
New-ItemProperty -LiteralPath $key -Name Script -PropertyType String -Value __SCRIPT__ | Out-Null
$exe = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
$read = "(Get-ItemProperty -LiteralPath '$key' -Name Script).Script"
$arg = '-NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "& ([scriptblock]::Create(' +
$read + '))"'
$action = New-ScheduledTaskAction -Execute $exe -Argument $arg
$principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries `
-ExecutionTimeLimit (New-TimeSpan -Hours 4) -MultipleInstances IgnoreNew
$about = 'napalm-windows: installs the Windows updates an application chose; deleted when its ' +
'run ends'
Register-ScheduledTask -TaskPath '__PATH__' -TaskName __TASK__ -Action $action `
-Principal $principal -Settings $settings -Description $about | Out-Null
Start-ScheduledTask -TaskPath '__PATH__' -TaskName __TASK__
"""
# The task's state first: a result written after it was read is still found below.
_PS_FOLLOW = r"""
$ErrorActionPreference = 'Stop'
$task = @(Get-ScheduledTask -TaskPath '__PATH__' -ErrorAction SilentlyContinue |
Where-Object { $_.TaskName -eq __TASK__ })
$state = 'gone'
if ($task.Count) { $state = [string]$task[0].State }
$run = Get-ItemProperty -ErrorAction SilentlyContinue -LiteralPath ('__RUNS__\' + __RUN__)
ConvertTo-Json -Compress -InputObject ([pscustomobject]@{
state = $state
log = [string]$run.Log
result = [string]$run.Result
})
"""
_PS_CLEANUP = r"""
$ErrorActionPreference = 'Stop'
Unregister-ScheduledTask -TaskPath '__PATH__' -TaskName __TASK__ -Confirm:$false `
-ErrorAction SilentlyContinue
$key = '__RUNS__\' + __RUN__
if (Test-Path -LiteralPath $key) { Remove-Item -LiteralPath $key -Recurse }
"""
def _script(template: str, **values: str) -> str:
"""*template* with its ``__NAME__`` placeholders filled; the run's own as given, the
module's constants always. Values are PowerShell already: quote them first."""
values = {"PATH": TASK_PATH, "PREFIX": TASK_PREFIX, "RUNS": RUNS, **values}
for name, value in values.items():
template = template.replace(f"__{name}__", value)
return template
Run = Callable[[str], str]
Log = Callable[[str], None]
class _Lines:
"""Every line of the run, each handed to *log* once as it comes."""
def __init__(self, log: Log | None):
self.log = log
self.lines: list[str] = []
def say(self, line: str) -> None:
self.lines.append(line)
if self.log is not None:
self.log(line)
def host(self, text: str, seen: int) -> int:
"""Hand on the lines of the host's *text* past the first *seen*; how many there are."""
lines = text.split("\n") if text else []
for line in lines[seen:]:
self.say(line)
return max(len(lines), seen)
def result(self, success: bool, error: str | None = None) -> ApplyUpdatesResultDict:
out: ApplyUpdatesResultDict = {"success": success, "output": "\n".join(self.lines)}
if not success:
out["error"] = error or "The update run did not succeed; its output says why."
return out
def _ids(run_id: str) -> dict[str, str]:
return {"RUN": _ps_quote(run_id), "TASK": _ps_quote(TASK_PREFIX + run_id)}
def _sweep(run: Run) -> list[str]:
"""The earlier runs still installing; the others are deleted."""
reading = json.loads(run(_script(_PS_SWEEP)) or "{}")
return [str(b) for b in _as_list(reading.get("busy"))]
def run_script(run_id: str) -> str:
"""What the task runs as SYSTEM for the run *run_id*."""
return _PS_RUN.replace("__KEY__", f"{RUNS}\\{run_id}")
def _start(run: Run, run_id: str, identities: list[str]) -> None:
requested = ",".join(_ps_quote(i) for i in identities)
script = _ps_quote(run_script(run_id))
run(_script(_PS_START, REQUESTED=requested, SCRIPT=script, **_ids(run_id)))
def _cleanup(run: Run, run_id: str) -> None:
run(_script(_PS_CLEANUP, **_ids(run_id)))
def _outcome(result: dict[str, Any], lines: _Lines, refused_before: int) -> ApplyUpdatesResultDict:
refused = len(_as_list(result.get("refused"))) + refused_before
failed = len(_as_list(result.get("failed")))
if result.get("error"):
return lines.result(False, str(result["error"]))
if refused or failed:
return lines.result(False, f"{refused} update(s) refused, {failed} failed.")
return lines.result(True)
def _follow(run: Run, run_id: str, lines: _Lines, refused_before: int) -> ApplyUpdatesResultDict:
"""Hand on the run's lines until it ends; its outcome."""
seen = 0
deadline = time.monotonic() + FOLLOW_SECONDS
follow = _script(_PS_FOLLOW, **_ids(run_id))
while True:
time.sleep(POLL_SECONDS)
reading = json.loads(run(follow) or "{}")
seen = lines.host(str(reading.get("log") or ""), seen)
if reading.get("result"):
_cleanup(run, run_id)
return _outcome(json.loads(reading["result"]), lines, refused_before)
if reading.get("state") != "Running":
_cleanup(run, run_id)
return lines.result(False, "The update task ended without a result.")
if time.monotonic() > deadline:
return lines.result(
False,
"The updates are still installing on the host; the run carries on there, "
"and the update history shows what it installed.",
)
def install(
run: Run, chosen: dict[str, str], missing: list[str], log: Log | None
) -> ApplyUpdatesResultDict:
"""Install the updates *chosen* (``identity -> title``) in a SYSTEM task, following it.
*missing* are names the caller asked for that the last search does not offer: each
is refused, by name, and the others are installed.
"""
lines = _Lines(log)
for name in missing:
lines.say(f"Refused {name}: not offered by the last search")
if not chosen:
if missing:
return lines.result(False, f"{len(missing)} update(s) refused, 0 failed.")
lines.say("Nothing to install.")
return lines.result(True)
busy = _sweep(run)
if busy:
lines.say(f"An earlier update run is still installing on the host: {', '.join(busy)}")
return lines.result(False, "An earlier update run is still installing on the host.")
run_id = uuid.uuid4().hex[:12]
for identity, title in chosen.items():
lines.say(f"Chosen: {title} ({identity})")
_start(run, run_id, list(chosen))
return _follow(run, run_id, lines, len(missing))
-11
View File
@@ -1,11 +0,0 @@
[
{"channel": "Application", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Application.evtx", "size": 20975616, "modified": 1764499800, "records": 41233, "type": "Administrative"},
{"channel": "Security", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Security.evtx", "size": 20975616, "modified": 1764499990, "records": 58812, "type": "Administrative"},
{"channel": "System", "path": "C:\\Windows\\System32\\Winevt\\Logs\\System.evtx", "size": 20975616, "modified": 1764499950, "records": 30187, "type": "Administrative"},
{"channel": "Microsoft-Windows-Sysmon/Operational", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-Sysmon%4Operational.evtx", "size": 67113984, "modified": 1764499999, "records": 120044, "type": "Operational"},
{"channel": "Microsoft-Windows-PowerShell/Operational", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-PowerShell%4Operational.evtx", "size": 15798272, "modified": null, "records": 9120, "type": "Operational"},
{"channel": "Microsoft-Windows-Kernel-PnP/Device Management", "path": null, "size": 69632, "modified": 1764400000, "records": 12, "type": "Operational"},
{"channel": "Microsoft-Windows-WMI-Activity/Debug", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-WMI-Activity%4Debug.etl", "size": 4096, "modified": 1764400000, "records": 3, "type": "Debug"},
{"channel": "Microsoft-Windows-Kernel-Boot/Analytic", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-Kernel-Boot%4Analytic.etl", "size": 4096, "modified": 1764400000, "records": 7, "type": "Analytic"},
{"channel": "Microsoft-Windows-Empty/Operational", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-Empty%4Operational.evtx", "size": 69632, "modified": 1764400000, "records": 0, "type": "Operational"}
]
-217
View File
@@ -1,217 +0,0 @@
{
"parts": {
"rare": {
"ok": true,
"capped": false,
"events": [
{
"provider": "Microsoft-Windows-WER-SystemErrorReporting",
"id": 1001,
"time": 1764470150,
"props": [
"0x0000009f (0x0000000000000003, 0xffffc40f1a2b3c40, 0xfffff80412345678, 0xffffc40f1a2b3d50)",
"C:\\Windows\\MEMORY.DMP",
"1130-01"
],
"message": "The computer has rebooted from a bugcheck. The bugcheck was: 0x0000009f (0x0000000000000003, 0xffffc40f1a2b3c40, 0xfffff80412345678, 0xffffc40f1a2b3d50). A dump was saved in: C:\\Windows\\MEMORY.DMP. Report Id: 1130-01."
},
{
"provider": "EventLog",
"id": 6008,
"time": 1764470040,
"props": [
"03:12:09",
"\u200e30.\u200e11.\u200e2026",
"",
"",
"1234",
"",
""
],
"message": "The previous system shutdown at 03:12:09 on 30.11.2026 was unexpected."
},
{
"provider": "Microsoft-Windows-Kernel-Power",
"id": 41,
"time": 1764470035,
"props": [
"159",
"3",
"18446676388826430528",
"18446735294628329080",
"18446676388826430800",
"false",
"0"
],
"message": "The system has rebooted without cleanly shutting down first."
},
{
"provider": "Microsoft-Windows-WHEA-Logger",
"id": 18,
"time": 1764383600,
"props": [
"1",
"0",
"5",
"0",
"0"
],
"message": "A fatal hardware error has occurred."
},
{
"provider": "disk",
"id": 7,
"time": 1764466400,
"props": [
"\\Device\\Harddisk1\\DR1"
],
"message": "The device, \\Device\\Harddisk1\\DR1, has a bad block."
},
{
"provider": "Microsoft-Windows-Ntfs",
"id": 55,
"time": 1764462800,
"props": [
"D:",
"\\Device\\HarddiskVolume5",
"0x2"
],
"message": "A corruption was discovered in the file system structure on volume D:."
},
{
"provider": "Microsoft-Windows-Kernel-Power",
"id": 41,
"time": 1764297200,
"props": [
"0",
"0",
"0",
"0",
"0",
"false",
"0"
],
"message": null
}
]
},
"frequent": {
"ok": true,
"capped": false,
"events": [
{
"provider": "Service Control Manager",
"id": 7031,
"time": 1764470600,
"props": [
"Backup Agent",
"1",
"60000",
"1",
"Restart the service"
],
"message": null
},
{
"provider": "Microsoft-Windows-WHEA-Logger",
"id": 47,
"time": 1764470500,
"props": [
"3",
"0",
"1"
],
"message": null
},
{
"provider": "disk",
"id": 153,
"time": 1764470400,
"props": [
"\\Device\\Harddisk1\\DR1",
"0x1d4c0",
"1",
"\\Device\\00000034"
],
"message": null
},
{
"provider": "Service Control Manager",
"id": 7034,
"time": 1764470300,
"props": [
"Vendor Sync",
"2"
],
"message": null
},
{
"provider": "Microsoft-Windows-WHEA-Logger",
"id": 19,
"time": 1764470200,
"props": [
"3",
"0",
"1"
],
"message": null
}
]
},
"apps": {
"ok": true,
"capped": false,
"events": [
{
"provider": "Application Error",
"id": 1000,
"time": 1764470900,
"props": [
"vendorapp.exe",
"4.2.0.0",
"65a1b2c3",
"ntdll.dll",
"10.0.20348.2340",
"f0e1d2c3",
"c0000005",
"00000000000a1b2c",
"1f40",
"01db1234567890ab",
"C:\\Program Files\\Vendor\\vendorapp.exe"
],
"message": null
},
{
"provider": "Application Error",
"id": 1000,
"time": 1764470800,
"props": [
"vendorapp.exe",
"4.2.0.0",
"65a1b2c3",
"ntdll.dll",
"10.0.20348.2340",
"f0e1d2c3",
"c0000005",
"00000000000a1b2c",
"1f40",
"01db1234567890ab",
"C:\\Program Files\\Vendor\\vendorapp.exe"
],
"message": null
},
{
"provider": "Application Error",
"id": 1000,
"time": 1764470700,
"props": [
"legacy.exe",
"1.0.0.0",
"5f0a0b0c"
],
"message": null
}
]
}
}
}
+5 -9
View File
@@ -1,11 +1,7 @@
[
{"name": "WinRM", "state": "Running", "start_mode": "Auto", "pid": 1234, "exit_code": 0, "service_code": 0, "account": "NT AUTHORITY\\NetworkService", "trigger_start": false},
{"name": "Spooler", "state": "Stopped", "start_mode": "Manual", "pid": 0, "exit_code": 0, "service_code": 0, "account": "LocalSystem", "trigger_start": false},
{"name": "MSSQL$SQLEXPRESS", "state": "Running", "start_mode": "Auto", "pid": 4321, "exit_code": 0, "service_code": 0, "account": "CORP\\svc-sql", "trigger_start": false},
{"name": "RemoteRegistry", "state": "Stopped", "start_mode": "Disabled", "pid": 0, "exit_code": 1077, "service_code": 0, "account": "NT AUTHORITY\\LocalService", "trigger_start": true},
{"name": "wuauserv", "state": "Stopped", "start_mode": "Manual", "pid": null, "exit_code": 0, "service_code": 0, "account": "LocalSystem", "trigger_start": true},
{"name": "AppReadiness", "state": "Stopped", "start_mode": "Auto", "pid": 0, "exit_code": 1077, "service_code": 0, "account": "LocalSystem", "trigger_start": false},
{"name": "BackupAgent", "state": "Stopped", "start_mode": "Auto", "pid": 0, "exit_code": 1067, "service_code": 0, "account": "CORP\\svc-backup", "trigger_start": false},
{"name": "VendorSync", "state": "Stopped", "start_mode": "Auto", "pid": 0, "exit_code": 1066, "service_code": 2147942405, "account": "LocalSystem", "trigger_start": false},
{"name": "BthServ", "state": "Stopped", "start_mode": "Auto", "pid": 0, "exit_code": 1, "service_code": 0, "account": null, "trigger_start": true}
{"name": "WinRM", "state": "Running", "start_mode": "Auto", "pid": 1234},
{"name": "Spooler", "state": "Stopped", "start_mode": "Manual", "pid": 0},
{"name": "MSSQL$SQLEXPRESS", "state": "Running", "start_mode": "Auto", "pid": 4321},
{"name": "RemoteRegistry", "state": "Stopped", "start_mode": "Disabled", "pid": 0},
{"name": "wuauserv", "state": "Stopped", "start_mode": "Manual", "pid": null}
]
+1
View File
@@ -0,0 +1 @@
[{"id":"d2b5e0a8-6c3e-4c9b-8a55-0f6b5bb2a1c4","revision":200,"title":"Security Intelligence Update for Microsoft Defender Antivirus - KB2267602 (Version 1.441.120.0) - Current Channel (Broad)","at":1795603600,"operation":1,"result":2,"hresult":0,"client":"Windows Defender (77BDAF73-B396-481F-9042-AD358843EC24)"},{"id":"1c7f9e2a-5b4d-4e0f-9d8c-3a2b1c0d9e8f","revision":3,"title":"2026-11 Cumulative Update for .NET Framework 3.5, 4.8 and 4.8.1 for Microsoft server operating system version 21H2 for x64 (KB5070100)","at":1795590000,"operation":1,"result":4,"hresult":-2145124329,"client":"napalm-windows"},{"id":"aa11bb22-cc33-4d44-8e55-ff6677889900","revision":1,"title":"2026-10 Cumulative Update for Microsoft server operating system version 21H2 for x64-based Systems (KB5066000)","at":1792900000,"operation":1,"result":2,"hresult":0,"client":"UpdateOrchestrator"},{"id":"bb22cc33-dd44-4e55-8f66-0011aabbccdd","revision":2,"title":"Update for Windows Security platform - KB5007651 (Version 1.0.2509.1001)","at":1792800000,"operation":2,"result":2,"hresult":0,"client":"AutomaticUpdates"},{"id":"cc33dd44-ee55-4f66-8a77-1122bbccddee","revision":1,"title":"2026-09 Cumulative Update for Microsoft server operating system version 21H2 for x64-based Systems (KB5063000)","at":1790200000,"operation":1,"result":1,"hresult":0,"client":""}]
+1
View File
@@ -0,0 +1 @@
{"search":"{\"searched_at\":1795600000,\"finished_at\":1795600094,\"result\":2,\"wsus\":null,\"updates\":[{\"id\":\"8f5c0d55-3b0f-4ad0-9a3e-1a8a0d7f6e11\",\"revision\":1,\"title\":\"2026-11 Cumulative Update for Microsoft server operating system version 21H2 for x64-based Systems (KB5070000)\",\"kb\":[\"5070000\"],\"cves\":[\"CVE-2026-21001\",\"CVE-2026-21002\",\"CVE-2026-21003\"],\"severity\":\"Critical\",\"classifications\":[\"0fa1201d-4330-4fa8-8ae9-b877473b6441\"],\"browse_only\":false,\"interactive\":false,\"reboot\":2,\"eula_accepted\":true,\"downloaded\":false},{\"id\":\"d2b5e0a8-6c3e-4c9b-8a55-0f6b5bb2a1c4\",\"revision\":200,\"title\":\"Security Intelligence Update for Microsoft Defender Antivirus - KB2267602 (Version 1.441.120.0) - Current Channel (Broad)\",\"kb\":[\"2267602\"],\"cves\":[],\"severity\":\"\",\"classifications\":[\"e0789628-ce08-4437-be74-2495b842f43b\"],\"browse_only\":false,\"interactive\":false,\"reboot\":0,\"eula_accepted\":true,\"downloaded\":true},{\"id\":\"1c7f9e2a-5b4d-4e0f-9d8c-3a2b1c0d9e8f\",\"revision\":3,\"title\":\"2026-11 Cumulative Update for .NET Framework 3.5, 4.8 and 4.8.1 for Microsoft server operating system version 21H2 for x64 (KB5070100)\",\"kb\":[\"5070100\"],\"cves\":[\"CVE-2026-21101\"],\"severity\":\"Important\",\"classifications\":[\"0fa1201d-4330-4fa8-8ae9-b877473b6441\"],\"browse_only\":false,\"interactive\":false,\"reboot\":0,\"eula_accepted\":true,\"downloaded\":false},{\"id\":\"6a0d3c1e-9f8b-4d7a-8e6c-5b4a3f2e1d0c\",\"revision\":1,\"title\":\"Windows Malicious Software Removal Tool x64 - v5.141 (KB890830)\",\"kb\":[\"890830\"],\"cves\":[],\"severity\":\"\",\"classifications\":[\"28bc880e-0592-4cbf-8f95-c79b17911d5f\"],\"browse_only\":false,\"interactive\":false,\"reboot\":0,\"eula_accepted\":true,\"downloaded\":false},{\"id\":\"4e3d2c1b-0a9f-4e8d-8c7b-6a5f4e3d2c1b\",\"revision\":1,\"title\":\"2026-11 Cumulative Update Preview for Microsoft server operating system version 21H2 for x64-based Systems (KB5070200)\",\"kb\":[\"5070200\"],\"cves\":[],\"severity\":\"\",\"classifications\":[\"cd5ffd1e-e932-4e3a-bf74-18bf0b1bbd83\"],\"browse_only\":true,\"interactive\":false,\"reboot\":0,\"eula_accepted\":true,\"downloaded\":false},{\"id\":\"9b8a7c6d-5e4f-4a3b-9c2d-1e0f9a8b7c6d\",\"revision\":1,\"title\":\"Windows Server 2025 upgrade\",\"kb\":[],\"cves\":[],\"severity\":\"\",\"classifications\":[\"3689bdc8-b205-4af4-8d4a-a63924c5e9d5\"],\"browse_only\":false,\"interactive\":false,\"reboot\":0,\"eula_accepted\":false,\"downloaded\":false}]}","installed":[{"id":"d2b5e0a8-6c3e-4c9b-8a55-0f6b5bb2a1c4","revision":200,"at":1795603600},{"id":"8f5c0d55-3b0f-4ad0-9a3e-1a8a0d7f6e11","revision":1,"at":1795500000}],"history_error":null}
+1
View File
@@ -0,0 +1 @@
{"searched_at":1795600000,"finished_at":1795600094,"result":2,"wsus":null,"updates":[{"id":"8f5c0d55-3b0f-4ad0-9a3e-1a8a0d7f6e11","revision":1,"title":"2026-11 Cumulative Update for Microsoft server operating system version 21H2 for x64-based Systems (KB5070000)","kb":["5070000"],"cves":["CVE-2026-21001","CVE-2026-21002","CVE-2026-21003"],"severity":"Critical","classifications":["0fa1201d-4330-4fa8-8ae9-b877473b6441"],"browse_only":false,"interactive":false,"reboot":2,"eula_accepted":true,"downloaded":false},{"id":"d2b5e0a8-6c3e-4c9b-8a55-0f6b5bb2a1c4","revision":200,"title":"Security Intelligence Update for Microsoft Defender Antivirus - KB2267602 (Version 1.441.120.0) - Current Channel (Broad)","kb":["2267602"],"cves":[],"severity":"","classifications":["e0789628-ce08-4437-be74-2495b842f43b"],"browse_only":false,"interactive":false,"reboot":0,"eula_accepted":true,"downloaded":true},{"id":"1c7f9e2a-5b4d-4e0f-9d8c-3a2b1c0d9e8f","revision":3,"title":"2026-11 Cumulative Update for .NET Framework 3.5, 4.8 and 4.8.1 for Microsoft server operating system version 21H2 for x64 (KB5070100)","kb":["5070100"],"cves":["CVE-2026-21101"],"severity":"Important","classifications":["0fa1201d-4330-4fa8-8ae9-b877473b6441"],"browse_only":false,"interactive":false,"reboot":0,"eula_accepted":true,"downloaded":false},{"id":"6a0d3c1e-9f8b-4d7a-8e6c-5b4a3f2e1d0c","revision":1,"title":"Windows Malicious Software Removal Tool x64 - v5.141 (KB890830)","kb":["890830"],"cves":[],"severity":"","classifications":["28bc880e-0592-4cbf-8f95-c79b17911d5f"],"browse_only":false,"interactive":false,"reboot":0,"eula_accepted":true,"downloaded":false},{"id":"4e3d2c1b-0a9f-4e8d-8c7b-6a5f4e3d2c1b","revision":1,"title":"2026-11 Cumulative Update Preview for Microsoft server operating system version 21H2 for x64-based Systems (KB5070200)","kb":["5070200"],"cves":[],"severity":"","classifications":["cd5ffd1e-e932-4e3a-bf74-18bf0b1bbd83"],"browse_only":true,"interactive":false,"reboot":0,"eula_accepted":true,"downloaded":false},{"id":"9b8a7c6d-5e4f-4a3b-9c2d-1e0f9a8b7c6d","revision":1,"title":"Windows Server 2025 upgrade","kb":[],"cves":[],"severity":"","classifications":["3689bdc8-b205-4af4-8d4a-a63924c5e9d5"],"browse_only":false,"interactive":false,"reboot":0,"eula_accepted":false,"downloaded":false}]}
-103
View File
@@ -1,103 +0,0 @@
"""The event channels as the host's log sources (NetOrk/netork#2897).
A Windows host keeps its logs in event channels. ``Get-WinEvent -ListLog *`` names
every one with its ``.evtx`` file, size, last write and record count; a channel that
is switched on and holds records is a log the host writes. Analytic and debug
channels are trace sessions, not logs a reader can follow, and are left out. The
answer is the shape of tests/fixtures/synthetic/event_channels.json.
"""
from __future__ import annotations
import json
from pathlib import Path
import pytest
from napalm_windows import WindowsDriver
from napalm_windows import event_channels as mod
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "event_channels.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(answer: str | None = None) -> dict:
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(FIXTURE.read_text() if answer is None else answer)
return d.get_log_sources()
class TestTheReading:
def test_read_as_an_administrator_without_a_journal(self):
reading = _reading()
assert (reading["attributed"], reading["journald"], reading["forwarding"]) == (
True,
False,
None,
)
def test_every_channel_with_records_sorted_by_name(self):
assert [s["channel"] for s in _reading()["sources"]] == [
"Application",
"Microsoft-Windows-Kernel-PnP/Device Management",
"Microsoft-Windows-PowerShell/Operational",
"Microsoft-Windows-Sysmon/Operational",
"Security",
"System",
]
def test_a_channel_is_an_eventlog_source(self):
sysmon = next(s for s in _reading()["sources"] if "Sysmon" in s["channel"])
assert sysmon == {
"kind": "eventlog",
"path": r"C:\Windows\System32\Winevt\Logs\Microsoft-Windows-Sysmon%4Operational.evtx",
"unit": None,
"container_id": None,
"process": None,
"size": 67113984,
"modified": "2025-11-30T10:53:19+00:00",
"channel": "Microsoft-Windows-Sysmon/Operational",
}
def test_what_the_host_did_not_say_is_none(self):
sources = {s["channel"]: s for s in _reading()["sources"]}
assert sources["Microsoft-Windows-PowerShell/Operational"]["modified"] is None
assert sources["Microsoft-Windows-Kernel-PnP/Device Management"]["path"] is None
@pytest.mark.parametrize("left_out", ["Debug", "Analytic", "Empty"])
def test_trace_sessions_and_empty_channels_are_left_out(self, left_out):
assert not any(left_out in s["channel"] for s in _reading()["sources"])
def test_a_single_channel_is_still_a_list(self):
one = json.loads(FIXTURE.read_text())[2]
assert [s["channel"] for s in _reading(json.dumps(one))["sources"]] == ["System"]
def test_no_channel_is_no_sources(self):
assert _reading("")["sources"] == []
class TestTheScript:
def test_lists_every_channel_once(self):
assert "Get-WinEvent -ListLog *" in mod._PS_EVENT_CHANNELS
def test_a_channel_it_may_not_open_costs_only_that_channel(self):
assert "-ErrorAction SilentlyContinue" in mod._PS_EVENT_CHANNELS
def test_only_channels_switched_on_and_holding_records(self):
assert "$_.IsEnabled -and $_.RecordCount" in mod._PS_EVENT_CHANNELS
def test_the_file_is_named_as_it_is_on_disk(self):
assert "ExpandEnvironmentVariables" in mod._PS_EVENT_CHANNELS
def test_a_list_goes_through_input_object(self):
assert "-InputObject @(" in mod._PS_EVENT_CHANNELS
-206
View File
@@ -1,206 +0,0 @@
"""What the event log recorded that says something is wrong with the host (NetOrk/netork#2897).
One script asks the event log three questions over the reading's window: the rare
events of the System log (an unexpected shutdown, a bugcheck, a fatal hardware
error, a bad block, a file system corruption), its frequent ones (corrected
hardware errors, retried disk I/O, services that ended unexpectedly) and the
Application log's crashing programs. Each is bounded by time and count, and each
catches ``NoMatchingEventsFound``: ``Get-WinEvent`` throws when nothing matches. The
answer is the shape of tests/fixtures/synthetic/host_events.json.
"""
from __future__ import annotations
import json
import re
from pathlib import Path
from typing import Any
import pytest
from napalm_device_types import HOST_EVENT_KINDS, HostEventsMixin
from napalm_windows import WindowsDriver
from napalm_windows import host_events as mod
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "host_events.json"
NOW = 1764500000.0
WEEK = 7 * 86400
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 _driver(answer: dict[str, Any] | str | None = None) -> WindowsDriver:
if answer is None:
answer = FIXTURE.read_text()
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(answer if isinstance(answer, str) else json.dumps(answer))
return d
def _fixture() -> dict[str, Any]:
return json.loads(FIXTURE.read_text())
@pytest.fixture(autouse=True)
def _now(monkeypatch):
monkeypatch.setattr(mod.time, "time", lambda: NOW)
def _kinds(reading) -> list[tuple[str, str | None]]:
return [(e["kind"], e["subject"]) for e in reading["events"]]
class TestTheEvents:
def test_every_event_as_its_kind_and_subject_newest_first(self):
assert _kinds(_driver().get_host_events()) == [
("app_crash", r"C:\Program Files\Vendor\vendorapp.exe"),
("app_crash", r"C:\Program Files\Vendor\vendorapp.exe"),
("app_crash", "legacy.exe"),
("service_crash", "Backup Agent"),
("hardware_error_corrected", None),
("disk_error", r"\Device\Harddisk1\DR1"),
("service_crash", "Vendor Sync"),
("hardware_error_corrected", None),
("system_crash", "0x0000009f"),
("unexpected_shutdown", None),
("unexpected_shutdown", "0x0000009f"),
("disk_error", r"\Device\Harddisk1\DR1"),
("disk_error", "D:"),
("hardware_error_fatal", None),
("unexpected_shutdown", None),
]
def test_an_event_says_when_where_and_what_the_host_wrote(self):
crash = next(
e for e in _driver().get_host_events()["events"] if e["kind"] == "system_crash"
)
assert crash == {
"kind": "system_crash",
"time": "2025-11-30T02:35:50+00:00",
"subject": "0x0000009f",
"source": "System: Microsoft-Windows-WER-SystemErrorReporting 1001",
"message": crash["message"],
}
assert crash["message"].startswith("The computer has rebooted from a bugcheck.")
def test_a_power_loss_without_a_bugcheck_has_no_stop_code(self):
shutdowns = [
e for e in _driver().get_host_events()["events"] if e["kind"] == "unexpected_shutdown"
]
assert [e["subject"] for e in shutdowns] == [None, "0x0000009f", None]
def test_the_hosts_message_is_cut(self):
answer = _fixture()
answer["parts"]["rare"]["events"][0]["message"] = "y" * 5000
events = _driver(answer).get_host_events()["events"]
assert max(len(e["message"] or "") for e in events) == 300
def test_an_event_the_reading_does_not_know_is_left_out(self):
answer = _fixture()
answer["parts"]["rare"]["events"] = [
{"provider": "Microsoft-Windows-Kernel-General", "id": 12, "time": NOW, "props": []}
]
kinds = {e["kind"] for e in _driver(answer).get_host_events()["events"]}
assert "unexpected_shutdown" not in kinds
def test_a_single_event_is_still_a_list(self):
answer = _fixture()
answer["parts"]["apps"]["events"] = answer["parts"]["apps"]["events"][0]
apps = [e for e in _driver(answer).get_host_events()["events"] if e["kind"] == "app_crash"]
assert len(apps) == 1
class TestWhatWasRead:
def test_a_full_reading_names_nothing_capped_or_unread(self):
reading = _driver().get_host_events()
assert (reading["capped"], reading["unread"]) == ([], [])
def test_an_empty_log_is_no_events_not_an_error(self):
"""What the script makes of ``NoMatchingEventsFound``: read, nothing found."""
answer = _fixture()
for part in answer["parts"].values():
part["events"] = []
reading = _driver(answer).get_host_events()
assert (reading["events"], reading["unread"]) == ([], [])
def test_a_query_that_failed_names_its_kinds_unread(self):
answer = _fixture()
answer["parts"]["frequent"] = {"ok": False, "capped": False, "events": [], "error": "x"}
reading = _driver(answer).get_host_events()
assert reading["unread"] == ["hardware_error_corrected", "disk_error", "service_crash"]
assert "service_crash" not in {e["kind"] for e in reading["events"]}
def test_a_query_read_up_to_its_bound_names_its_kinds_capped(self):
answer = _fixture()
answer["parts"]["apps"]["capped"] = True
assert _driver(answer).get_host_events()["capped"] == ["app_crash"]
def test_a_part_missing_from_the_answer_is_unread(self):
answer = _fixture()
del answer["parts"]["apps"]
assert _driver(answer).get_host_events()["unread"] == ["app_crash"]
def test_every_kind_is_read_by_some_query(self):
read = {kind for kinds in mod._PART_KINDS.values() for kind in kinds}
assert read == set(HOST_EVENT_KINDS)
@pytest.mark.parametrize("answer", ["", "[]", '{"since": 1}'])
def test_an_answer_without_a_report_raises(self, answer):
with pytest.raises(ValueError):
_driver(answer).get_host_events()
class TestTheWindow:
def test_a_week_by_default(self):
d = _driver()
reading = d.get_host_events()
assert reading["since"] == "2025-11-23T10:53:20+00:00"
assert "@SystemTime>='2025-11-23T10:53:20.000Z'" in d._transport.sent[0]
def test_the_callers_start(self):
d = _driver()
reading = d.get_host_events(since=NOW - 3600)
assert reading["since"] == "2025-11-30T09:53:20+00:00"
assert "@SystemTime>='2025-11-30T09:53:20.000Z'" in d._transport.sent[0]
class TestTheScript:
script = mod.host_events_script(NOW - WEEK)
def test_every_query_catches_no_matching_events(self):
assert self.script.count("Get-WinEvent") == 1
assert "NoMatchingEventsFound" in self.script
assert len(re.findall(r"\(Q '(System|Application)'", self.script)) == 3
def test_every_query_is_bounded_by_count(self):
bounds = [int(n) for n in re.findall(r"\(Q '\w+' \$\w+ (\d+)", self.script)]
assert bounds == [100, 500, 200]
assert "-MaxEvents $max" in self.script
def test_every_query_is_bounded_by_time(self):
assert self.script.count("TimeCreated[@SystemTime>=") == 3
def test_only_the_rare_events_carry_their_message(self):
assert re.findall(r"\(Q '\w+' \$\w+ \d+ \$(true|false)\)", self.script) == [
"true",
"false",
"false",
]
def test_the_answer_survives_a_deep_object(self):
assert "-Depth 6" in self.script
def test_stops_on_errors_it_does_not_catch(self):
assert self.script.lstrip().startswith("$ErrorActionPreference = 'Stop'")
def test_the_driver_carries_the_contract(self):
assert isinstance(WindowsDriver("h", "u", "p"), HostEventsMixin)
+13
View File
@@ -637,3 +637,16 @@ def test_a_written_task_reads_back_as_the_spec():
spec["description"],
)
assert f"<Command>{execute}</Command>" in xml
def test_an_update_run_task_is_the_drivers_own_and_offers_nothing() -> None:
"""A run's SYSTEM task (``windows_update_run``) is no administrator's job, and while it
exists it is not to be switched or started again (netork#2892)."""
reading = _reading()
task = copy.deepcopy(reading["tasks"][0])
task.update(path="\\napalm-windows\\", name="update-run-0123456789ab", description="")
reading["tasks"].append(task)
reading["count"] += 1
job = _jobs(reading)["task:\\napalm-windows\\update-run-0123456789ab"]
assert job["managed_by"] == "application"
assert job["actions"] == []
-125
View File
@@ -1,125 +0,0 @@
"""The host's services and how each one's last run ended (NetOrk/netork#2897).
``Win32_Service`` says whether a service runs and how it starts, and also what its
last run ended with: ``ExitCode`` (``1066`` hands over to
``ServiceSpecificExitCode``, ``1077`` is "not started since boot"). Together with
whether a trigger starts it (a ``TriggerInfo`` key under the service) that tells a
service that died from one stopped on purpose. The reading is the shape of
tests/fixtures/synthetic/services.json.
"""
from __future__ import annotations
import json
from pathlib import Path
from napalm_windows import WindowsDriver
from napalm_windows import services as mod
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "services.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 if script == mod._PS_SERVICES else ""
def _services(answer: str | None = None) -> dict[str, dict]:
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(FIXTURE.read_text() if answer is None else answer)
return {s["name"]: s for s in d.get_services()}
class TestRunningAndEnabled:
def test_maps_state_and_start_mode(self):
services = _services()
assert {n: (s["running"], s["enabled"], s["pid"]) for n, s in services.items()} == {
"WinRM": (True, True, 1234),
"Spooler": (False, False, 0),
"MSSQL$SQLEXPRESS": (True, True, 4321),
"RemoteRegistry": (False, False, 0),
"wuauserv": (False, False, 0),
"AppReadiness": (False, True, 0),
"BackupAgent": (False, True, 0),
"VendorSync": (False, True, 0),
"BthServ": (False, True, 0),
}
def test_a_single_service_is_still_a_list(self):
one = json.loads(FIXTURE.read_text())[0]
assert list(_services(json.dumps(one))) == ["WinRM"]
def test_nothing_read_is_no_services(self):
assert _services("") == {}
class TestHowTheLastRunEnded:
def test_a_running_service_succeeded(self):
assert _services()["WinRM"] == {
"name": "WinRM",
"running": True,
"enabled": True,
"pid": 1234,
"result": "success",
"exit_code": None,
"trigger_start": False,
"account": "NT AUTHORITY\\NetworkService",
}
def test_one_stopped_on_purpose_succeeded(self):
assert (_services()["Spooler"]["result"], _services()["Spooler"]["exit_code"]) == (
"success",
None,
)
def test_one_not_started_since_boot_has_no_result(self):
"""1077: a delayed or a demand-start service that has not run yet."""
service = _services()["AppReadiness"]
assert (service["result"], service["exit_code"]) == (None, None)
def test_one_that_died_ended_with_its_exit_code(self):
"""1067: the process terminated unexpectedly."""
service = _services()["BackupAgent"]
assert (service["result"], service["exit_code"]) == ("exit-code", 1067)
def test_a_service_specific_error_is_the_services_own_code(self):
service = _services()["VendorSync"]
assert (service["result"], service["exit_code"]) == ("exit-code", 2147942405)
def test_a_trigger_start_service_says_so(self):
assert _services()["BthServ"]["trigger_start"] is True
assert _services()["BackupAgent"]["trigger_start"] is False
def test_the_account_it_runs_as(self):
assert _services()["BackupAgent"]["account"] == "CORP\\svc-backup"
assert _services()["BthServ"]["account"] is None
def test_a_reading_without_the_new_fields_says_nothing_of_them(self):
"""An older script's answer: running and enabled only, nothing invented."""
old = [{"name": "WinRM", "state": "Stopped", "start_mode": "Auto", "pid": 0}]
service = _services(json.dumps(old))["WinRM"]
assert (service["result"], service["exit_code"], service["trigger_start"]) == (
None,
None,
False,
)
class TestTheScript:
def test_exit_codes_leave_the_host_as_wide_integers(self):
"""``ServiceSpecificExitCode`` is a UInt32: ``[int]`` would throw on an HRESULT."""
assert "[int64]$_.ExitCode" in mod._PS_SERVICES
assert "[int64]$_.ServiceSpecificExitCode" in mod._PS_SERVICES
def test_trigger_start_is_read_once_from_the_registry(self):
assert r"Services\*\TriggerInfo" in mod._PS_SERVICES
assert "-ErrorAction SilentlyContinue" in mod._PS_SERVICES
def test_a_list_goes_through_input_object(self):
assert "-InputObject @(" in mod._PS_SERVICES
+13
View File
@@ -370,6 +370,19 @@ class TestGetRouteTo:
assert list(routes) == ["192.168.50.0/24"]
class TestGetServices:
def test_maps_state_and_start_mode(self):
services = _driver(_PS_SERVICES=_fixture("services.json")).get_services()
assert services == [
{"name": "WinRM", "running": True, "enabled": True, "pid": 1234},
{"name": "Spooler", "running": False, "enabled": False, "pid": 0},
{"name": "MSSQL$SQLEXPRESS", "running": True, "enabled": True, "pid": 4321},
{"name": "RemoteRegistry", "running": False, "enabled": False, "pid": 0},
{"name": "wuauserv", "running": False, "enabled": False, "pid": 0},
]
class TestGetListeningSockets:
"""netOrk #673: what listens, and which Windows service it is."""
+329
View File
@@ -0,0 +1,329 @@
"""Windows Update: the search, the pending list read from it, and the history (netork#2892).
A fake transport answers each script from tests/fixtures/synthetic/wu_*.json, the JSON
the scripts are written to emit. What a real host emits the fixtures cannot prove --
see the README there.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_device_types import PackageIndexMissing
from napalm_windows import WindowsDriver
from napalm_windows import windows_update as mod
from napalm_windows.transport import PowerShellError
FIXTURES = Path(__file__).parent / "fixtures" / "synthetic"
CU = "Cumulative-Update-for-Microsoft-server-operating-system-version-21H2-for-x64-based-Systems"
DEFENDER = "Security-Intelligence-Update-for-Microsoft-Defender-Antivirus-Current-Channel-Broad"
DOTNET = (
"Cumulative-Update-for-.NET-Framework-3.5-4.8-and-4.8.1-for-Microsoft-server-operating-"
"system-version-21H2-for-x64"
)
MSRT = "Windows-Malicious-Software-Removal-Tool-x64"
def _fixture(name: str) -> Any:
return json.loads((FIXTURES / f"wu_{name}.json").read_text())
class FakeTransport:
"""Answers each Windows Update script with its canned output; records them all."""
def __init__(self, answers: dict[str, Any]):
self.answers = answers
self.sent: list[str] = []
self.is_open = True
def run(self, script: str) -> str:
self.sent.append(script)
answer = self.answers[script]
if isinstance(answer, Exception):
raise answer
return answer if isinstance(answer, str) else json.dumps(answer)
def close(self) -> None:
self.is_open = False
def _driver(**answers: Any) -> WindowsDriver:
scripts = {
"search": mod._PS_WU_SEARCH,
"pending": mod._PS_WU_PENDING,
"history": mod._PS_WU_HISTORY,
}
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport({scripts[k]: v for k, v in answers.items()}) # type: ignore[assignment]
return d
# ---------------------------------------------------------------------------
# Names
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(
("title", "name"),
[
(
"2026-11 Cumulative Update for Microsoft server operating system version 21H2 "
"for x64-based Systems (KB5070000)",
CU,
),
(
"Security Intelligence Update for Microsoft Defender Antivirus - KB2267602 "
"(Version 1.441.120.0) - Current Channel (Broad)",
DEFENDER,
),
("Windows Malicious Software Removal Tool x64 - v5.141 (KB890830)", MSRT),
(
"2026-01 Cumulative Update for Windows 11, version 24H2 for x64-based Systems "
"(KB5050009) (26100.2894)",
"Cumulative-Update-for-Windows-11-version-24H2-for-x64-based-Systems",
),
(
"2026-11 Kumulatives Update für Microsoft Server Operating System, Version 21H2 "
"für x64-basierte Systeme (KB5070000)",
"Kumulatives-Update-fur-Microsoft-Server-Operating-System-Version-21H2-fur-"
"x64-basierte-Systeme",
),
],
)
def test_an_update_is_named_by_what_it_keeps_from_month_to_month(title: str, name: str) -> None:
"""Next month's cumulative update replaces this one under the same name, so the time
the host has been waiting for it is not reset each month: the date, the KB article
and the version are left out of the name."""
assert mod.update_name(title, ["5070000"], "8f5c0d55-3b0f-4ad0-9a3e-1a8a0d7f6e11") == name
assert mod.NAME.fullmatch(name)
def test_a_title_with_nothing_left_is_named_by_its_kb_then_by_its_id() -> None:
assert mod.update_name("(KB5070000)", ["5070000"], "x") == "KB5070000"
assert mod.update_name("", [], "8f5c0d55-3b0f") == "8f5c0d55-3b0f"
def test_a_long_title_is_cut_to_a_name_a_store_keeps() -> None:
name = mod.update_name("Update " * 80, [], "x")
assert len(name) <= mod.NAME_MAX
assert not name.endswith("-")
# ---------------------------------------------------------------------------
# Pending updates: read from the last search, never searching in the poll
# ---------------------------------------------------------------------------
def _pending(**kw: Any) -> dict[str, dict[str, Any]]:
answers = {"pending": _fixture("pending"), **kw}
return {u["name"]: dict(u) for u in _driver(**answers).get_available_updates()}
def test_the_pending_list_is_the_last_search_without_what_was_installed_since() -> None:
"""The Defender update was installed an hour after the search; the cumulative update
has an install in the history, but from before the search -- it is offered again."""
pending = _pending()
assert sorted(pending) == sorted([CU, DOTNET, MSRT])
def test_a_pending_update_says_what_it_fixes() -> None:
cu = _pending()[CU]
assert cu == {
"name": CU,
"current_version": "",
"new_version": "KB5070000",
"origin": "Windows Update",
"security": True,
"title": (
"2026-11 Cumulative Update for Microsoft server operating system version 21H2 "
"for x64-based Systems (KB5070000)"
),
"advisories": ["KB5070000"],
"cves": ["CVE-2026-21001", "CVE-2026-21002", "CVE-2026-21003"],
"vendor_severity": "Critical",
}
def test_security_is_what_windows_classifies_so() -> None:
pending = _pending()
assert pending[DOTNET]["security"] is True
assert pending[DOTNET]["vendor_severity"] == "Important"
# The removal tool is an update rollup: known, and not a security update.
assert pending[MSRT]["security"] is False
assert pending[MSRT]["vendor_severity"] is None
assert pending[MSRT]["cves"] == []
def test_optional_updates_and_feature_upgrades_are_not_pending() -> None:
"""A preview Windows does not install by itself, and an in-place upgrade of the OS,
are no pending updates: this path installs neither."""
names = set(_pending())
assert not any("Preview" in n for n in names)
assert not any("upgrade" in n for n in names)
def test_definition_updates_count_as_security() -> None:
search = _fixture("search")
reading = {"search": json.dumps(search), "installed": [], "history_error": None}
assert _pending(pending=reading)[DEFENDER]["security"] is True
def test_updates_of_the_same_name_are_one_entry() -> None:
search = _fixture("search")
twin = dict(search["updates"][0], id="00000000-0000-4000-8000-000000000001")
twin.update(kb=["5070001"], cves=["CVE-2026-21009"], severity="Moderate")
search["updates"].append(twin)
reading = {"search": json.dumps(search), "installed": [], "history_error": None}
cu = _pending(pending=reading)[CU]
assert cu["new_version"] == "KB5070000 KB5070001"
assert cu["advisories"] == ["KB5070000", "KB5070001"]
assert cu["cves"] == ["CVE-2026-21001", "CVE-2026-21002", "CVE-2026-21003", "CVE-2026-21009"]
assert cu["vendor_severity"] == "Critical" # the higher of the two
def test_an_update_without_a_kb_shows_its_revision() -> None:
search = _fixture("search")
search["updates"][3]["kb"] = []
reading = {"search": json.dumps(search), "installed": [], "history_error": None}
assert _pending(pending=reading)[MSRT]["new_version"] == "rev 1"
def test_a_wsus_client_names_its_server() -> None:
search = dict(_fixture("search"), wsus="https://wsus.example.lan:8531")
reading = {"search": json.dumps(search), "installed": [], "history_error": None}
assert _pending(pending=reading)[CU]["origin"] == "WSUS https://wsus.example.lan:8531"
def test_no_search_yet_is_a_missing_index_that_a_refresh_cures() -> None:
with pytest.raises(PackageIndexMissing, match="refresh"):
_pending(pending={"search": None, "installed": [], "history_error": None})
def test_a_failed_history_read_keeps_the_search_as_it_was() -> None:
reading = dict(_fixture("pending"), installed=[], history_error="0x8024000C")
assert DEFENDER in _pending(pending=reading)
def test_a_reading_that_is_no_search_raises() -> None:
with pytest.raises(ValueError, match="Windows Update"):
_pending(pending={"search": "[1, 2]", "installed": [], "history_error": None})
def test_the_poll_does_not_search() -> None:
"""The search takes minutes: the poll reads what the refresh found."""
d = _driver(pending=_fixture("pending"))
d.get_available_updates()
assert d._transport.sent == [mod._PS_WU_PENDING] # type: ignore[union-attr]
# ---------------------------------------------------------------------------
# Refresh: the search itself
# ---------------------------------------------------------------------------
def test_the_refresh_searches_and_says_what_it_found() -> None:
result = _driver(search=_fixture("search")).refresh_available_updates()
assert result["success"] is True
assert result["output"] == (
"Windows Update offers 4 updates, 3 of them for security, searched in 94 s."
)
def test_a_refresh_windows_refuses_is_a_failed_refresh() -> None:
d = _driver(search=PowerShellError("Exception from HRESULT: 0x8024402C"))
assert d.refresh_available_updates() == {
"success": False,
"output": "Exception from HRESULT: 0x8024402C",
}
def test_a_search_script_keeps_what_it_found_for_the_poll() -> None:
"""The search writes its reading where only administrators can write, and the poll's
script reads it there."""
assert "Set-ItemProperty" in mod._PS_WU_SEARCH
assert mod.STORE in mod._PS_WU_SEARCH and mod.STORE in mod._PS_WU_PENDING
assert mod.STORE.startswith("HKLM:\\SOFTWARE\\napalm-windows\\")
assert "Type='Software'" in mod._PS_WU_SEARCH # no drivers
# ---------------------------------------------------------------------------
# History
# ---------------------------------------------------------------------------
def _history(since: int | None = None, reading: Any = None) -> list[dict[str, Any]]:
d = _driver(history=_fixture("history") if reading is None else reading)
return [dict(t) for t in d.get_update_history(since)]
def test_each_history_entry_is_a_transaction_newest_first() -> None:
history = _history()
assert [t["start"] for t in history] == sorted((t["start"] for t in history), reverse=True)
first = history[0]
assert first == {
"id": "d2b5e0a8-6c3e-4c9b-8a55-0f6b5bb2a1c4:200:1:1795603600",
"start": 1795603600,
"end": 1795603600,
"packages": [
{
"name": DEFENDER,
"action": "install",
"old_version": None,
"new_version": "KB2267602",
"title": (
"Security Intelligence Update for Microsoft Defender Antivirus - KB2267602 "
"(Version 1.441.120.0) - Current Channel (Broad)"
),
}
],
"requested_by": "Windows Defender (77BDAF73-B396-481F-9042-AD358843EC24)",
"command": None,
"error": None,
}
def test_a_failed_install_names_its_error() -> None:
failed = next(t for t in _history() if t["requested_by"] == "napalm-windows")
assert failed["error"] == "failed (0x80240017)"
def test_an_uninstall_removes_its_kb() -> None:
removed = next(t for t in _history() if t["packages"][0]["action"] == "remove")
assert removed["packages"][0]["old_version"] == "KB5007651"
assert removed["packages"][0]["new_version"] is None
def test_an_install_still_running_has_no_end_and_an_unknown_requester() -> None:
running = _history()[-1]
assert running["end"] is None
assert running["requested_by"] is None
assert running["error"] is None
def test_the_history_since_a_moment() -> None:
assert [t["start"] for t in _history(since=1795590000)] == [1795603600, 1795590000]
def test_an_empty_history() -> None:
assert _history(reading="") == []
def test_other_results_are_named() -> None:
entry = dict(_fixture("history")[0], result=5, hresult=0)
assert _history(reading=[entry])[0]["error"] == "aborted"
entry = dict(entry, result=3, hresult=-2145124329)
assert _history(reading=[entry])[0]["error"] == "succeeded with errors (0x80240017)"
def test_one_name_is_unknown_security_when_one_of_its_updates_does_not_say() -> None:
search = _fixture("search")
twin = dict(search["updates"][3], id="00000000-0000-4000-8000-000000000002")
twin["classifications"] = []
search["updates"].append(twin)
reading = {"search": json.dumps(search), "installed": [], "history_error": None}
assert _pending(pending=reading)[MSRT]["security"] is None
+271
View File
@@ -0,0 +1,271 @@
"""Installing Windows updates in a one-shot SYSTEM task (netork#2892).
The transport is faked: each script the run sends is recognised by what it does and
answered as the host would. The SYSTEM script itself is read here as text; what Windows
Update does with it only a real host can show.
"""
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 windows_update as wu
from napalm_windows import windows_update_run as mod
from napalm_windows.transport import PowerShellError
FIXTURES = Path(__file__).parent / "fixtures" / "synthetic"
CU_ID = "8f5c0d55-3b0f-4ad0-9a3e-1a8a0d7f6e11:1"
DOTNET_ID = "1c7f9e2a-5b4d-4e0f-9d8c-3a2b1c0d9e8f:3"
MSRT_ID = "6a0d3c1e-9f8b-4d7a-8e6c-5b4a3f2e1d0c:1"
CU = "Cumulative-Update-for-Microsoft-server-operating-system-version-21H2-for-x64-based-Systems"
MSRT = "Windows-Malicious-Software-Removal-Tool-x64"
class Host:
"""The host's side of a run: what the sweep finds, and what each look shows."""
def __init__(
self,
looks: list[dict[str, Any]] | None = None,
busy: list[str] | None = None,
start_fails: str | None = None,
):
self.looks = list(looks or [])
self.busy = busy or []
self.start_fails = start_fails
self.sent: list[str] = []
self.is_open = True
def kind(self, script: str) -> str:
if script == wu._PS_WU_PENDING:
return "pending"
if "busy" in script and "Unregister-ScheduledTask" in script:
return "sweep"
if "Register-ScheduledTask" in script:
return "start"
if "$state = 'gone'" in script:
return "follow"
if "Remove-Item -LiteralPath $key" in script:
return "cleanup"
raise AssertionError(f"unexpected script: {script[:80]}")
def run(self, script: str) -> str:
kind = self.kind(script)
self.sent.append(kind)
if kind == "pending":
return (FIXTURES / "wu_pending.json").read_text()
if kind == "sweep":
return json.dumps({"busy": self.busy, "swept": ["update-run-0123456789ab"]})
if kind == "start":
self.start_script = script
if self.start_fails:
raise PowerShellError(self.start_fails)
return ""
if kind == "follow":
return json.dumps(self.looks.pop(0))
return ""
def close(self) -> None:
self.is_open = False
def _look(state: str, log: list[str], result: dict[str, Any] | None = None) -> dict[str, Any]:
return {"state": state, "log": "\n".join(log), "result": json.dumps(result) if result else ""}
def _result(**kw: Any) -> dict[str, Any]:
return {
"reboot_required": False,
"installed": [],
"refused": [],
"failed": [],
"error": None,
**kw,
}
@pytest.fixture(autouse=True)
def no_waiting(monkeypatch: pytest.MonkeyPatch) -> list[float]:
slept: list[float] = []
monkeypatch.setattr(mod.time, "sleep", slept.append)
return slept
def _driver(host: Host) -> WindowsDriver:
d = WindowsDriver("win01", "admin", "secret")
d._transport = host # type: ignore[assignment]
return d
def test_a_run_installs_in_a_system_task_and_hands_on_each_line() -> None:
host = Host(
[
_look("Running", ["Searching Windows Update again for the chosen updates"]),
_look(
"Ready",
[
"Searching Windows Update again for the chosen updates",
"Downloading 1 update(s)",
"Installing 1 update(s); the host is not restarted",
"Installed: 2026-11 Cumulative Update ... (KB5070000) (" + CU_ID + ")",
"A restart finishes the installation.",
],
_result(installed=[CU_ID], reboot_required=True),
),
]
)
seen: list[str] = []
result = _driver(host).apply_updates([CU], log=seen.append)
assert result["success"] is True
assert "error" not in result
assert host.sent == ["pending", "sweep", "start", "follow", "follow", "cleanup"]
assert seen[0].startswith("Chosen: 2026-11 Cumulative Update")
assert seen[1:] == [
"Searching Windows Update again for the chosen updates",
"Downloading 1 update(s)",
"Installing 1 update(s); the host is not restarted",
"Installed: 2026-11 Cumulative Update ... (KB5070000) (" + CU_ID + ")",
"A restart finishes the installation.",
]
assert result["output"] == "\n".join(seen)
def test_the_task_gets_exactly_the_updates_chosen_and_runs_as_system() -> None:
host = Host([_look("Ready", [], _result(installed=[CU_ID]))])
_driver(host).apply_updates([CU])
start = host.start_script
assert f"@('{CU_ID}')" in start
assert DOTNET_ID not in start
assert "-UserId 'SYSTEM'" in start and "-RunLevel Highest" in start
assert "Register-ScheduledTask -TaskPath '\\napalm-windows\\'" in start
# The script travels in the run's registry key, never as a file.
assert "-Name Script" in start and ".ps1" not in start
def test_every_pending_update_when_none_is_named() -> None:
host = Host([_look("Ready", [], _result(installed=[CU_ID, DOTNET_ID, MSRT_ID]))])
assert _driver(host).apply_updates([])["success"] is True
for identity in (CU_ID, DOTNET_ID, MSRT_ID):
assert f"'{identity}'" in host.start_script
def test_a_name_the_last_search_does_not_offer_is_refused_and_the_rest_installed() -> None:
host = Host([_look("Ready", ["Installed: x"], _result(installed=[MSRT_ID]))])
seen: list[str] = []
result = _driver(host).apply_updates([MSRT, "Gone-Update"], log=seen.append)
assert seen[0] == "Refused Gone-Update: not offered by the last search"
assert result["success"] is False
assert result["error"] == "1 update(s) refused, 0 failed."
def test_only_names_the_search_does_not_offer_start_nothing() -> None:
host = Host()
result = _driver(host).apply_updates(["Gone-Update"])
assert result["success"] is False
assert host.sent == ["pending"]
def test_nothing_pending_is_nothing_to_install() -> None:
result = mod.install(lambda s: "", {}, [], None)
assert result == {"success": True, "output": "Nothing to install."}
def test_a_name_that_is_no_package_name_is_refused_before_anything_runs() -> None:
host = Host()
with pytest.raises(ValueError, match="Invalid update name"):
_driver(host).apply_updates(["KB1; Restart-Computer"])
assert host.sent == []
def test_what_the_task_refused_or_failed_makes_the_run_fail() -> None:
refused = {"id": CU_ID, "reason": "it asks for input while it installs"}
failed = {"id": DOTNET_ID, "step": "Install", "result": 4, "hresult": -2145124329}
host = Host([_look("Ready", [], _result(refused=[refused], failed=[failed]))])
result = _driver(host).apply_updates([])
assert result["success"] is False
assert result["error"] == "1 update(s) refused, 1 failed."
def test_a_pending_restart_installs_nothing_and_says_so() -> None:
error = "A restart is pending on the host: nothing is installed until it has restarted."
host = Host([_look("Ready", [error], _result(error=error))])
result = _driver(host).apply_updates([CU])
assert result["success"] is False
assert result["error"] == error
def test_a_task_that_ends_without_a_result_failed_and_is_cleaned_up() -> None:
host = Host([_look("Ready", ["Downloading 1 update(s)"])])
result = _driver(host).apply_updates([CU])
assert result["success"] is False
assert result["error"] == "The update task ended without a result."
assert host.sent[-1] == "cleanup"
def test_an_earlier_run_still_installing_refuses_this_one() -> None:
host = Host(busy=["update-run-0123456789ab"])
result = _driver(host).apply_updates([CU])
assert result["success"] is False
assert "still installing" in result["error"]
assert host.sent == ["pending", "sweep"]
def test_a_run_followed_too_long_is_left_to_finish_on_the_host(
monkeypatch: pytest.MonkeyPatch,
) -> None:
clock = iter([0.0, 10.0, mod.FOLLOW_SECONDS + 1.0])
monkeypatch.setattr(mod.time, "monotonic", lambda: next(clock))
host = Host([_look("Running", ["Downloading 1 update(s)"]), _look("Running", [])])
result = _driver(host).apply_updates([CU])
assert result["success"] is False
assert "carries on there" in result["error"]
assert "cleanup" not in host.sent # the next run's sweep deletes it once it ended
def test_a_task_windows_refuses_to_register_raises() -> None:
host = Host(start_fails="Access is denied.")
with pytest.raises(PowerShellError, match="Access is denied"):
_driver(host).apply_updates([CU])
def test_the_follower_waits_between_looks(no_waiting: list[float]) -> None:
host = Host([_look("Running", []), _look("Ready", [], _result(installed=[CU_ID]))])
_driver(host).apply_updates([CU])
assert no_waiting == [mod.POLL_SECONDS, mod.POLL_SECONDS]
# ---------------------------------------------------------------------------
# The SYSTEM script, read as text
# ---------------------------------------------------------------------------
def test_the_system_script_guards_what_it_installs() -> None:
script = mod.run_script("0123456789ab")
assert "HKLM:\\SOFTWARE\\napalm-windows\\WindowsUpdate\\Runs\\0123456789ab" in script
# A pending restart refuses everything before any download.
assert script.index("$pending -or $installer.RebootRequiredBeforeInstallation") < (
script.index("CreateUpdateDownloader")
)
# Exactly the ID and revision, offered once, quiet, licence accepted on the host.
assert "no longer offered" in script
assert "offered more than once" in script
assert "CanRequestUserInput" in script
assert "EulaAccepted" in script
assert "AcceptEula" not in script
# Never restarts, and Windows Update's history names the run.
assert "Restart-Computer" not in script and "shutdown" not in script.lower()
assert "ClientApplicationID = 'napalm-windows'" in script
def test_the_scripts_quote_what_they_are_given() -> None:
start = mod._script(mod._PS_START, RUN="'x'", TASK="'t'", REQUESTED="'a'", SCRIPT="'s'")
assert "__" not in start
for template in (mod._PS_SWEEP, mod._PS_FOLLOW, mod._PS_CLEANUP):
assert "__" not in mod._script(template, RUN="'x'", TASK="'t'")
+7 -12
View File
@@ -13,16 +13,8 @@ from __future__ import annotations
import argparse
import getpass
import pathlib
import time
from napalm_windows import (
WindowsDriver,
event_channels,
host_events,
scheduled_tasks,
services,
time_sync,
)
from napalm_windows import WindowsDriver, scheduled_tasks, time_sync, windows_update
from napalm_windows import windows as mod
SCRIPTS = {
@@ -31,12 +23,15 @@ SCRIPTS = {
"interfaces_ip": mod._PS_INTERFACES_IP,
"arp": mod._PS_ARP,
"routes": mod._PS_ROUTES,
"services": services._PS_SERVICES,
"services": mod._PS_SERVICES,
"listening": mod._PS_LISTENING,
"scheduled_tasks": scheduled_tasks._PS_SCHEDULED_TASKS,
"time_sync": time_sync._PS_TIME_SYNC,
"host_events": host_events.host_events_script(time.time() - 7 * 86400),
"event_channels": event_channels._PS_EVENT_CHANNELS,
# The search takes minutes and keeps its reading under HKLM\SOFTWARE\napalm-windows,
# which the pending reading after it reads back. Nothing is installed.
"wu_search": windows_update._PS_WU_SEARCH,
"wu_pending": windows_update._PS_WU_PENDING,
"wu_history": windows_update._PS_WU_HISTORY,
}
OUT = pathlib.Path(__file__).parent / "harvest-out"