Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f8f46c133d | ||
|
|
891a31fe45 | ||
|
|
54b3c9b362 | ||
|
|
81c4df3159 | ||
|
|
169d88f7e5 | ||
|
|
a97e59c1e2 | ||
|
|
8ed5e0ed87 |
No files matched your search
+28
-17
@@ -7,23 +7,34 @@ 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`.
|
||||
- The host's SMBIOS identity, what ties it to its BMC (NetOrk/netork#2888):
|
||||
`get_system_identity` reads the system UUID and product serial
|
||||
(`Win32_ComputerSystemProduct`), the board serial (`Win32_BaseBoard`) and the system
|
||||
firmware's vendor, version and release date (`Win32_BIOS`) in one script of its own.
|
||||
Vendor placeholders such as "To be filled by O.E.M." or an all-F UUID read as empty,
|
||||
by napalm-device-types' rules (`clean_system_identity`).
|
||||
- Running processes (NetOrk/netork#2889): `get_processes` lists them the way `ps` does --
|
||||
parent, owner, CPU and memory share, virtual and resident size, start and command line
|
||||
-- from `Win32_Process` and `Get-Process -IncludeUserName` in one script. A process
|
||||
that exited between the two reads, or whose PID was reused in between, is left out.
|
||||
- Local accounts (NetOrk/netork#2889): `get_os_users` lists the host's own accounts with
|
||||
their local groups and profile folder. `uid` is the account's relative identifier
|
||||
(500 for the built-in Administrator), `sid` its whole security identifier. A domain
|
||||
controller, which has no local accounts, and a host without the LocalAccounts cmdlets
|
||||
raise `NotImplementedError`.
|
||||
- Installed software (NetOrk/netork#2890): `get_packages` lists the programs installed
|
||||
for the whole machine from the Uninstall keys, the 64-bit and the 32-bit ones, each
|
||||
with its publisher and architecture; `source` is `msi` or `exe`. Hidden system
|
||||
components and updates listed under their product are left out. Programs installed
|
||||
for one user only, and Store apps, are not read yet; nothing is installed or removed.
|
||||
- Restart required and automatic updates (NetOrk/netork#2891): `get_host_status` says
|
||||
the host needs a restart when Windows Update or component servicing waits for one;
|
||||
pending file renames, a pending update executable and a new computer name are named
|
||||
in the reason but do not count on their own. Automatic updates follow the Windows
|
||||
Update policy (`NoAutoUpdate`, `AUOptions`); without one a Windows client installs on
|
||||
its own and a server follows its local setting. When they last succeeded is the
|
||||
latest successful installation Windows Update recorded; the system drive's size and
|
||||
free space come with it. Nothing searches for updates during the reading.
|
||||
- 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
|
||||
|
||||
@@ -36,14 +36,17 @@ 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` |
|
||||
| `get_system_identity` | `Win32_ComputerSystemProduct` (UUID, serial), `Win32_BaseBoard`, `Win32_BIOS`; placeholders empty (napalm-device-types' `clean_system_identity`). See *Host basics* |
|
||||
| `get_processes` | `Win32_Process` joined with `Get-Process -IncludeUserName` by PID and start, shaped like `ps` |
|
||||
| `get_os_users` | `Get-LocalUser`, `Get-LocalGroup` + `Get-LocalGroupMember` (ADSI fallback), `Win32_UserProfile`; the RID as `uid`, the SID as `sid` |
|
||||
| `get_packages` | The machine-wide Uninstall keys, native and `WOW6432Node`; no per-user installs, no Store apps, nothing installed |
|
||||
| `get_host_status` | `Microsoft.Update.SystemInfo`, the registry's restart markers, the Windows Update policy and history, the system drive |
|
||||
| `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 +102,31 @@ 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
|
||||
### Host basics
|
||||
|
||||
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`.
|
||||
* **Identity.** Windows decodes the SMBIOS system UUID the way dmidecode does; the
|
||||
release date is CIM's midnight UTC, read as that day.
|
||||
* **Processes.** `cpu` is the CPU time over the time since the start, per logical
|
||||
processor; `memory` the working set over the visible memory; `started` the local time
|
||||
as `ps -o lstart` prints it. Windows has no controlling terminal and no `ps` state:
|
||||
`tty` and `state` are empty. The owner needs an elevated session; without one it is
|
||||
empty. PID 0 (System Idle Process) is no process.
|
||||
* **Local accounts.** `gid` is 513, the primary group of every local account; `home` is
|
||||
the profile folder, empty until the account first logs on; `shell` is empty.
|
||||
* **Packages.** A 32-bit and a 64-bit install of one program are two packages, told
|
||||
apart by `architecture`. Keys without a `DisplayName`, `SystemComponent=1` and
|
||||
entries with a `ParentKeyName` are left out.
|
||||
* **Restart required** is Windows Update's `RebootRequired` (or its registry marker) or
|
||||
component servicing's `RebootPending`. `PendingFileRenameOperations`,
|
||||
`UpdateExeVolatile` and a pending computer rename only make up the reason.
|
||||
* **Automatic updates.** Policy first: `NoAutoUpdate=1` off, `AUOptions` 4 on, 2, 3
|
||||
and 7 off, 5 the local setting. Without a policy a client is on and a server follows
|
||||
its local `AUOptions`; a server with neither reads as unknown. The last success is the
|
||||
latest successful installation Windows Update recorded (its history, the AutoUpdate
|
||||
result, the older registry result); the interval is 31 days, the cadence of the
|
||||
monthly cumulative update.
|
||||
|
||||
### Host events
|
||||
|
||||
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: Windows Update, health metrics, Hyper-V.
|
||||
See netork#300 for the plan.
|
||||
|
||||
## Preparing a host
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
"""One reading script's JSON object, which the host readings of this driver share."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
|
||||
def json_object(out: str, what: str) -> dict[str, Any]:
|
||||
"""*out*, a script's ``ConvertTo-Json`` of one object, parsed.
|
||||
|
||||
:raises ValueError: when it is empty or no object, naming *what* was read.
|
||||
"""
|
||||
out = out.strip()
|
||||
raw = json.loads(out) if out else None
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError(f"the {what} reading came back empty")
|
||||
return raw
|
||||
@@ -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}
|
||||
@@ -0,0 +1,28 @@
|
||||
"""What every host reports about itself, gathered for the driver (NetOrk/netork#2888-#2891).
|
||||
|
||||
One mixin made of one module per reading, so the driver names a single base:
|
||||
|
||||
* :mod:`napalm_windows.system_identity` -- ``get_system_identity``
|
||||
* :mod:`napalm_windows.processes` -- ``get_processes``
|
||||
* :mod:`napalm_windows.os_users` -- ``get_os_users``
|
||||
* :mod:`napalm_windows.packages` -- ``get_packages``
|
||||
* :mod:`napalm_windows.host_status` -- ``get_host_status``
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from napalm_windows.host_status import WindowsHostStatusMixin
|
||||
from napalm_windows.os_users import WindowsOsUsersMixin
|
||||
from napalm_windows.packages import WindowsPackagesMixin
|
||||
from napalm_windows.processes import WindowsProcessesMixin
|
||||
from napalm_windows.system_identity import WindowsSystemIdentityMixin
|
||||
|
||||
|
||||
class WindowsHostBasicsMixin(
|
||||
WindowsSystemIdentityMixin,
|
||||
WindowsProcessesMixin,
|
||||
WindowsOsUsersMixin,
|
||||
WindowsPackagesMixin,
|
||||
WindowsHostStatusMixin,
|
||||
):
|
||||
"""The readings napalm-linux has as a matter of course; each module documents its own."""
|
||||
@@ -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)
|
||||
@@ -0,0 +1,230 @@
|
||||
"""Whether a Windows host needs a restart, and whether it updates itself (NetOrk/netork#2891).
|
||||
|
||||
:class:`WindowsHostStatusMixin` gives the driver napalm-device-types' ``get_host_status``
|
||||
(``HostStatusDict``) in one script. Each part is read on its own -- a COM object that
|
||||
does not answer over WinRM leaves the rest standing -- and nothing searches for updates:
|
||||
that is the update reading's, and too slow for a poll.
|
||||
|
||||
**Restart required** is what Windows says about its own updates:
|
||||
|
||||
* Windows Update's ``Microsoft.Update.SystemInfo.RebootRequired``, and its registry
|
||||
marker ``WindowsUpdate\\Auto Update\\RebootRequired`` where the COM object did not
|
||||
answer;
|
||||
* component-based servicing's ``RebootPending`` (features, roles, servicing stack).
|
||||
|
||||
Other markers only explain: ``PendingFileRenameOperations``, which antivirus and
|
||||
installers set routinely and which would keep the flag up for days, ``UpdateExeVolatile``
|
||||
and a new computer name taking effect at the next restart. They make up
|
||||
``reboot_reason`` with the two above, and a host with only them needs no restart.
|
||||
|
||||
**Automatic updates** follow the policy (``HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\
|
||||
WindowsUpdate\\AU``): ``NoAutoUpdate=1`` is off; ``AUOptions`` 4 installs on its own,
|
||||
2, 3 and 7 only notify or download; 5 leaves it to the local setting. Without a policy
|
||||
Windows 10 and 11 install on their own, and ignore the local ``AUOptions`` an upgrade may
|
||||
have left; a Windows Server follows its local setting (``sconfig``), and without one the
|
||||
answer is None: what each Server release does then is not established.
|
||||
|
||||
**When they last succeeded** is the latest successful installation Windows Update knows
|
||||
of, whoever started it: its history's last 50 entries, the ``Microsoft.Update.AutoUpdate``
|
||||
result and the older registry result (``Auto Update\\Results\\Install``), whichever is
|
||||
latest. Windows has something to install every month -- the cumulative update -- so
|
||||
automatic updates are meant to have installed something within 31 days
|
||||
(``auto_updates_interval``); on Linux that is the timer's day.
|
||||
|
||||
**Filesystems** are the system drive's size and free space, where updates unpack.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import calendar
|
||||
import time
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types.models import FilesystemUsageDict, HostStatusDict
|
||||
|
||||
from napalm_windows._powershell import _as_list
|
||||
from napalm_windows._reading import json_object
|
||||
|
||||
_AU_POLICY = r"HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU"
|
||||
_AU_LOCAL = r"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update"
|
||||
_CBS = r"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing"
|
||||
_SESSION_MANAGER = r"HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager"
|
||||
_COMPUTER_NAME = r"HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName"
|
||||
|
||||
# WUA's dates are UTC with no kind; IUpdateHistoryEntry.Operation 1 is an installation,
|
||||
# ResultCode 2 succeeded and 3 succeeded with errors.
|
||||
_PS_HOST_STATUS = rf"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
function V($path, $name) {{
|
||||
$item = Get-ItemProperty -LiteralPath $path -Name $name -ErrorAction SilentlyContinue
|
||||
if ($item) {{ $item.$name }}
|
||||
}}
|
||||
function Utc($t) {{
|
||||
if ($t) {{ ([DateTimeOffset][DateTime]::SpecifyKind($t, 'Utc')).ToUnixTimeSeconds() }}
|
||||
}}
|
||||
$wu = $null
|
||||
try {{ $wu = [bool](New-Object -ComObject Microsoft.Update.SystemInfo).RebootRequired }} catch {{ }}
|
||||
$installs = $null
|
||||
try {{
|
||||
$searcher = (New-Object -ComObject Microsoft.Update.Session).CreateUpdateSearcher()
|
||||
$count = $searcher.GetTotalHistoryCount()
|
||||
$installs = @(if ($count -gt 0) {{
|
||||
$searcher.QueryHistory(0, [Math]::Min($count, 50)) | Where-Object {{
|
||||
$_.Operation -eq 1 -and ($_.ResultCode -eq 2 -or $_.ResultCode -eq 3)
|
||||
}} | ForEach-Object {{ Utc $_.Date }}
|
||||
}})
|
||||
}} catch {{ }}
|
||||
$au = $null
|
||||
try {{
|
||||
$results = (New-Object -ComObject Microsoft.Update.AutoUpdate).Results
|
||||
$au = Utc $results.LastInstallationSuccessDate
|
||||
}} catch {{ }}
|
||||
$drive = $null
|
||||
try {{
|
||||
$disk = Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DeviceID='$env:SystemDrive'"
|
||||
if ($disk) {{
|
||||
$drive = [pscustomobject]@{{
|
||||
drive = [string]$disk.DeviceID; size = [int64]$disk.Size; free = [int64]$disk.FreeSpace
|
||||
}}
|
||||
}}
|
||||
}} catch {{ }}
|
||||
ConvertTo-Json -Compress -Depth 3 -InputObject ([pscustomobject]@{{
|
||||
wu_reboot_required = $wu
|
||||
cbs_reboot_pending = Test-Path -LiteralPath '{_CBS}\RebootPending'
|
||||
wu_reboot_key = Test-Path -LiteralPath '{_AU_LOCAL}\RebootRequired'
|
||||
file_renames = [bool](V '{_SESSION_MANAGER}' 'PendingFileRenameOperations')
|
||||
update_exe = [string](V 'HKLM:\SOFTWARE\Microsoft\Updates' 'UpdateExeVolatile')
|
||||
computer_name = [string](V '{_COMPUTER_NAME}\ComputerName' 'ComputerName')
|
||||
active_name = [string](V '{_COMPUTER_NAME}\ActiveComputerName' 'ComputerName')
|
||||
no_auto_update = [string](V '{_AU_POLICY}' 'NoAutoUpdate')
|
||||
au_options = [string](V '{_AU_POLICY}' 'AUOptions')
|
||||
local_au_options = [string](V '{_AU_LOCAL}' 'AUOptions')
|
||||
product_type = [int](Get-CimInstance -ClassName Win32_OperatingSystem).ProductType
|
||||
installs = $installs
|
||||
au_last_install = $au
|
||||
legacy_last_install = [string](V '{_AU_LOCAL}\Results\Install' 'LastSuccessTime')
|
||||
system_drive = $drive
|
||||
}})
|
||||
"""
|
||||
|
||||
#: ``AUOptions``: 2 notify, 3 download and notify, 4 install on a schedule, 7 (Server)
|
||||
#: download, notify to install and to restart; 1 is the older "never check".
|
||||
_AU_OPTIONS = {"1": False, "2": False, "3": False, "4": True, "7": False}
|
||||
#: ``Win32_OperatingSystem.ProductType`` of a client; 2 and 3 are servers.
|
||||
_WORKSTATION = 1
|
||||
#: How often a Windows host has something to install: the monthly cumulative update.
|
||||
MONTHLY = 31 * 86400
|
||||
|
||||
|
||||
def _marker(raw: dict[str, Any], key: str) -> bool:
|
||||
return raw.get(key) is True
|
||||
|
||||
|
||||
#: The markers that explain a restart, in the order they are named, each with its words.
|
||||
_REASONS = (
|
||||
(
|
||||
("wu_reboot_required", "wu_reboot_key"),
|
||||
"Windows Update needs a restart to finish installing updates",
|
||||
),
|
||||
(("cbs_reboot_pending",), "component-based servicing has a restart pending"),
|
||||
(
|
||||
("file_renames",),
|
||||
"files wait to be replaced at the next restart (PendingFileRenameOperations)",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _rename(raw: dict[str, Any]) -> str | None:
|
||||
"""The new computer name a restart takes effect with, if there is one."""
|
||||
new, active = str(raw.get("computer_name") or ""), str(raw.get("active_name") or "")
|
||||
if new and active and new.lower() != active.lower():
|
||||
return f"the computer takes its new name {new} at the next restart"
|
||||
return None
|
||||
|
||||
|
||||
def _restart_reasons(raw: dict[str, Any]) -> list[str]:
|
||||
reasons = [text for keys, text in _REASONS if any(_marker(raw, key) for key in keys)]
|
||||
if str(raw.get("update_exe") or "0") != "0":
|
||||
reasons.append("an update waits for a restart (UpdateExeVolatile)")
|
||||
rename = _rename(raw)
|
||||
return [*reasons, rename] if rename else reasons
|
||||
|
||||
|
||||
def _restart_required(raw: dict[str, Any]) -> bool:
|
||||
"""Windows Update or component servicing waits for a restart; see the module."""
|
||||
return any(
|
||||
_marker(raw, key) for key in ("wu_reboot_required", "wu_reboot_key", "cbs_reboot_pending")
|
||||
)
|
||||
|
||||
|
||||
def _auto_updates(raw: dict[str, Any]) -> bool | None:
|
||||
"""Whether the host installs updates on its own; see the module."""
|
||||
if str(raw.get("no_auto_update") or "") == "1":
|
||||
return False
|
||||
policy = _AU_OPTIONS.get(str(raw.get("au_options") or ""))
|
||||
if policy is not None:
|
||||
return policy
|
||||
if int(raw.get("product_type") or 0) == _WORKSTATION:
|
||||
return True
|
||||
return _AU_OPTIONS.get(str(raw.get("local_au_options") or ""))
|
||||
|
||||
|
||||
def _registry_time(value: Any) -> int | None:
|
||||
"""``Results\\Install``'s ``LastSuccessTime``, ``YYYY-MM-DD HH:MM:SS`` in UTC."""
|
||||
try:
|
||||
return calendar.timegm(time.strptime(str(value or ""), "%Y-%m-%d %H:%M:%S"))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _last_success(raw: dict[str, Any]) -> int | None:
|
||||
"""The latest successful installation any of the three sources knows of."""
|
||||
known = [*_as_list(raw.get("installs")), raw.get("au_last_install")]
|
||||
known.append(_registry_time(raw.get("legacy_last_install")))
|
||||
times = [int(t) for t in known if isinstance(t, int | float) and t > 0]
|
||||
return max(times, default=None)
|
||||
|
||||
|
||||
def _filesystems(raw: dict[str, Any]) -> list[FilesystemUsageDict] | None:
|
||||
drive = raw.get("system_drive")
|
||||
if not isinstance(drive, dict):
|
||||
return None
|
||||
total, free = int(drive.get("size") or 0), int(drive.get("free") or 0)
|
||||
return [
|
||||
{
|
||||
"mountpoint": f"{drive.get('drive') or ''}\\",
|
||||
"total": total,
|
||||
"used": total - free,
|
||||
"available": free,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def parse_host_status(raw: dict[str, Any]) -> HostStatusDict:
|
||||
"""``_PS_HOST_STATUS``'s JSON as the host status; see the module."""
|
||||
reasons = _restart_reasons(raw)
|
||||
auto = _auto_updates(raw)
|
||||
return {
|
||||
"reboot_required": _restart_required(raw),
|
||||
"reboot_reason": "; ".join(reasons) or None,
|
||||
"auto_updates": auto,
|
||||
"auto_updates_last_success": _last_success(raw),
|
||||
"auto_updates_interval": MONTHLY if auto else None,
|
||||
"filesystems": _filesystems(raw),
|
||||
}
|
||||
|
||||
|
||||
class WindowsHostStatusMixin:
|
||||
"""``get_host_status`` from Windows Update and the registry; the driver carries the
|
||||
script."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_raw(self, script: str) -> str: ...
|
||||
|
||||
def get_host_status(self) -> HostStatusDict:
|
||||
"""Whether the host needs a restart and installs updates on its own; see the module.
|
||||
|
||||
:raises ValueError: when the reading came back empty.
|
||||
"""
|
||||
return parse_host_status(json_object(self._run_raw(_PS_HOST_STATUS), "host status"))
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Local accounts on Windows as napalm-device-types' ``UserDict`` (NetOrk/netork#2889).
|
||||
|
||||
:class:`WindowsOsUsersMixin` gives the driver ``get_os_users``. One script reads the
|
||||
accounts (``Get-LocalUser``), the local groups with their members
|
||||
(``Get-LocalGroupMember``) and the profiles' paths (``Win32_UserProfile``).
|
||||
|
||||
Windows names an account by its security identifier, not a number:
|
||||
|
||||
* ``uid`` is the relative identifier, the SID's last part: 500 for the built-in
|
||||
Administrator, 501 Guest, 1000 and up for accounts created. ``sid`` is the whole SID.
|
||||
* ``gid`` is 513, the primary group every local account has ("None"); Windows offers
|
||||
no other for them.
|
||||
* ``home`` is the profile's folder, empty for an account that never logged on and so
|
||||
has none; ``shell`` is empty.
|
||||
* ``groups`` are the local groups the account is a direct member of. A group whose
|
||||
members cannot be read -- ``Get-LocalGroupMember`` fails on a member SID it cannot
|
||||
resolve, and the ADSI fallback failed too -- names nobody.
|
||||
|
||||
These are the host's own accounts. Who may log in and how (administrators, RDP rights,
|
||||
domain accounts) is the login accounts' contract, not this one. A domain controller
|
||||
has no local accounts -- ``Get-LocalUser`` would list the domain's -- and a host without
|
||||
the LocalAccounts module cannot list them; both raise ``NotImplementedError``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types.models import UserDict
|
||||
|
||||
from napalm_windows._powershell import _as_list
|
||||
from napalm_windows._reading import json_object
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_PS_OS_USERS = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$role = [int](Get-CimInstance -ClassName Win32_ComputerSystem).DomainRole
|
||||
$local = [bool](Get-Command -Name Get-LocalUser -ErrorAction SilentlyContinue)
|
||||
$users = @()
|
||||
$groups = @()
|
||||
if ($role -lt 4 -and $local) {
|
||||
$homes = @{}
|
||||
Get-CimInstance -ClassName Win32_UserProfile | ForEach-Object {
|
||||
$homes[[string]$_.SID] = [string]$_.LocalPath
|
||||
}
|
||||
$users = @(Get-LocalUser | ForEach-Object {
|
||||
$sid = [string]$_.SID
|
||||
[pscustomobject]@{ name = [string]$_.Name; sid = $sid; home = $homes[$sid] }
|
||||
})
|
||||
$groups = @(Get-LocalGroup | ForEach-Object {
|
||||
$group = $_
|
||||
$members = $null
|
||||
try {
|
||||
$members = @(Get-LocalGroupMember -SID $group.SID | ForEach-Object { [string]$_.SID })
|
||||
} catch {
|
||||
try {
|
||||
$adsi = [ADSI]"WinNT://$env:COMPUTERNAME/$($group.Name),group"
|
||||
$members = @($adsi.psbase.Invoke('Members') | ForEach-Object {
|
||||
$bytes = $_.GetType().InvokeMember('objectSid', 'GetProperty', $null, $_, $null)
|
||||
(New-Object System.Security.Principal.SecurityIdentifier($bytes, 0)).Value
|
||||
})
|
||||
} catch { $members = $null }
|
||||
}
|
||||
[pscustomobject]@{ name = [string]$group.Name; members = $members }
|
||||
})
|
||||
}
|
||||
ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
|
||||
domain_role = $role
|
||||
local_accounts = $local
|
||||
users = $users
|
||||
groups = $groups
|
||||
})
|
||||
"""
|
||||
|
||||
#: ``Win32_ComputerSystem.DomainRole`` of a backup and of a primary domain controller.
|
||||
_DOMAIN_CONTROLLER = 4
|
||||
#: DOMAIN_GROUP_RID_USERS: the primary group of every local account.
|
||||
_PRIMARY_GROUP = 513
|
||||
|
||||
|
||||
def _rid(sid: str) -> int:
|
||||
tail = sid.rsplit("-", 1)[-1]
|
||||
return int(tail) if tail.isdigit() else 0
|
||||
|
||||
|
||||
def _memberships(groups: list[Any]) -> dict[str, list[str]]:
|
||||
"""SID -> the names of the groups it is a direct member of, in the order read."""
|
||||
member_of: dict[str, list[str]] = {}
|
||||
for group in groups:
|
||||
members = group.get("members")
|
||||
if members is None:
|
||||
logger.warning("the members of local group %r could not be read", group.get("name"))
|
||||
continue
|
||||
for sid in _as_list(members):
|
||||
member_of.setdefault(str(sid), []).append(str(group["name"]))
|
||||
return member_of
|
||||
|
||||
|
||||
def parse_os_users(raw: dict[str, Any]) -> list[UserDict]:
|
||||
"""``_PS_OS_USERS``'s JSON as ``UserDict``s; see the module.
|
||||
|
||||
:raises NotImplementedError: on a domain controller, or without ``Get-LocalUser``.
|
||||
"""
|
||||
if int(raw.get("domain_role") or 0) >= _DOMAIN_CONTROLLER:
|
||||
raise NotImplementedError(
|
||||
"a domain controller has no local accounts; its accounts are the domain's"
|
||||
)
|
||||
if not raw.get("local_accounts"):
|
||||
raise NotImplementedError("Get-LocalUser is not available on this host")
|
||||
member_of = _memberships(_as_list(raw.get("groups")))
|
||||
users: list[UserDict] = []
|
||||
for user in _as_list(raw.get("users")):
|
||||
sid = str(user.get("sid") or "")
|
||||
users.append(
|
||||
{
|
||||
"username": str(user["name"]),
|
||||
"uid": _rid(sid),
|
||||
"gid": _PRIMARY_GROUP,
|
||||
"home": str(user.get("home") or ""),
|
||||
"shell": "",
|
||||
"groups": member_of.get(sid, []),
|
||||
"sid": sid,
|
||||
}
|
||||
)
|
||||
return users
|
||||
|
||||
|
||||
class WindowsOsUsersMixin:
|
||||
"""``get_os_users`` from the LocalAccounts cmdlets; the driver carries the script."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_raw(self, script: str) -> str: ...
|
||||
|
||||
def get_os_users(self) -> list[UserDict]:
|
||||
"""The host's local accounts; see the module.
|
||||
|
||||
:raises NotImplementedError: on a domain controller, or without ``Get-LocalUser``.
|
||||
:raises ValueError: when the reading came back empty.
|
||||
"""
|
||||
return parse_os_users(json_object(self._run_raw(_PS_OS_USERS), "local account"))
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Installed software on Windows as packages (NetOrk/netork#2890).
|
||||
|
||||
:class:`WindowsPackagesMixin` gives the driver napalm-device-types' ``get_packages``
|
||||
(``PackageDict``) from the machine-wide Uninstall keys, the list "Apps & features" and
|
||||
``winget list`` read too:
|
||||
|
||||
* ``HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall``: the host's native
|
||||
programs (``x64``, ``arm64`` on ARM, ``x86`` on a 32-bit Windows);
|
||||
* ``HKLM\\SOFTWARE\\WOW6432Node\\...\\Uninstall``: the 32-bit programs of a 64-bit
|
||||
Windows (``x86``).
|
||||
|
||||
A 32-bit and a 64-bit install of one program stay two packages, told apart by
|
||||
``architecture``. Left out: keys without a ``DisplayName``, ``SystemComponent=1``
|
||||
(parts Windows or a suite hides from the list) and entries with a ``ParentKeyName``
|
||||
(updates listed under their product; Windows' own updates are the update history's).
|
||||
``source`` is ``msi`` for a Windows Installer package (``WindowsInstaller=1``), else
|
||||
``exe``; ``size`` is ``EstimatedSize`` (KiB) in bytes, 0 where none is given;
|
||||
``publisher`` is the vendor the program names.
|
||||
|
||||
Not read: per-user installs (a user's own ``HKU`` hive -- over WinRM ``HKCU`` is the
|
||||
connecting account's, and the hives of whoever is logged on would make the list change
|
||||
with them), Store and MSIX apps, and winget, which is a per-user App Execution Alias
|
||||
that does not work reliably in a WinRM session. Nothing is installed or removed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types.models import PackageDict
|
||||
|
||||
from napalm_windows._powershell import _as_list
|
||||
|
||||
_UNINSTALL = r"Microsoft\Windows\CurrentVersion\Uninstall"
|
||||
|
||||
_PS_PACKAGES = rf"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$native = switch ($env:PROCESSOR_ARCHITECTURE) {{
|
||||
'ARM64' {{ 'arm64' }}
|
||||
'x86' {{ 'x86' }}
|
||||
default {{ 'x64' }}
|
||||
}}
|
||||
$keys = @(
|
||||
[pscustomobject]@{{ path = 'HKLM:\SOFTWARE\{_UNINSTALL}'; arch = $native }},
|
||||
[pscustomobject]@{{ path = 'HKLM:\SOFTWARE\WOW6432Node\{_UNINSTALL}'; arch = 'x86' }}
|
||||
)
|
||||
ConvertTo-Json -Compress -Depth 3 -InputObject @(
|
||||
foreach ($key in $keys) {{
|
||||
if (Test-Path -LiteralPath $key.path) {{
|
||||
Get-ChildItem -LiteralPath $key.path -ErrorAction SilentlyContinue | ForEach-Object {{
|
||||
[pscustomobject]@{{
|
||||
key = [string]$_.PSChildName
|
||||
arch = $key.arch
|
||||
name = [string]$_.GetValue('DisplayName')
|
||||
version = [string]$_.GetValue('DisplayVersion')
|
||||
publisher = [string]$_.GetValue('Publisher')
|
||||
system = [string]$_.GetValue('SystemComponent')
|
||||
parent = [string]$_.GetValue('ParentKeyName')
|
||||
msi = [string]$_.GetValue('WindowsInstaller')
|
||||
size = [string]$_.GetValue('EstimatedSize')
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
)
|
||||
"""
|
||||
|
||||
|
||||
class WindowsPackageDict(PackageDict):
|
||||
"""A program from the Uninstall keys, with whose it is and which build."""
|
||||
|
||||
publisher: str
|
||||
architecture: str # x64, x86 or arm64
|
||||
|
||||
|
||||
def _size(value: Any) -> int:
|
||||
text = str(value or "").strip()
|
||||
return int(text) * 1024 if text.isdigit() else 0
|
||||
|
||||
|
||||
def _listed(entry: dict[str, Any]) -> bool:
|
||||
"""A program the host lists as installed: named, not hidden, not an update."""
|
||||
return bool(
|
||||
str(entry.get("name") or "").strip()
|
||||
and str(entry.get("system") or "") != "1"
|
||||
and not str(entry.get("parent") or "").strip()
|
||||
)
|
||||
|
||||
|
||||
def _package(entry: dict[str, Any]) -> WindowsPackageDict:
|
||||
return {
|
||||
"name": str(entry["name"]).strip(),
|
||||
"version": str(entry.get("version") or "").strip(),
|
||||
"installed": True,
|
||||
"description": "",
|
||||
"size": _size(entry.get("size")),
|
||||
"source": "msi" if str(entry.get("msi") or "") == "1" else "exe",
|
||||
"publisher": str(entry.get("publisher") or "").strip(),
|
||||
"architecture": str(entry.get("arch") or ""),
|
||||
}
|
||||
|
||||
|
||||
def parse_packages(raw: Any) -> list[PackageDict]:
|
||||
"""``_PS_PACKAGES``'s JSON as packages, by name; see the module."""
|
||||
packages = [_package(e) for e in _as_list(raw) if isinstance(e, dict) and _listed(e)]
|
||||
packages.sort(key=lambda p: (p["name"].lower(), p["architecture"]))
|
||||
return list(packages)
|
||||
|
||||
|
||||
class WindowsPackagesMixin:
|
||||
"""``get_packages`` from the Uninstall keys; 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_packages(self) -> list[PackageDict]:
|
||||
"""The programs installed for the whole machine; see the module."""
|
||||
return parse_packages(self._run_ps(_PS_PACKAGES))
|
||||
@@ -0,0 +1,159 @@
|
||||
"""Running processes on Windows, shaped like ``ps`` output (NetOrk/netork#2889).
|
||||
|
||||
:class:`WindowsProcessesMixin` gives the driver napalm-device-types' ``get_processes``
|
||||
(``ProcessDict``). One script reads two sources and the join happens here:
|
||||
|
||||
* ``Win32_Process``: PID, parent, command line, start (``CreationDate``), the CPU time
|
||||
(``KernelModeTime`` + ``UserModeTime``, in 100 ns), ``WorkingSetSize`` and
|
||||
``VirtualSize``. Read first: it is the list.
|
||||
* ``Get-Process -IncludeUserName``: the owner, one call for all processes instead of a
|
||||
``GetOwner()`` per process. It needs an elevated session, which netOrk's WinRM
|
||||
administrator has; without one the script falls back to ``Get-Process`` and the owner
|
||||
is unknown (empty).
|
||||
|
||||
A process is reported only when both saw it with the same start: one that exited between
|
||||
the two reads is dropped rather than half-filled, and a PID reused in between is another
|
||||
process. PID 0, the System Idle Process, is no process and is left out, as ``ps`` leaves
|
||||
it out.
|
||||
|
||||
The values follow ``ps``: ``cpu`` is the CPU time over the time since the start, per
|
||||
logical processor, so 0-100; ``memory`` the working set over the visible memory;
|
||||
``vsz`` and ``rss`` in KiB; ``started`` as ``lstart`` prints it, in the host's local
|
||||
time. Windows has no controlling terminal and no process state of that kind: ``tty``
|
||||
and ``state`` are empty. A process without a readable command line (``System``,
|
||||
protected processes) shows its image name. Command lines are reported as the host
|
||||
gives them, as ``ps`` does on Linux.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types.models import ProcessDict
|
||||
|
||||
from napalm_windows._powershell import _as_list
|
||||
from napalm_windows._reading import json_object
|
||||
|
||||
_PS_PROCESSES = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
function Unix($t) { if ($t) { ([DateTimeOffset]$t).ToUnixTimeSeconds() } else { $null } }
|
||||
function Offset($t) { if ($t) { [int]([DateTimeOffset]$t).Offset.TotalMinutes } else { 0 } }
|
||||
$os = Get-CimInstance -ClassName Win32_OperatingSystem
|
||||
$cs = Get-CimInstance -ClassName Win32_ComputerSystem
|
||||
$processes = @(Get-CimInstance -ClassName Win32_Process | ForEach-Object {
|
||||
[pscustomobject]@{
|
||||
pid = [int]$_.ProcessId
|
||||
ppid = [int]$_.ParentProcessId
|
||||
name = [string]$_.Name
|
||||
command = [string]$_.CommandLine
|
||||
started = Unix $_.CreationDate
|
||||
offset = Offset $_.CreationDate
|
||||
cpu = [int64]$_.KernelModeTime + [int64]$_.UserModeTime
|
||||
ws = [int64]$_.WorkingSetSize
|
||||
vsz = [int64]$_.VirtualSize
|
||||
}
|
||||
})
|
||||
try { $running = @(Get-Process -IncludeUserName) } catch { $running = @(Get-Process) }
|
||||
$owners = @($running | ForEach-Object {
|
||||
$start = $null
|
||||
try { $start = Unix $_.StartTime } catch { }
|
||||
[pscustomobject]@{ pid = [int]$_.Id; user = [string]$_.UserName; started = $start }
|
||||
})
|
||||
ConvertTo-Json -Compress -Depth 3 -InputObject ([pscustomobject]@{
|
||||
now = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
|
||||
cores = [int]$cs.NumberOfLogicalProcessors
|
||||
memory_kib = [int64]$os.TotalVisibleMemorySize
|
||||
processes = $processes
|
||||
owners = $owners
|
||||
})
|
||||
"""
|
||||
|
||||
#: How far the two sources' starts of one process may differ: they round differently.
|
||||
_SAME_START = 2
|
||||
_DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
|
||||
_MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
|
||||
|
||||
|
||||
def _lstart(started: int | None, offset_minutes: int) -> str:
|
||||
"""Unix time in the host's local time, as ``ps -o lstart`` prints it in the C locale."""
|
||||
if started is None:
|
||||
return ""
|
||||
t = datetime.fromtimestamp(started, UTC) + timedelta(minutes=offset_minutes)
|
||||
return f"{_DAYS[t.weekday()]} {_MONTHS[t.month - 1]} {t.day:2d} {t:%H:%M:%S} {t.year}"
|
||||
|
||||
|
||||
class _Host:
|
||||
"""What the reading says about the host as a whole."""
|
||||
|
||||
def __init__(self, raw: dict[str, Any]) -> None:
|
||||
self.now = int(raw.get("now") or 0)
|
||||
self.cores = max(int(raw.get("cores") or 1), 1)
|
||||
self.memory_kib = int(raw.get("memory_kib") or 0)
|
||||
|
||||
def cpu(self, cpu_100ns: int, started: int | None) -> float:
|
||||
if started is None:
|
||||
return 0.0
|
||||
elapsed = max(self.now - started, 1)
|
||||
return round(min(cpu_100ns / 10_000_000 / elapsed / self.cores * 100, 100.0), 1)
|
||||
|
||||
def memory(self, rss_kib: int) -> float:
|
||||
return round(rss_kib * 100 / self.memory_kib, 1) if self.memory_kib else 0.0
|
||||
|
||||
|
||||
def _started(entry: dict[str, Any]) -> int | None:
|
||||
value = entry.get("started")
|
||||
return int(value) if value is not None else None
|
||||
|
||||
|
||||
def _same_process(entry: dict[str, Any], owner: dict[str, Any]) -> bool:
|
||||
"""False when ``Get-Process`` saw another start under this PID: it was reused."""
|
||||
ours, theirs = _started(entry), _started(owner)
|
||||
return ours is None or theirs is None or abs(ours - theirs) <= _SAME_START
|
||||
|
||||
|
||||
def _process(entry: dict[str, Any], owner: dict[str, Any], host: _Host) -> ProcessDict:
|
||||
started = _started(entry)
|
||||
rss = int(entry.get("ws") or 0) // 1024
|
||||
return {
|
||||
"pid": int(entry["pid"]),
|
||||
"ppid": int(entry.get("ppid") or 0),
|
||||
"user": str(owner.get("user") or ""),
|
||||
"cpu": host.cpu(int(entry.get("cpu") or 0), started),
|
||||
"memory": host.memory(rss),
|
||||
"vsz": int(entry.get("vsz") or 0) // 1024,
|
||||
"rss": rss,
|
||||
"tty": "",
|
||||
"state": "",
|
||||
"started": _lstart(started, int(entry.get("offset") or 0)),
|
||||
"command": str(entry.get("command") or entry.get("name") or ""),
|
||||
}
|
||||
|
||||
|
||||
def parse_processes(raw: dict[str, Any]) -> list[ProcessDict]:
|
||||
"""``_PS_PROCESSES``'s JSON as ``ProcessDict``s by PID; see the module for the join."""
|
||||
host = _Host(raw)
|
||||
owners = {int(o["pid"]): o for o in _as_list(raw.get("owners"))}
|
||||
processes = []
|
||||
for entry in _as_list(raw.get("processes")):
|
||||
owner = owners.get(int(entry["pid"]))
|
||||
if not entry["pid"] or owner is None or not _same_process(entry, owner):
|
||||
continue
|
||||
processes.append(_process(entry, owner, host))
|
||||
return sorted(processes, key=lambda p: p["pid"])
|
||||
|
||||
|
||||
class WindowsProcessesMixin:
|
||||
"""``get_processes`` from ``Win32_Process`` and ``Get-Process``; the driver carries
|
||||
the script."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_raw(self, script: str) -> str: ...
|
||||
|
||||
def get_processes(self) -> list[ProcessDict]:
|
||||
"""A snapshot of the running processes, shaped like ``ps``; see the module.
|
||||
|
||||
:raises ValueError: when the reading came back empty.
|
||||
"""
|
||||
return parse_processes(json_object(self._run_raw(_PS_PROCESSES), "process"))
|
||||
@@ -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))]
|
||||
@@ -0,0 +1,85 @@
|
||||
"""The SMBIOS identity of a Windows host: what ties it to its BMC (NetOrk/netork#2888).
|
||||
|
||||
:class:`WindowsSystemIdentityMixin` gives the driver ``get_system_identity`` with the
|
||||
shape and the placeholder rules of napalm-device-types' ``SystemIdentityMixin``, which
|
||||
reads Linux' DMI files. Windows reads the same SMBIOS tables through its CIM classes,
|
||||
in one script of its own -- not folded into ``get_facts``, so a class only the identity
|
||||
needs cannot fail the facts:
|
||||
|
||||
* ``Win32_ComputerSystemProduct``: ``UUID`` (the system UUID, which Windows decodes from
|
||||
SMBIOS 2.6+ the way dmidecode does) and ``IdentifyingNumber`` (the product serial);
|
||||
* ``Win32_BaseBoard``: ``SerialNumber``, of the first board;
|
||||
* ``Win32_BIOS``: ``Manufacturer``, ``SMBIOSBIOSVersion`` and ``ReleaseDate``. CIM gives
|
||||
the date as midnight UTC; it travels as Unix time and is read as that UTC day.
|
||||
|
||||
Vendor placeholders ("To be filled by O.E.M.", all-F UUIDs) read as empty
|
||||
(``clean_system_identity``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types import clean_system_identity
|
||||
from napalm_device_types.system_identity import SystemIdentityDict
|
||||
|
||||
from napalm_windows._reading import json_object
|
||||
|
||||
_PS_SYSTEM_IDENTITY = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$product = Get-CimInstance -ClassName Win32_ComputerSystemProduct
|
||||
$board = @(Get-CimInstance -ClassName Win32_BaseBoard) | Select-Object -First 1
|
||||
$bios = Get-CimInstance -ClassName Win32_BIOS
|
||||
[pscustomobject]@{
|
||||
uuid = [string]$product.UUID
|
||||
product_serial = [string]$product.IdentifyingNumber
|
||||
board_serial = if ($board) { [string]$board.SerialNumber } else { $null }
|
||||
bios_vendor = [string]$bios.Manufacturer
|
||||
bios_version = [string]$bios.SMBIOSBIOSVersion
|
||||
bios_date = if ($bios.ReleaseDate) {
|
||||
([DateTimeOffset]$bios.ReleaseDate).ToUnixTimeSeconds()
|
||||
} else { $null }
|
||||
} | ConvertTo-Json -Compress
|
||||
"""
|
||||
|
||||
|
||||
def _text(raw: dict[str, Any], key: str) -> str:
|
||||
return str(raw.get(key) or "")
|
||||
|
||||
|
||||
def _utc_day(value: Any) -> str:
|
||||
"""Unix time as its UTC day, ``YYYY-MM-DD``; empty for none."""
|
||||
if not isinstance(value, int | float) or isinstance(value, bool):
|
||||
return ""
|
||||
return datetime.fromtimestamp(value, UTC).date().isoformat()
|
||||
|
||||
|
||||
def parse_system_identity(raw: dict[str, Any]) -> SystemIdentityDict:
|
||||
"""``_PS_SYSTEM_IDENTITY``'s JSON as napalm-device-types' identity, placeholders empty."""
|
||||
return clean_system_identity(
|
||||
system_uuid=_text(raw, "uuid"),
|
||||
product_serial=_text(raw, "product_serial"),
|
||||
board_serial=_text(raw, "board_serial"),
|
||||
bios_vendor=_text(raw, "bios_vendor"),
|
||||
bios_version=_text(raw, "bios_version"),
|
||||
bios_date=_utc_day(raw.get("bios_date")),
|
||||
)
|
||||
|
||||
|
||||
class WindowsSystemIdentityMixin:
|
||||
"""``get_system_identity`` from the CIM classes; the driver carries the script."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_raw(self, script: str) -> str: ...
|
||||
|
||||
def get_system_identity(self) -> SystemIdentityDict:
|
||||
"""The host's SMBIOS identity and system firmware, each value empty when unknown
|
||||
or a vendor placeholder; see the module.
|
||||
|
||||
:raises ValueError: when the reading came back empty.
|
||||
"""
|
||||
return parse_system_identity(
|
||||
json_object(self._run_raw(_PS_SYSTEM_IDENTITY), "system identity")
|
||||
)
|
||||
+32
-10
@@ -24,13 +24,11 @@ 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.host_basics import WindowsHostBasicsMixin
|
||||
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
|
||||
|
||||
@@ -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"}
|
||||
|
||||
|
||||
@@ -250,12 +263,7 @@ def _is_noise_route(destination: str) -> bool:
|
||||
|
||||
|
||||
class WindowsDriver(
|
||||
WindowsScheduledJobsMixin,
|
||||
WindowsTimeSyncMixin,
|
||||
WindowsServicesMixin,
|
||||
WindowsHostEventsMixin,
|
||||
WindowsLogSourcesMixin,
|
||||
OSDriver,
|
||||
WindowsHostBasicsMixin, WindowsScheduledJobsMixin, WindowsTimeSyncMixin, OSDriver
|
||||
):
|
||||
"""NAPALM driver for Windows Server 2016+ and Windows 10/11.
|
||||
|
||||
@@ -484,6 +492,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``,
|
||||
|
||||
-11
@@ -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
@@ -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
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"wu_reboot_required":false,"cbs_reboot_pending":false,"wu_reboot_key":false,"file_renames":true,"update_exe":"0","computer_name":"WIN01","active_name":"WIN01","no_auto_update":"","au_options":"4","local_au_options":"","product_type":3,"installs":[1763337600,1762732800,1760659200],"au_last_install":1762732800,"legacy_last_install":"","system_drive":{"drive":"C:","size":136363114496,"free":52613349376}}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"domain_role":2,"local_accounts":true,"users":[{"name":"Administrator","sid":"S-1-5-21-1004336348-1177238915-682003330-500","home":"C:\\Users\\Administrator"},{"name":"DefaultAccount","sid":"S-1-5-21-1004336348-1177238915-682003330-503","home":null},{"name":"Guest","sid":"S-1-5-21-1004336348-1177238915-682003330-501","home":null},{"name":"WDAGUtilityAccount","sid":"S-1-5-21-1004336348-1177238915-682003330-504","home":null},{"name":"svc-backup","sid":"S-1-5-21-1004336348-1177238915-682003330-1001","home":"C:\\Users\\svc-backup"}],"groups":[{"name":"Administrators","members":["S-1-5-21-1004336348-1177238915-682003330-500","S-1-5-21-1004336348-1177238915-682003330-1001","S-1-5-21-3623811015-3361044348-30300820-512"]},{"name":"Backup Operators","members":["S-1-5-21-1004336348-1177238915-682003330-1001"]},{"name":"Guests","members":["S-1-5-21-1004336348-1177238915-682003330-501"]},{"name":"Remote Desktop Users","members":[]},{"name":"System Managed Accounts Group","members":["S-1-5-21-1004336348-1177238915-682003330-503"]},{"name":"Users","members":["S-1-5-21-1004336348-1177238915-682003330-1001","S-1-5-4","S-1-5-11"]}]}
|
||||
+1
@@ -0,0 +1 @@
|
||||
[{"key":"7-Zip","arch":"x64","name":"7-Zip 23.01 (x64)","version":"23.01","publisher":"Igor Pavlov","system":"","parent":"","msi":"","size":"5846"},{"key":"7-Zip","arch":"x86","name":"7-Zip 23.01 (x64)","version":"23.01","publisher":"Igor Pavlov","system":"","parent":"","msi":"","size":"4870"},{"key":"{90160000-008C-0000-1000-0000000FF1CE}","arch":"x64","name":"Office 16 Click-to-Run Extensibility Component","version":"16.0.17126.20132","publisher":"Microsoft Corporation","system":"1","parent":"","msi":"1","size":"0"},{"key":"{AC76BA86-1033-FFFF-7760-BC15014EA700}","arch":"x86","name":"Adobe Acrobat Reader DC","version":"23.008.20470","publisher":"Adobe","system":"","parent":"","msi":"1","size":"1158000"},{"key":"KB5034441","arch":"x64","name":"Security Update for Windows Server (KB5034441)","version":"","publisher":"Microsoft Corporation","system":"","parent":"Windows Server","msi":"","size":""},{"key":"Git_is1","arch":"x64","name":"Git","version":"2.43.0","publisher":"The Git Development Community","system":"","parent":"","msi":"","size":"309000"},{"key":"AddressBook","arch":"x64","name":"","version":"","publisher":"","system":"","parent":"","msi":"","size":""},{"key":"{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}","arch":"x64","name":"Microsoft Visual C++ 2015-2022 Redistributable (x64) - 14.38.33130","version":"14.38.33130.0","publisher":"Microsoft Corporation","system":"","parent":"","msi":"","size":"20532"}]
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"now":1764590400,"cores":4,"memory_kib":8388608,"processes":[{"pid":0,"ppid":0,"name":"System Idle Process","command":"","started":null,"offset":0,"cpu":4000000000000,"ws":8192,"vsz":8192},{"pid":4,"ppid":0,"name":"System","command":"","started":null,"offset":0,"cpu":12000000000,"ws":143360,"vsz":3997696},{"pid":812,"ppid":640,"name":"svchost.exe","command":"C:\\Windows\\system32\\svchost.exe -k DcomLaunch -p","started":1764504000,"offset":60,"cpu":3456000000,"ws":31457280,"vsz":2203318222848},{"pid":4312,"ppid":3988,"name":"powershell.exe","command":"\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -NoLogo","started":1764589800,"offset":60,"cpu":1200000000,"ws":104857600,"vsz":2203500000000},{"pid":5120,"ppid":812,"name":"WmiPrvSE.exe","command":"C:\\Windows\\system32\\wbem\\wmiprvse.exe","started":1764590395,"offset":60,"cpu":1000000,"ws":10485760,"vsz":2203400000000},{"pid":6000,"ppid":812,"name":"conhost.exe","command":"\\??\\C:\\Windows\\system32\\conhost.exe 0x4","started":1764590370,"offset":60,"cpu":0,"ws":4194304,"vsz":2203300000000}],"owners":[{"pid":0,"user":null,"started":null},{"pid":4,"user":"NT AUTHORITY\\SYSTEM","started":null},{"pid":812,"user":"NT AUTHORITY\\SYSTEM","started":1764504000},{"pid":4312,"user":"WIN01\\admin","started":1764589800},{"pid":6000,"user":"WIN01\\admin","started":1764590398},{"pid":7777,"user":"WIN01\\admin","started":1764590399}]}
|
||||
+5
-9
@@ -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}
|
||||
]
|
||||
@@ -0,0 +1 @@
|
||||
{"uuid":"4C4C4544-0042-3510-8051-B4C04F4D3732","product_serial":"4B5QM72","board_serial":".4B5QM72.CNCMS0012345AB.","bios_vendor":"Dell Inc.","bios_version":"2.19.0","bios_date":1692057600}
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -0,0 +1,211 @@
|
||||
"""Whether a Windows host needs a restart, and whether it updates itself (NetOrk/netork#2891).
|
||||
|
||||
One script reads Windows Update's own answer (``Microsoft.Update.SystemInfo``), the
|
||||
registry's restart markers, the Windows Update policy and history, and the system
|
||||
drive; a fake transport answers it from tests/fixtures/synthetic/host_status.json: a
|
||||
member server whose policy installs updates automatically, with file renames pending
|
||||
from an installer and nothing else.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from napalm_device_types.models import HostStatusDict
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import host_status as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "host_status.json"
|
||||
MONTH = 31 * 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 _status(**changes: Any) -> HostStatusDict:
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
reading = {**json.loads(FIXTURE.read_text()), **changes}
|
||||
d._transport = FakeTransport(json.dumps(reading))
|
||||
return d.get_host_status()
|
||||
|
||||
|
||||
def test_reads_the_host_status():
|
||||
assert _status() == {
|
||||
"reboot_required": False,
|
||||
"reboot_reason": "files wait to be replaced at the next restart "
|
||||
"(PendingFileRenameOperations)",
|
||||
"auto_updates": True,
|
||||
"auto_updates_last_success": 1763337600,
|
||||
"auto_updates_interval": MONTH,
|
||||
"filesystems": [
|
||||
{
|
||||
"mountpoint": "C:\\",
|
||||
"total": 136363114496,
|
||||
"used": 136363114496 - 52613349376,
|
||||
"available": 52613349376,
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
# ── restart ───────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_pending_file_renames_alone_need_no_restart():
|
||||
# Antivirus and installers set them routinely; as a trigger they would keep the flag up.
|
||||
status = _status()
|
||||
assert status["reboot_required"] is False
|
||||
assert "PendingFileRenameOperations" in (status["reboot_reason"] or "")
|
||||
|
||||
|
||||
def test_windows_update_saying_so_needs_a_restart():
|
||||
status = _status(wu_reboot_required=True, file_renames=False)
|
||||
assert status["reboot_required"] is True
|
||||
assert status["reboot_reason"] == "Windows Update needs a restart to finish installing updates"
|
||||
|
||||
|
||||
def test_component_servicing_pending_needs_a_restart():
|
||||
status = _status(cbs_reboot_pending=True, file_renames=False)
|
||||
assert status["reboot_required"] is True
|
||||
assert status["reboot_reason"] == "component-based servicing has a restart pending"
|
||||
|
||||
|
||||
def test_windows_updates_registry_marker_stands_in_where_its_com_object_did_not_answer():
|
||||
status = _status(wu_reboot_required=None, wu_reboot_key=True, file_renames=False)
|
||||
assert status["reboot_required"] is True
|
||||
|
||||
|
||||
def test_nothing_pending_needs_no_restart_and_gives_no_reason():
|
||||
status = _status(file_renames=False)
|
||||
assert status["reboot_required"] is False
|
||||
assert status["reboot_reason"] is None
|
||||
|
||||
|
||||
def test_every_marker_found_is_named():
|
||||
status = _status(
|
||||
wu_reboot_required=True,
|
||||
cbs_reboot_pending=True,
|
||||
update_exe="1",
|
||||
computer_name="WIN02",
|
||||
)
|
||||
assert status["reboot_reason"] == "; ".join(
|
||||
[
|
||||
"Windows Update needs a restart to finish installing updates",
|
||||
"component-based servicing has a restart pending",
|
||||
"files wait to be replaced at the next restart (PendingFileRenameOperations)",
|
||||
"an update waits for a restart (UpdateExeVolatile)",
|
||||
"the computer takes its new name WIN02 at the next restart",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def test_a_rename_alone_needs_no_restart_for_updates():
|
||||
status = _status(file_renames=False, computer_name="WIN02")
|
||||
assert status["reboot_required"] is False
|
||||
assert status["reboot_reason"] == "the computer takes its new name WIN02 at the next restart"
|
||||
|
||||
|
||||
# ── automatic updates ─────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("au_options", "expected"),
|
||||
[("2", False), ("3", False), ("4", True), ("7", False)],
|
||||
ids=["notify", "download-only", "install", "server-notify-install-and-restart"],
|
||||
)
|
||||
def test_the_policys_au_options(au_options, expected):
|
||||
assert _status(au_options=au_options)["auto_updates"] is expected
|
||||
|
||||
|
||||
def test_a_policy_that_turns_automatic_updates_off():
|
||||
assert _status(no_auto_update="1")["auto_updates"] is False
|
||||
|
||||
|
||||
def test_a_policy_that_leaves_it_to_the_local_administrator():
|
||||
assert _status(au_options="5", local_au_options="4")["auto_updates"] is True
|
||||
assert _status(au_options="5", local_au_options="3")["auto_updates"] is False
|
||||
|
||||
|
||||
def test_a_client_without_a_policy_installs_updates_itself():
|
||||
assert _status(au_options="", product_type=1)["auto_updates"] is True
|
||||
|
||||
|
||||
def test_a_client_ignores_a_leftover_local_setting():
|
||||
# Windows 10 and 11 honour only the policy; an old AUOptions left from an upgrade stays.
|
||||
assert _status(au_options="", local_au_options="2", product_type=1)["auto_updates"] is True
|
||||
|
||||
|
||||
def test_a_server_follows_its_local_setting_without_a_policy():
|
||||
assert _status(au_options="", local_au_options="4")["auto_updates"] is True
|
||||
assert _status(au_options="", local_au_options="3")["auto_updates"] is False
|
||||
|
||||
|
||||
def test_a_server_without_any_setting_cannot_tell():
|
||||
status = _status(au_options="", local_au_options="")
|
||||
assert status["auto_updates"] is None
|
||||
assert status["auto_updates_interval"] is None
|
||||
|
||||
|
||||
def test_without_automatic_updates_there_is_no_interval():
|
||||
status = _status(au_options="3")
|
||||
assert status["auto_updates_interval"] is None
|
||||
assert status["auto_updates_last_success"] == 1763337600
|
||||
|
||||
|
||||
def test_the_last_success_is_the_latest_any_source_knows():
|
||||
status = _status(installs=[], au_last_install=None, legacy_last_install="2025-11-20 03:12:44")
|
||||
assert status["auto_updates_last_success"] == 1763608364
|
||||
status = _status(installs=[1760659200], au_last_install=1762732800)
|
||||
assert status["auto_updates_last_success"] == 1762732800
|
||||
|
||||
|
||||
def test_no_installation_known_has_no_last_success():
|
||||
status = _status(installs=None, au_last_install=None, legacy_last_install="")
|
||||
assert status["auto_updates_last_success"] is None
|
||||
|
||||
|
||||
def test_an_unset_com_date_is_no_installation():
|
||||
# WUA's DATE zero is 1899-12-30, which travels as a negative Unix time.
|
||||
status = _status(installs=[], au_last_install=-2209161600, legacy_last_install="garbage")
|
||||
assert status["auto_updates_last_success"] is None
|
||||
|
||||
|
||||
# ── the system drive ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_an_unread_system_drive_is_no_filesystem_reading():
|
||||
assert _status(system_drive=None)["filesystems"] is None
|
||||
|
||||
|
||||
def test_one_script_reads_it_all_each_part_on_its_own():
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(FIXTURE.read_text())
|
||||
d.get_host_status()
|
||||
(script,) = d._transport.sent # type: ignore[union-attr]
|
||||
assert script == mod._PS_HOST_STATUS
|
||||
for part in (
|
||||
"Microsoft.Update.SystemInfo",
|
||||
r"Component Based Servicing\RebootPending",
|
||||
"PendingFileRenameOperations",
|
||||
r"Policies\Microsoft\Windows\WindowsUpdate\AU",
|
||||
"QueryHistory",
|
||||
"Win32_LogicalDisk",
|
||||
):
|
||||
assert part in script
|
||||
# Each COM object is asked inside its own try, so one that does not answer over
|
||||
# WinRM leaves the rest of the reading standing.
|
||||
assert script.count("try {") >= 4
|
||||
# No update search in the poll: that is the update reading's, and slow.
|
||||
assert "Search(" not in script
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Local accounts on Windows as ``UserDict`` (NetOrk/netork#2889).
|
||||
|
||||
One script reads ``Get-LocalUser``, ``Get-LocalGroup`` with their members and the
|
||||
profiles' paths; a fake transport answers it from tests/fixtures/synthetic/os_users.json,
|
||||
a member server as Windows installs it plus one account created (``svc-backup``).
|
||||
Windows names an account by its SID: ``uid`` is its relative identifier, ``sid`` the
|
||||
whole of it (napalm-device-types' ``UserDict.sid``).
|
||||
"""
|
||||
|
||||
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 os_users as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "os_users.json"
|
||||
BASE = "S-1-5-21-1004336348-1177238915-682003330"
|
||||
|
||||
|
||||
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(**changes: Any) -> dict[str, Any]:
|
||||
return {**json.loads(FIXTURE.read_text()), **changes}
|
||||
|
||||
|
||||
def _users(reading: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(json.dumps(reading if reading is not None else _reading()))
|
||||
return {u["username"]: u for u in d.get_os_users()}
|
||||
|
||||
|
||||
def test_an_account_created_reads_like_a_posix_one():
|
||||
assert _users()["svc-backup"] == {
|
||||
"username": "svc-backup",
|
||||
"uid": 1001,
|
||||
"gid": 513,
|
||||
"home": "C:\\Users\\svc-backup",
|
||||
"shell": "",
|
||||
"groups": ["Administrators", "Backup Operators", "Users"],
|
||||
"sid": f"{BASE}-1001",
|
||||
}
|
||||
|
||||
|
||||
def test_the_built_in_accounts_keep_their_well_known_rids():
|
||||
users = _users()
|
||||
assert users["Administrator"]["uid"] == 500
|
||||
assert users["Guest"]["uid"] == 501
|
||||
assert users["Guest"]["groups"] == ["Guests"]
|
||||
|
||||
|
||||
def test_an_account_that_never_logged_on_has_no_home():
|
||||
assert _users()["Guest"]["home"] == ""
|
||||
|
||||
|
||||
def test_a_group_whose_members_could_not_be_read_names_nobody():
|
||||
# Get-LocalGroupMember and the ADSI fallback both failed: the script sends null.
|
||||
reading = _reading()
|
||||
reading["groups"][0]["members"] = None
|
||||
assert "Administrators" not in _users(reading)["svc-backup"]["groups"]
|
||||
|
||||
|
||||
def test_a_single_account_survives_powershells_unwrapping():
|
||||
reading = _reading()
|
||||
reading["users"] = reading["users"][0]
|
||||
reading["groups"] = reading["groups"][0]
|
||||
assert _users(reading)["Administrator"]["groups"] == ["Administrators"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("role", [4, 5])
|
||||
def test_a_domain_controller_has_no_local_accounts_to_list(role):
|
||||
with pytest.raises(NotImplementedError, match="domain controller"):
|
||||
_users(_reading(domain_role=role, users=[], groups=[]))
|
||||
|
||||
|
||||
def test_a_host_without_the_local_accounts_cmdlets_cannot_list_them():
|
||||
with pytest.raises(NotImplementedError, match="Get-LocalUser"):
|
||||
_users(_reading(local_accounts=False, users=[], groups=[]))
|
||||
|
||||
|
||||
def test_one_script_reads_accounts_groups_and_profiles():
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(json.dumps(_reading()))
|
||||
d.get_os_users()
|
||||
(script,) = d._transport.sent # type: ignore[union-attr]
|
||||
assert script == mod._PS_OS_USERS
|
||||
for part in ("Get-LocalUser", "Get-LocalGroupMember", "Win32_UserProfile", "DomainRole"):
|
||||
assert part in script
|
||||
# Probed first, so a host without the module says so instead of failing.
|
||||
assert "Get-Command -Name Get-LocalUser" in script
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Installed software on Windows: the machine-wide Uninstall keys (NetOrk/netork#2890).
|
||||
|
||||
One script reads the native and the 32-bit (``WOW6432Node``) Uninstall key of HKLM; a
|
||||
fake transport answers it from tests/fixtures/synthetic/packages.json. The fixture holds
|
||||
the cases the issue names: 7-Zip installed both as a 64-bit and a 32-bit program, a
|
||||
``SystemComponent`` entry, and an update listed under its product (``ParentKeyName``).
|
||||
"""
|
||||
|
||||
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 packages as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "packages.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() -> list[dict[str, Any]]:
|
||||
return json.loads(FIXTURE.read_text())
|
||||
|
||||
|
||||
def _driver(reading: Any = None) -> WindowsDriver:
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(json.dumps(_reading() if reading is None else reading))
|
||||
return d
|
||||
|
||||
|
||||
def _packages(reading: Any = None) -> list[Any]:
|
||||
return list(_driver(reading).get_packages())
|
||||
|
||||
|
||||
def test_a_program_reads_as_a_package():
|
||||
git = next(p for p in _packages() if p["name"] == "Git")
|
||||
assert git == {
|
||||
"name": "Git",
|
||||
"version": "2.43.0",
|
||||
"installed": True,
|
||||
"description": "",
|
||||
"size": 309000 * 1024,
|
||||
"source": "exe",
|
||||
"publisher": "The Git Development Community",
|
||||
"architecture": "x64",
|
||||
}
|
||||
|
||||
|
||||
def test_a_windows_installer_package_is_msi():
|
||||
acrobat = next(p for p in _packages() if p["name"] == "Adobe Acrobat Reader DC")
|
||||
assert acrobat["source"] == "msi"
|
||||
assert acrobat["architecture"] == "x86"
|
||||
|
||||
|
||||
def test_a_32_and_a_64_bit_install_of_one_program_stay_two_packages():
|
||||
zips = [p for p in _packages() if p["name"].startswith("7-Zip")]
|
||||
assert sorted(p["architecture"] for p in zips) == ["x64", "x86"]
|
||||
|
||||
|
||||
def test_system_components_updates_and_unnamed_keys_are_no_packages():
|
||||
names = [p["name"] for p in _packages()]
|
||||
assert "Office 16 Click-to-Run Extensibility Component" not in names
|
||||
assert "Security Update for Windows Server (KB5034441)" not in names
|
||||
assert "" not in names
|
||||
assert len(names) == 5
|
||||
|
||||
|
||||
def test_packages_come_sorted_by_name():
|
||||
names = [p["name"] for p in _packages()]
|
||||
assert names == sorted(names, key=str.lower)
|
||||
|
||||
|
||||
def test_a_missing_size_is_zero():
|
||||
reading = _reading()
|
||||
reading[5]["size"] = ""
|
||||
assert next(p for p in _packages(reading) if p["name"] == "Git")["size"] == 0
|
||||
|
||||
|
||||
def test_a_single_package_survives_powershells_unwrapping():
|
||||
assert [p["name"] for p in _packages(_reading()[5])] == ["Git"]
|
||||
|
||||
|
||||
def test_a_host_with_nothing_installed_has_no_packages():
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport("[]")
|
||||
assert d.get_packages() == []
|
||||
|
||||
|
||||
def test_one_script_reads_both_machine_wide_keys_and_no_users_hive():
|
||||
d = _driver()
|
||||
d.get_packages()
|
||||
(script,) = d._transport.sent # type: ignore[union-attr]
|
||||
assert script == mod._PS_PACKAGES
|
||||
assert r"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" in script
|
||||
assert r"HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall" in script
|
||||
# The connecting account's own hive says nothing about the host.
|
||||
assert "HKCU" not in script
|
||||
assert "winget" not in script
|
||||
|
||||
|
||||
def test_installing_and_removing_stay_not_offered():
|
||||
assert not hasattr(WindowsDriver, "install_package")
|
||||
assert not hasattr(WindowsDriver, "uninstall_package")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("answer", ["", "null"])
|
||||
def test_an_empty_answer_has_no_packages(answer):
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(answer)
|
||||
assert d.get_packages() == []
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Processes on Windows: ``Win32_Process`` joined with ``Get-Process`` (NetOrk/netork#2889).
|
||||
|
||||
One script reads both; a fake transport answers it from
|
||||
tests/fixtures/synthetic/processes.json. ``Win32_Process`` gives the parent, the command
|
||||
line, the start and the CPU and memory counters, ``Get-Process -IncludeUserName`` the
|
||||
owner. The fixture holds the cases the join decides:
|
||||
|
||||
* 0, the System Idle Process: no process, left out as ``ps`` leaves it out;
|
||||
* 5120, gone by the time ``Get-Process`` ran: dropped, not half-filled;
|
||||
* 6000, a PID ``Get-Process`` reports with another start: a new process under a PID
|
||||
that was reused between the two reads, dropped;
|
||||
* 7777, started after ``Win32_Process`` was read: not part of the reading.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import processes as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "processes.json"
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
def __init__(self, answer: str) -> None:
|
||||
self.answer = answer
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
return self.answer
|
||||
|
||||
|
||||
def _reading() -> dict[str, Any]:
|
||||
return json.loads(FIXTURE.read_text())
|
||||
|
||||
|
||||
def _driver(reading: dict[str, Any] | None = None) -> WindowsDriver:
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(json.dumps(reading if reading is not None else _reading()))
|
||||
return d
|
||||
|
||||
|
||||
def _by_pid(reading: dict[str, Any] | None = None) -> dict[int, Any]:
|
||||
return {p["pid"]: p for p in _driver(reading).get_processes()}
|
||||
|
||||
|
||||
def test_the_join_keeps_the_processes_both_reads_saw():
|
||||
assert sorted(_by_pid()) == [4, 812, 4312]
|
||||
|
||||
|
||||
def test_a_process_reads_like_ps():
|
||||
assert _by_pid()[4312] == {
|
||||
"pid": 4312,
|
||||
"ppid": 3988,
|
||||
"user": "WIN01\\admin",
|
||||
# 120 CPU seconds in 600 s on 4 logical processors
|
||||
"cpu": 5.0,
|
||||
# 100 MiB of 8 GiB
|
||||
"memory": 1.2,
|
||||
"vsz": 2203500000000 // 1024,
|
||||
"rss": 102400,
|
||||
"tty": "",
|
||||
"state": "",
|
||||
# 11:50 UTC, an hour east of it
|
||||
"started": "Mon Dec 1 12:50:00 2025",
|
||||
"command": '"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" -NoLogo',
|
||||
}
|
||||
|
||||
|
||||
def test_a_process_without_a_command_line_shows_its_name():
|
||||
system = _by_pid()[4]
|
||||
assert system["command"] == "System"
|
||||
assert system["started"] == ""
|
||||
assert system["cpu"] == 0.0
|
||||
|
||||
|
||||
def test_a_start_one_second_apart_is_the_same_process():
|
||||
# Get-Process and CIM round the start differently.
|
||||
reading = _reading()
|
||||
reading["owners"][2]["started"] += 1
|
||||
assert 812 in _by_pid(reading)
|
||||
|
||||
|
||||
def test_without_elevation_the_owner_is_unknown():
|
||||
# Get-Process -IncludeUserName needs an elevated session; the script falls back.
|
||||
reading = _reading()
|
||||
for owner in reading["owners"]:
|
||||
owner.pop("user")
|
||||
assert {p["user"] for p in _by_pid(reading).values()} == {""}
|
||||
|
||||
|
||||
def test_cpu_stays_within_a_hundred_percent():
|
||||
reading = _reading()
|
||||
reading["processes"][3]["cpu"] = 10**13
|
||||
assert _by_pid(reading)[4312]["cpu"] == 100.0
|
||||
|
||||
|
||||
def test_a_single_process_survives_powershells_unwrapping():
|
||||
reading = _reading()
|
||||
reading["processes"] = reading["processes"][2]
|
||||
reading["owners"] = reading["owners"][2]
|
||||
assert sorted(_by_pid(reading)) == [812]
|
||||
|
||||
|
||||
def test_one_script_reads_both_sources():
|
||||
d = _driver()
|
||||
d.get_processes()
|
||||
(script,) = d._transport.sent # type: ignore[union-attr]
|
||||
assert script == mod._PS_PROCESSES
|
||||
assert "Win32_Process" in script
|
||||
assert "Get-Process -IncludeUserName" in script
|
||||
|
||||
|
||||
def test_an_empty_answer_is_no_reading():
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport("")
|
||||
with pytest.raises(ValueError):
|
||||
d.get_processes()
|
||||
@@ -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
|
||||
@@ -0,0 +1,93 @@
|
||||
"""The SMBIOS identity on Windows: CIM classes instead of the DMI files (NetOrk/netork#2888).
|
||||
|
||||
One script reads ``Win32_ComputerSystemProduct``, ``Win32_BaseBoard`` and ``Win32_BIOS``;
|
||||
a fake transport answers it from tests/fixtures/synthetic/system_identity.json, a Dell
|
||||
server as the classes describe it. The placeholders are napalm-device-types' own
|
||||
(``clean_system_identity``).
|
||||
"""
|
||||
|
||||
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 system_identity as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "system_identity.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 _driver(**changes: Any) -> WindowsDriver:
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(json.dumps({**json.loads(FIXTURE.read_text()), **changes}))
|
||||
return d
|
||||
|
||||
|
||||
def test_reads_the_identity_and_the_firmware():
|
||||
assert _driver().get_system_identity() == {
|
||||
"system_uuid": "4c4c4544-0042-3510-8051-b4c04f4d3732",
|
||||
"product_serial": "4B5QM72",
|
||||
"board_serial": ".4B5QM72.CNCMS0012345AB.",
|
||||
"bios_vendor": "Dell Inc.",
|
||||
"bios_version": "2.19.0",
|
||||
"bios_date": "2023-08-15",
|
||||
}
|
||||
|
||||
|
||||
def test_one_script_reads_the_three_classes():
|
||||
d = _driver()
|
||||
d.get_system_identity()
|
||||
(script,) = d._transport.sent # type: ignore[union-attr]
|
||||
assert script == mod._PS_SYSTEM_IDENTITY
|
||||
for cls in ("Win32_ComputerSystemProduct", "Win32_BaseBoard", "Win32_BIOS"):
|
||||
assert cls in script
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("field", "value"),
|
||||
[
|
||||
("product_serial", "To be filled by O.E.M."),
|
||||
("board_serial", "Default string"),
|
||||
("uuid", "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF"),
|
||||
("uuid", "03000200-0400-0500-0006-000700080009"),
|
||||
("bios_vendor", "To be filled by O.E.M."),
|
||||
],
|
||||
)
|
||||
def test_oem_placeholders_read_as_empty(field, value):
|
||||
identity = _driver(**{field: value}).get_system_identity()
|
||||
key = {"uuid": "system_uuid"}.get(field, field)
|
||||
assert identity[key] == "" # type: ignore[literal-required]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["uuid", "product_serial", "board_serial", "bios_date"])
|
||||
def test_a_value_the_host_did_not_give_reads_as_empty(field):
|
||||
# A VM without a base board, a firmware without a release date: null in the JSON.
|
||||
identity = _driver(**{field: None}).get_system_identity()
|
||||
key = {"uuid": "system_uuid"}.get(field, field)
|
||||
assert identity[key] == "" # type: ignore[literal-required]
|
||||
|
||||
|
||||
def test_the_release_date_is_the_utc_day():
|
||||
# CIM gives the SMBIOS date as midnight UTC; the script sends it as Unix time.
|
||||
assert _driver(bios_date=1692057600 + 86399).get_system_identity()["bios_date"] == "2023-08-15"
|
||||
|
||||
|
||||
def test_an_empty_answer_is_no_reading():
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport("")
|
||||
with pytest.raises(ValueError):
|
||||
d.get_system_identity()
|
||||
@@ -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."""
|
||||
|
||||
|
||||
+11
-7
@@ -13,14 +13,15 @@ from __future__ import annotations
|
||||
import argparse
|
||||
import getpass
|
||||
import pathlib
|
||||
import time
|
||||
|
||||
from napalm_windows import (
|
||||
WindowsDriver,
|
||||
event_channels,
|
||||
host_events,
|
||||
host_status,
|
||||
os_users,
|
||||
packages,
|
||||
processes,
|
||||
scheduled_tasks,
|
||||
services,
|
||||
system_identity,
|
||||
time_sync,
|
||||
)
|
||||
from napalm_windows import windows as mod
|
||||
@@ -31,12 +32,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,
|
||||
"system_identity": system_identity._PS_SYSTEM_IDENTITY,
|
||||
"processes": processes._PS_PROCESSES,
|
||||
"os_users": os_users._PS_OS_USERS,
|
||||
"packages": packages._PS_PACKAGES,
|
||||
"host_status": host_status._PS_HOST_STATUS,
|
||||
}
|
||||
|
||||
OUT = pathlib.Path(__file__).parent / "harvest-out"
|
||||
|
||||
Reference in new issue
Block a user