Author SHA1 Message Date
Christian Manivong f8f46c133d refactor(host-status): the restart reasons as a table, within the complexity limit 2026-12-01 12:54:14 +01:00
Christian Manivong 891a31fe45 docs: the host basics in the README and CHANGELOG; harvest records their scripts 2026-12-01 12:53:46 +01:00
Christian Manivong 54b3c9b362 feat(host-status): restart required and automatic updates from Windows Update and the registry (NetOrk/netork#2891) 2026-12-01 12:53:17 +01:00
Christian Manivong 81c4df3159 feat(packages): installed programs from the machine-wide Uninstall keys (NetOrk/netork#2890) 2026-12-01 12:51:31 +01:00
Christian Manivong 169d88f7e5 feat(users): local accounts as UserDict, the RID as uid and the SID beside it (NetOrk/netork#2889) 2026-12-01 12:50:13 +01:00
Christian Manivong a97e59c1e2 feat(processes): running processes from Win32_Process and Get-Process (NetOrk/netork#2889) 2026-12-01 12:49:17 +01:00
Christian Manivong 8ed5e0ed87 feat(identity): the SMBIOS identity from the CIM classes (NetOrk/netork#2888) 2026-12-01 12:47:57 +01:00
christianmanivong 977ddbd904 Merge pull request 'feat(power): restart and shut the host down with Restart-/Stop-Computer (NetOrk/netork#2841)' (#11) from feature/host-shutdown-2841 into main
driver / standard (push) Successful in 13s
driver / lint (push) Successful in 13s
driver / lowest (push) Successful in 25s
driver / types (push) Successful in 48s
driver / test (3.12) (push) Successful in 1m9s
driver / build (push) Successful in 24s
driver / test (3.13) (push) Successful in 56s
driver / security (push) Successful in 56s
CI / driver (push) Successful in 1m55s
driver / publish (push) Skipped
2026-11-29 21:58:22 +00:00
Christian Manivong d7511efd43 feat(power): restart and shut the host down with Restart-/Stop-Computer (NetOrk/netork#2841)
driver / standard (pull_request) Successful in 16s
driver / lint (pull_request) Successful in 13s
driver / test (3.13) (pull_request) Successful in 43s
driver / types (pull_request) Successful in 56s
driver / lowest (pull_request) Successful in 25s
driver / test (3.12) (pull_request) Successful in 55s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 56s
CI / driver (pull_request) Successful in 2m2s
driver / publish (pull_request) Skipped
reboot_host() and shutdown_host() run Restart-Computer and Stop-Computer
without -Force over the PSRP connection: Windows asks running programs
to close and refuses while other users are logged on. A refusal raises
RuntimeError with the host's answer; a connection the host drops before
answering counts as accepted, which PsrpTransport.run_last() reports.
2026-11-29 11:32:33 +01:00
christianmanivong 442541d30a Merge pull request 'feat(time-sync): w32time's servers and the time zone through TimeSyncMixin' (#10) from feature/time-sync-2367 into main
driver / standard (push) Successful in 15s
driver / lint (push) Successful in 14s
driver / types (push) Successful in 1m5s
driver / test (3.12) (push) Successful in 1m2s
driver / test (3.13) (push) Successful in 1m1s
driver / lowest (push) Successful in 29s
driver / build (push) Successful in 30s
driver / security (push) Successful in 1m4s
CI / driver (push) Successful in 2m35s
driver / publish (push) Skipped
2026-11-11 14:51:44 +00:00
Christian Manivong 0b30ab00a5 feat(time-sync): w32time's servers and the time zone through TimeSyncMixin
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 57s
driver / test (3.12) (pull_request) Successful in 58s
driver / test (3.13) (pull_request) Successful in 51s
driver / lowest (pull_request) Successful in 26s
driver / build (pull_request) Successful in 27s
driver / security (pull_request) Successful in 57s
CI / driver (pull_request) Successful in 2m23s
driver / publish (pull_request) Skipped
netOrk keeps one list of NTP servers and a time zone per site and aligns
a device that differs (NetOrk/netork#2360). A Windows host takes part
through w32time and its time zone, in one PowerShell script per read.

The servers and the mode are read from w32time's registry values, group
policy's first, not from w32tm /query /configuration, whose text is in
the host's language; synchronised is the leap indicator on the first
line of w32tm /query /status, which reads the same in any language. The
servers are written the way w32tm /config /manualpeerlist
/syncfromflags:manual writes them (NtpServer with 0x8, Type NTP),
followed by w32tm /config /update: no value passes a native command
line, whose quoting Windows PowerShell 5.1 mangles. A domain member that
takes its time from the domain hierarchy (NT5DS, AllSync) and a host
whose w32time comes from group policy refuse the write: their time is
set elsewhere, and a local write would be overridden or break the
domain's time.

Windows keeps a Windows zone, which stands for several IANA zones, so
Europe/Vienna written would read back as Europe/Berlin and the poll
would align the host forever. The IANA name written is kept beside it
in HKLM\SOFTWARE\napalm-windows and read back while the host is still
in that Windows zone. The zone is read from the registry, which
[TimeZoneInfo]::Local caches for the life of the remote session.

The zone table is now CLDR's windowsZones.xml (release 49) both ways,
generated by tools/windows_zones.py with tzdata's links and committed
with its source and checksum; nothing is fetched at runtime. CLDR's old
names (Asia/Calcutta) read as their current ones (Asia/Kolkata).

Writes the host already has are skipped. Needs napalm-device-types
4.35.0.

Refs NetOrk/netork#2367
2026-11-11 15:27:56 +01:00
christianmanivong 37708009a0 Merge pull request 'feat(scheduled-jobs): the Task Scheduler as scheduled jobs (#8)' (#9) from feature/scheduled-jobs into main
driver / standard (push) Successful in 19s
driver / lint (push) Successful in 18s
driver / types (push) Successful in 1m7s
driver / test (3.12) (push) Successful in 1m2s
driver / test (3.13) (push) Successful in 58s
driver / lowest (push) Successful in 29s
driver / build (push) Successful in 27s
driver / security (push) Successful in 1m1s
CI / driver (push) Successful in 2m40s
driver / publish (push) Skipped
2026-11-03 08:20:27 +00:00
Christian Manivong 74a8c53c7c chore(scheduled-jobs): require napalm-device-types 4.27.0
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 12s
driver / types (pull_request) Successful in 54s
driver / test (3.12) (pull_request) Successful in 55s
driver / test (3.13) (pull_request) Successful in 46s
driver / lowest (pull_request) Successful in 32s
driver / build (pull_request) Successful in 27s
driver / security (pull_request) Successful in 1m1s
CI / driver (pull_request) Successful in 2m22s
driver / publish (pull_request) Skipped
4.26.0 went out with the sshd drop-in change; the scheduled-jobs
contract is in 4.27.0.
2026-11-03 08:36:00 +01:00
Christian Manivong a508b872b0 feat(scheduled-jobs): the Task Scheduler as scheduled jobs (#8)
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 15s
driver / test (3.12) (pull_request) Failing after 14s
driver / types (pull_request) Failing after 23s
driver / test (3.13) (pull_request) Failing after 13s
driver / lowest (pull_request) Failing after 14s
driver / security (pull_request) Failing after 32s
driver / build (pull_request) Successful in 25s
CI / driver (pull_request) Failing after 1m21s
driver / publish (pull_request) Skipped
netOrk shows and controls every scheduled job of a host; on Windows that
is the Task Scheduler. The driver now implements napalm-device-types'
ScheduledJobsMixin over PowerShell Remoting, one script per call as every
getter does.

get_scheduled_jobs reads every task with its run info in one script
(Get-ScheduledTask, Get-ScheduledTaskInfo) as task:<path><name>, its
triggers summarised. Tasks under \Microsoft\ are the platform's, others
the admin's: Windows does not record which software installed a task.
The time zone is mapped to IANA for the common Windows zones, else None.
A reading cut short, or holding fewer tasks than it counted, raises.

manage_scheduled_job switches the task's own flag or starts it;
Start-ScheduledTask returns once the task has started, so the result says
that and no more. A disabled task, or one that refuses a start on demand,
is not offered run.

put_scheduled_job registers an application's task \<name> in the root
folder from XML, so a create and a change write the whole definition the
same way: the command runs in cmd.exe /d /s /c, the principal is SYSTEM
or a local user without a stored password (S4U), and the cron expression
becomes triggers only where Task Scheduler can say it exactly; any other
shape is refused, naming why. The description keeps the job's name and
cron expression, so the reading gives back what was written, and the
digest also covers the triggers, so a change by hand is seen.
delete_scheduled_job unregisters such a task and no other. Every write
reads the task again first, and every value goes into PowerShell
single-quoted with its quotes doubled.

Requires napalm-device-types 4.26.0.

Closes #8
2026-11-03 05:49:12 +01:00
christianmanivong 581c2df5e8 Merge pull request 'fix: an unknown ARP age is -1.0, not 0.0' (#7) from fix/arp-unknown-age into main
driver / standard (push) Successful in 17s
driver / lint (push) Successful in 15s
driver / types (push) Successful in 1m6s
driver / test (3.12) (push) Successful in 1m5s
driver / lowest (push) Successful in 32s
driver / test (3.13) (push) Successful in 57s
driver / build (push) Successful in 31s
driver / security (push) Successful in 1m12s
CI / driver (push) Successful in 2m50s
driver / publish (push) Skipped
2026-10-30 09:11:44 +00:00
Christian Manivong dacefaa606 fix: an unknown ARP age is -1.0, not 0.0
driver / standard (pull_request) Successful in 15s
driver / lint (pull_request) Successful in 19s
driver / types (pull_request) Successful in 1m0s
driver / test (3.12) (pull_request) Successful in 57s
driver / lowest (pull_request) Successful in 24s
driver / test (3.13) (pull_request) Successful in 48s
driver / build (pull_request) Successful in 25s
driver / security (pull_request) Successful in 1m1s
CI / driver (pull_request) Successful in 2m32s
driver / publish (pull_request) Skipped
Get-NetNeighbor reports a state but no age, so get_arp_table reports
ARP_AGE_UNKNOWN instead of 0.0 ("confirmed just now").

NetOrk/netork#1327
2026-10-30 08:37:08 +01:00
christianmanivong 7c985acfad Merge pull request 'chore: Python 3.12 is the floor (NAPALM/driver-standard#6)' (#6) from chore/python-312-floor into main
driver / standard (push) Successful in 15s
driver / lint (push) Successful in 12s
driver / types (push) Successful in 56s
driver / test (3.12) (push) Successful in 55s
driver / test (3.13) (push) Successful in 50s
driver / lowest (push) Successful in 25s
driver / build (push) Successful in 27s
driver / security (push) Successful in 1m2s
CI / driver (push) Successful in 2m24s
driver / publish (push) Skipped
2026-10-27 10:46:56 +00:00
Christian Manivong cd50d3c102 fix: the floor on napalm is 5.1 (NAPALM/driver-standard#6)
driver / standard (pull_request) Successful in 15s
driver / lint (pull_request) Successful in 12s
driver / test (3.12) (pull_request) Successful in 55s
driver / types (pull_request) Successful in 1m1s
driver / test (3.13) (pull_request) Successful in 50s
driver / lowest (pull_request) Successful in 27s
driver / build (pull_request) Successful in 32s
driver / security (pull_request) Successful in 1m26s
CI / driver (pull_request) Successful in 2m51s
driver / publish (pull_request) Skipped
napalm 5.0 and older import pkg_resources, which a Python 3.12 venv no
longer has, so the lowest job failed on them.
2026-10-27 10:49:32 +01:00
Christian Manivong 15740f9e05 chore: Python 3.12 is the floor (NAPALM/driver-standard#6)
driver / standard (pull_request) Successful in 20s
driver / lint (pull_request) Successful in 14s
driver / test (3.12) (pull_request) Successful in 1m2s
driver / types (pull_request) Successful in 1m8s
driver / test (3.13) (pull_request) Successful in 56s
driver / lowest (pull_request) Failing after 30s
driver / build (pull_request) Successful in 34s
driver / security (pull_request) Successful in 1m16s
CI / driver (pull_request) Failing after 2m57s
driver / publish (pull_request) Skipped
netOrk runs every driver in its own containers on Python 3.12, so 3.10
and 3.11 are no longer supported or tested. requires-python, mypy and
ruff move to 3.12, along with what ruff's pyupgrade rules then rewrite.
2026-10-27 10:19:01 +01:00
38 changed files with 4992 additions and 34 deletions

No files matched your search

+80
View File
@@ -6,6 +6,86 @@ All notable changes to this driver. The format follows
## [Unreleased]
### Added
- 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
`-Force`: Windows asks running programs to close and refuses while other users are
logged on, a disconnected session included, instead of throwing away what they have
not saved. A refusal raises `RuntimeError` with the host's answer. Both cmdlets start
the shutdown and return, so no delay is needed before the session goes; a connection
the host drops before answering counts as accepted. `PsrpTransport.run_last(script)`
tells the two apart: `False` when the connection broke, `PowerShellError` when the
script wrote an error.
- Time sync: napalm-device-types' `TimeSyncMixin` (4.35.0), servers and zone
(NetOrk/netork#2367). `get_time_sync` reads w32time's `NtpServer` and `Type` from the
registry (group policy's first; `NoSync` has no servers), whether the clock is
synchronised (the leap indicator of `w32tm /query /status`) and the zone, in one
script. `configure_time_sync` writes the servers as `<server>,0x8` with `Type NTP`
and `w32tm /config /update`, starting a stopped Windows Time service, and the zone
with `Set-TimeZone`. A domain member that takes its time from the domain hierarchy
(`NT5DS`, `AllSync`) reports its configured servers and refuses the write, as does a
host whose w32time settings come from group policy. The IANA name written is kept in
`HKLM\SOFTWARE\napalm-windows` so it reads back as written; writes the host already
has are skipped.
- The time zone table is CLDR's `windowsZones.xml` (release 49), generated into
`napalm_windows/_windows_zones.py` by `tools/windows_zones.py` with tzdata's links,
both ways: every Windows zone reads as an IANA name, not only the common ones, and
every IANA zone CLDR maps has its Windows zone.
- Scheduled jobs: the Task Scheduler as napalm-device-types' `ScheduledJobsMixin` (#8).
`get_scheduled_jobs` reads every task with its last and next run in one script
(`Get-ScheduledTask`, `Get-ScheduledTaskInfo`) as `task:<path><name>`: a task under
`\Microsoft\` is the `platform`'s, any other the `admin`'s, and a task in the root
folder whose description starts with `napalm-scheduled-job: <name>` an `application`'s.
The time zone comes as an IANA name for the common Windows zones, else `None`.
`manage_scheduled_job` enables, disables (`Enable-`/`Disable-ScheduledTask`) or starts
one (`Start-ScheduledTask`, which returns once the task has started). `put_scheduled_job`
registers an application's task `\<name>` from XML: the command runs in
`cmd.exe /d /s /c`, `SYSTEM` or a local user without a stored password (S4U), and the
cron expression becomes triggers where Task Scheduler can express it exactly; any other
shape is refused, naming why. `delete_scheduled_job` unregisters it. Every write reads
the task again first and refuses over a change it did not see. Fixture synthetic.
### Changed
- The floor on napalm-device-types is 4.35.0, which declares the time sync contract.
- Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver
on 3.12, so 3.10 and 3.11 are no longer tested (NAPALM/driver-standard#6).
- The floor on napalm is 5.1: older releases import `pkg_resources`, which a Python
3.12 venv no longer has.
### Fixed
- `get_arp_table()` reports an unknown age as `-1.0` (napalm-device-types'
`ARP_AGE_UNKNOWN`) instead of `0.0`, which means "confirmed just now":
`Get-NetNeighbor` has a state but no age (NetOrk/netork#1327).
## [0.2.0] - 2026-10-23
The first release on PyPI.
+84 -1
View File
@@ -37,13 +37,96 @@ handshake once.
| `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`, `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_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
(`10.0.20348.2340`): Windows ships fixes as UBR bumps, which is what CVE
matching has to compare against.
Not yet: packages, Windows Update, scheduled tasks, health metrics, Hyper-V.
### Scheduled tasks
An application's own job is the task `\<name>` in the root folder, never a folder of
its own. Its description is `napalm-scheduled-job: <name> <description>` and a second
line `schedule: <cron expression>`, so the reading gives back the cron expression and
the command it was written with; its digest also covers the triggers, so triggers
changed by hand count as a change.
* **Command:** `cmd.exe /d /s /c "<command>"` — one line, as a Windows command line.
* **Principal:** `SYSTEM`, or a local user who runs it whether logged on or not
without a stored password (`S4U`). Such a run has no network credentials, and the
user needs the "Log on as a batch job" right.
* **Schedule:** a cron expression becomes triggers only where Task Scheduler can
express it exactly — daily, weekly on weekdays, or monthly on days of the month (in
some months); at one or more times, or evenly spaced times as one repetition
(`*/5`, `*/15 8-17`, `0 */6`), or one repeating trigger per hour (`*/7`); at most 48
triggers. `@reboot` is a boot trigger. Refused, naming why: both a day of the month
and a weekday (cron's *either* rule), a weekday together with days or months, and
times needing more than 48 triggers. A repetition counts elapsed time, so on the day
summer time starts or ends its later runs shift by the hour.
* **Not read:** which software installed a task (Windows does not record it), so a
vendor's updater is `admin`; and the days of a monthly trigger, which
`Get-ScheduledTask` does not expose.
### Time sync
napalm-device-types' `TimeSyncMixin`; both the servers and the zone are written.
* **Servers** are w32time's `NtpServer` in order, without their `,0x` flags; group
policy's values (`HKLM\SOFTWARE\Policies\Microsoft\W32Time\Parameters`) win over
the local ones. `Type NoSync` has none. Written as `<server>,0x8` (client mode) with
`Type NTP` — what `w32tm /config /manualpeerlist /syncfromflags:manual` writes —
then `w32tm /config /update`; a stopped Windows Time service is started first.
* **Domain members** that take their time from the domain hierarchy (`Type NT5DS` or
`AllSync`) report the servers configured, and a write is refused: the domain sets
their time. So is a write where group policy sets w32time.
* **Synchronised** is the leap indicator of `w32tm /query /status` (`3` = not
synchronised); a stopped service is not synchronised. `daemon` is `w32time`.
* **Zone:** Windows keeps a Windows zone (`W. Europe Standard Time`), which stands
for several IANA zones. It is read as the zone CLDR names for it (`Europe/Berlin`)
and written with `Set-TimeZone` from CLDR's mapping
([`windowsZones.xml`](https://github.com/unicode-org/cldr/blob/release-49/common/supplemental/windowsZones.xml),
generated into `napalm_windows/_windows_zones.py` by `tools/windows_zones.py`,
never fetched at runtime). The IANA name written is kept in
`HKLM\SOFTWARE\napalm-windows` (`IanaTimeZone`) and read back while the host is
still in that Windows zone, so `Europe/Vienna` reads back as `Europe/Vienna`. A
zone with summer time switched off reads as `None`; writing the zone switches it
back on.
### Host basics
* **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.
Not yet: Windows Update, health metrics, Hyper-V.
See netork#300 for the plan.
## Preparing a host
+24
View File
@@ -0,0 +1,24 @@
"""What every script and every parse of this driver shares: quoting and the JSON quirk."""
from __future__ import annotations
from typing import Any
# PowerShell accepts these as single-quote delimiters alongside the ASCII one.
_PS_SINGLE_QUOTES = ("'", "‘", "’", "‚", "‛")
def _as_list(value: Any) -> list[Any]:
"""Undo ConvertTo-Json unwrapping a one-element array into a bare value."""
if value is None:
return []
if isinstance(value, list):
return value
return [value]
def _ps_quote(value: str) -> str:
"""Quote ``value`` as a PowerShell single-quoted (verbatim) string."""
for q in _PS_SINGLE_QUOTES:
value = value.replace(q, q + q)
return f"'{value}'"
+18
View File
@@ -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
+732
View File
@@ -0,0 +1,732 @@
"""Windows time zones and IANA names. Generated by tools/windows_zones.py: do not edit.
Source: CLDR release-49, common/supplemental/windowsZones.xml
(sha256 5f902f94106a396cb7774f0b0e1ca4dfecb686494045350c0b4935d378e3913b),
with the link lines of the IANA time zone database 2026e (tzdata.zi).
"""
WINDOWS_TO_IANA: dict[str, str] = {
"AUS Central Standard Time": "Australia/Darwin",
"AUS Eastern Standard Time": "Australia/Sydney",
"Afghanistan Standard Time": "Asia/Kabul",
"Alaskan Standard Time": "America/Anchorage",
"Alberta Standard Time": "America/Edmonton",
"Aleutian Standard Time": "America/Adak",
"Altai Standard Time": "Asia/Barnaul",
"Arab Standard Time": "Asia/Riyadh",
"Arabian Standard Time": "Asia/Dubai",
"Arabic Standard Time": "Asia/Baghdad",
"Argentina Standard Time": "America/Argentina/Buenos_Aires",
"Astrakhan Standard Time": "Europe/Astrakhan",
"Atlantic Standard Time": "America/Halifax",
"Aus Central W. Standard Time": "Australia/Eucla",
"Azerbaijan Standard Time": "Asia/Baku",
"Azores Standard Time": "Atlantic/Azores",
"Bahia Standard Time": "America/Bahia",
"Bangladesh Standard Time": "Asia/Dhaka",
"Belarus Standard Time": "Europe/Minsk",
"Bougainville Standard Time": "Pacific/Bougainville",
"British Columbia Standard Time": "America/Vancouver",
"Canada Central Standard Time": "America/Regina",
"Cape Verde Standard Time": "Atlantic/Cape_Verde",
"Caucasus Standard Time": "Asia/Yerevan",
"Cen. Australia Standard Time": "Australia/Adelaide",
"Central America Standard Time": "America/Guatemala",
"Central Asia Standard Time": "Asia/Bishkek",
"Central Brazilian Standard Time": "America/Cuiaba",
"Central Europe Standard Time": "Europe/Budapest",
"Central European Standard Time": "Europe/Warsaw",
"Central Pacific Standard Time": "Pacific/Guadalcanal",
"Central Standard Time": "America/Chicago",
"Central Standard Time (Mexico)": "America/Mexico_City",
"Chatham Islands Standard Time": "Pacific/Chatham",
"China Standard Time": "Asia/Shanghai",
"Cuba Standard Time": "America/Havana",
"Dateline Standard Time": "Etc/GMT+12",
"E. Africa Standard Time": "Africa/Nairobi",
"E. Australia Standard Time": "Australia/Brisbane",
"E. Europe Standard Time": "Europe/Chisinau",
"E. South America Standard Time": "America/Sao_Paulo",
"Easter Island Standard Time": "Pacific/Easter",
"Eastern Standard Time": "America/New_York",
"Eastern Standard Time (Mexico)": "America/Cancun",
"Egypt Standard Time": "Africa/Cairo",
"Ekaterinburg Standard Time": "Asia/Yekaterinburg",
"FLE Standard Time": "Europe/Kyiv",
"Fiji Standard Time": "Pacific/Fiji",
"GMT Standard Time": "Europe/London",
"GTB Standard Time": "Europe/Bucharest",
"Georgian Standard Time": "Asia/Tbilisi",
"Greenland Standard Time": "America/Nuuk",
"Greenwich Standard Time": "Atlantic/Reykjavik",
"Haiti Standard Time": "America/Port-au-Prince",
"Hawaiian Standard Time": "Pacific/Honolulu",
"India Standard Time": "Asia/Kolkata",
"Iran Standard Time": "Asia/Tehran",
"Israel Standard Time": "Asia/Jerusalem",
"Jordan Standard Time": "Asia/Amman",
"Kaliningrad Standard Time": "Europe/Kaliningrad",
"Korea Standard Time": "Asia/Seoul",
"Libya Standard Time": "Africa/Tripoli",
"Line Islands Standard Time": "Pacific/Kiritimati",
"Lord Howe Standard Time": "Australia/Lord_Howe",
"Magadan Standard Time": "Asia/Magadan",
"Magallanes Standard Time": "America/Punta_Arenas",
"Manitoba Standard Time": "America/Winnipeg",
"Marquesas Standard Time": "Pacific/Marquesas",
"Mauritius Standard Time": "Indian/Mauritius",
"Middle East Standard Time": "Asia/Beirut",
"Montevideo Standard Time": "America/Montevideo",
"Morocco Standard Time": "Africa/Casablanca",
"Mountain Standard Time": "America/Denver",
"Mountain Standard Time (Mexico)": "America/Mazatlan",
"Myanmar Standard Time": "Asia/Yangon",
"N. Central Asia Standard Time": "Asia/Novosibirsk",
"Namibia Standard Time": "Africa/Windhoek",
"Nepal Standard Time": "Asia/Kathmandu",
"New Zealand Standard Time": "Pacific/Auckland",
"Newfoundland Standard Time": "America/St_Johns",
"Norfolk Standard Time": "Pacific/Norfolk",
"North Asia East Standard Time": "Asia/Irkutsk",
"North Asia Standard Time": "Asia/Krasnoyarsk",
"North Korea Standard Time": "Asia/Pyongyang",
"Omsk Standard Time": "Asia/Omsk",
"Pacific SA Standard Time": "America/Santiago",
"Pacific Standard Time": "America/Los_Angeles",
"Pacific Standard Time (Mexico)": "America/Tijuana",
"Pakistan Standard Time": "Asia/Karachi",
"Paraguay Standard Time": "America/Asuncion",
"Qyzylorda Standard Time": "Asia/Qyzylorda",
"Romance Standard Time": "Europe/Paris",
"Russia Time Zone 10": "Asia/Srednekolymsk",
"Russia Time Zone 11": "Asia/Kamchatka",
"Russia Time Zone 3": "Europe/Samara",
"Russian Standard Time": "Europe/Moscow",
"SA Eastern Standard Time": "America/Cayenne",
"SA Pacific Standard Time": "America/Bogota",
"SA Western Standard Time": "America/La_Paz",
"SE Asia Standard Time": "Asia/Bangkok",
"Saint Pierre Standard Time": "America/Miquelon",
"Sakhalin Standard Time": "Asia/Sakhalin",
"Samoa Standard Time": "Pacific/Apia",
"Sao Tome Standard Time": "Africa/Sao_Tome",
"Saratov Standard Time": "Europe/Saratov",
"Singapore Standard Time": "Asia/Singapore",
"South Africa Standard Time": "Africa/Johannesburg",
"South Sudan Standard Time": "Africa/Juba",
"Sri Lanka Standard Time": "Asia/Colombo",
"Sudan Standard Time": "Africa/Khartoum",
"Syria Standard Time": "Asia/Damascus",
"Taipei Standard Time": "Asia/Taipei",
"Tasmania Standard Time": "Australia/Hobart",
"Tocantins Standard Time": "America/Araguaina",
"Tokyo Standard Time": "Asia/Tokyo",
"Tomsk Standard Time": "Asia/Tomsk",
"Tonga Standard Time": "Pacific/Tongatapu",
"Transbaikal Standard Time": "Asia/Chita",
"Turkey Standard Time": "Europe/Istanbul",
"Turks And Caicos Standard Time": "America/Grand_Turk",
"US Eastern Standard Time": "America/Indiana/Indianapolis",
"US Mountain Standard Time": "America/Phoenix",
"UTC": "Etc/UTC",
"UTC+12": "Etc/GMT-12",
"UTC+13": "Etc/GMT-13",
"UTC-02": "Etc/GMT+2",
"UTC-08": "Etc/GMT+8",
"UTC-09": "Etc/GMT+9",
"UTC-11": "Etc/GMT+11",
"Ulaanbaatar Standard Time": "Asia/Ulaanbaatar",
"Venezuela Standard Time": "America/Caracas",
"Vladivostok Standard Time": "Asia/Vladivostok",
"Volgograd Standard Time": "Europe/Volgograd",
"W. Australia Standard Time": "Australia/Perth",
"W. Central Africa Standard Time": "Africa/Lagos",
"W. Europe Standard Time": "Europe/Berlin",
"W. Mongolia Standard Time": "Asia/Hovd",
"West Asia Standard Time": "Asia/Tashkent",
"West Bank Standard Time": "Asia/Hebron",
"West Pacific Standard Time": "Pacific/Port_Moresby",
"Yakutsk Standard Time": "Asia/Yakutsk",
"Yukon Standard Time": "America/Whitehorse",
}
IANA_TO_WINDOWS: dict[str, str] = {
"Africa/Abidjan": "Greenwich Standard Time",
"Africa/Accra": "Greenwich Standard Time",
"Africa/Addis_Ababa": "E. Africa Standard Time",
"Africa/Algiers": "W. Central Africa Standard Time",
"Africa/Asmara": "E. Africa Standard Time",
"Africa/Asmera": "E. Africa Standard Time",
"Africa/Bamako": "Greenwich Standard Time",
"Africa/Bangui": "W. Central Africa Standard Time",
"Africa/Banjul": "Greenwich Standard Time",
"Africa/Bissau": "Greenwich Standard Time",
"Africa/Blantyre": "South Africa Standard Time",
"Africa/Brazzaville": "W. Central Africa Standard Time",
"Africa/Bujumbura": "South Africa Standard Time",
"Africa/Cairo": "Egypt Standard Time",
"Africa/Casablanca": "Morocco Standard Time",
"Africa/Ceuta": "Romance Standard Time",
"Africa/Conakry": "Greenwich Standard Time",
"Africa/Dakar": "Greenwich Standard Time",
"Africa/Dar_es_Salaam": "E. Africa Standard Time",
"Africa/Djibouti": "E. Africa Standard Time",
"Africa/Douala": "W. Central Africa Standard Time",
"Africa/El_Aaiun": "Morocco Standard Time",
"Africa/Freetown": "Greenwich Standard Time",
"Africa/Gaborone": "South Africa Standard Time",
"Africa/Harare": "South Africa Standard Time",
"Africa/Johannesburg": "South Africa Standard Time",
"Africa/Juba": "South Sudan Standard Time",
"Africa/Kampala": "E. Africa Standard Time",
"Africa/Khartoum": "Sudan Standard Time",
"Africa/Kigali": "South Africa Standard Time",
"Africa/Kinshasa": "W. Central Africa Standard Time",
"Africa/Lagos": "W. Central Africa Standard Time",
"Africa/Libreville": "W. Central Africa Standard Time",
"Africa/Lome": "Greenwich Standard Time",
"Africa/Luanda": "W. Central Africa Standard Time",
"Africa/Lubumbashi": "South Africa Standard Time",
"Africa/Lusaka": "South Africa Standard Time",
"Africa/Malabo": "W. Central Africa Standard Time",
"Africa/Maputo": "South Africa Standard Time",
"Africa/Maseru": "South Africa Standard Time",
"Africa/Mbabane": "South Africa Standard Time",
"Africa/Mogadishu": "E. Africa Standard Time",
"Africa/Monrovia": "Greenwich Standard Time",
"Africa/Nairobi": "E. Africa Standard Time",
"Africa/Ndjamena": "W. Central Africa Standard Time",
"Africa/Niamey": "W. Central Africa Standard Time",
"Africa/Nouakchott": "Greenwich Standard Time",
"Africa/Ouagadougou": "Greenwich Standard Time",
"Africa/Porto-Novo": "W. Central Africa Standard Time",
"Africa/Sao_Tome": "Sao Tome Standard Time",
"Africa/Timbuktu": "Greenwich Standard Time",
"Africa/Tripoli": "Libya Standard Time",
"Africa/Tunis": "W. Central Africa Standard Time",
"Africa/Windhoek": "Namibia Standard Time",
"America/Adak": "Aleutian Standard Time",
"America/Anchorage": "Alaskan Standard Time",
"America/Anguilla": "SA Western Standard Time",
"America/Antigua": "SA Western Standard Time",
"America/Araguaina": "Tocantins Standard Time",
"America/Argentina/Buenos_Aires": "Argentina Standard Time",
"America/Argentina/Catamarca": "Argentina Standard Time",
"America/Argentina/Cordoba": "Argentina Standard Time",
"America/Argentina/Jujuy": "Argentina Standard Time",
"America/Argentina/La_Rioja": "Argentina Standard Time",
"America/Argentina/Mendoza": "Argentina Standard Time",
"America/Argentina/Rio_Gallegos": "Argentina Standard Time",
"America/Argentina/Salta": "Argentina Standard Time",
"America/Argentina/San_Juan": "Argentina Standard Time",
"America/Argentina/San_Luis": "Argentina Standard Time",
"America/Argentina/Tucuman": "Argentina Standard Time",
"America/Argentina/Ushuaia": "Argentina Standard Time",
"America/Aruba": "SA Western Standard Time",
"America/Asuncion": "Paraguay Standard Time",
"America/Atikokan": "SA Pacific Standard Time",
"America/Atka": "Aleutian Standard Time",
"America/Bahia": "Bahia Standard Time",
"America/Bahia_Banderas": "Central Standard Time (Mexico)",
"America/Barbados": "SA Western Standard Time",
"America/Belem": "SA Eastern Standard Time",
"America/Belize": "Central America Standard Time",
"America/Blanc-Sablon": "SA Western Standard Time",
"America/Boa_Vista": "SA Western Standard Time",
"America/Bogota": "SA Pacific Standard Time",
"America/Boise": "Mountain Standard Time",
"America/Buenos_Aires": "Argentina Standard Time",
"America/Cambridge_Bay": "Mountain Standard Time",
"America/Campo_Grande": "Central Brazilian Standard Time",
"America/Cancun": "Eastern Standard Time (Mexico)",
"America/Caracas": "Venezuela Standard Time",
"America/Catamarca": "Argentina Standard Time",
"America/Cayenne": "SA Eastern Standard Time",
"America/Cayman": "SA Pacific Standard Time",
"America/Chicago": "Central Standard Time",
"America/Chihuahua": "Central Standard Time (Mexico)",
"America/Ciudad_Juarez": "Mountain Standard Time",
"America/Coral_Harbour": "SA Pacific Standard Time",
"America/Cordoba": "Argentina Standard Time",
"America/Costa_Rica": "Central America Standard Time",
"America/Coyhaique": "Magallanes Standard Time",
"America/Creston": "US Mountain Standard Time",
"America/Cuiaba": "Central Brazilian Standard Time",
"America/Curacao": "SA Western Standard Time",
"America/Danmarkshavn": "Greenwich Standard Time",
"America/Dawson": "Yukon Standard Time",
"America/Dawson_Creek": "US Mountain Standard Time",
"America/Denver": "Mountain Standard Time",
"America/Detroit": "Eastern Standard Time",
"America/Dominica": "SA Western Standard Time",
"America/Edmonton": "Alberta Standard Time",
"America/Eirunepe": "SA Pacific Standard Time",
"America/El_Salvador": "Central America Standard Time",
"America/Ensenada": "Pacific Standard Time (Mexico)",
"America/Fort_Nelson": "US Mountain Standard Time",
"America/Fortaleza": "SA Eastern Standard Time",
"America/Glace_Bay": "Atlantic Standard Time",
"America/Godthab": "Greenland Standard Time",
"America/Goose_Bay": "Atlantic Standard Time",
"America/Grand_Turk": "Turks And Caicos Standard Time",
"America/Grenada": "SA Western Standard Time",
"America/Guadeloupe": "SA Western Standard Time",
"America/Guatemala": "Central America Standard Time",
"America/Guayaquil": "SA Pacific Standard Time",
"America/Guyana": "SA Western Standard Time",
"America/Halifax": "Atlantic Standard Time",
"America/Havana": "Cuba Standard Time",
"America/Hermosillo": "US Mountain Standard Time",
"America/Indiana/Indianapolis": "US Eastern Standard Time",
"America/Indiana/Knox": "Central Standard Time",
"America/Indiana/Marengo": "US Eastern Standard Time",
"America/Indiana/Petersburg": "Eastern Standard Time",
"America/Indiana/Tell_City": "Central Standard Time",
"America/Indiana/Vevay": "US Eastern Standard Time",
"America/Indiana/Vincennes": "Eastern Standard Time",
"America/Indiana/Winamac": "Eastern Standard Time",
"America/Indianapolis": "US Eastern Standard Time",
"America/Inuvik": "Alberta Standard Time",
"America/Iqaluit": "Eastern Standard Time",
"America/Jamaica": "SA Pacific Standard Time",
"America/Jujuy": "Argentina Standard Time",
"America/Juneau": "Alaskan Standard Time",
"America/Kentucky/Louisville": "Eastern Standard Time",
"America/Kentucky/Monticello": "Eastern Standard Time",
"America/Knox_IN": "Central Standard Time",
"America/Kralendijk": "SA Western Standard Time",
"America/La_Paz": "SA Western Standard Time",
"America/Lima": "SA Pacific Standard Time",
"America/Los_Angeles": "Pacific Standard Time",
"America/Louisville": "Eastern Standard Time",
"America/Lower_Princes": "SA Western Standard Time",
"America/Maceio": "SA Eastern Standard Time",
"America/Managua": "Central America Standard Time",
"America/Manaus": "SA Western Standard Time",
"America/Marigot": "SA Western Standard Time",
"America/Martinique": "SA Western Standard Time",
"America/Matamoros": "Central Standard Time",
"America/Mazatlan": "Mountain Standard Time (Mexico)",
"America/Mendoza": "Argentina Standard Time",
"America/Menominee": "Central Standard Time",
"America/Merida": "Central Standard Time (Mexico)",
"America/Metlakatla": "Alaskan Standard Time",
"America/Mexico_City": "Central Standard Time (Mexico)",
"America/Miquelon": "Saint Pierre Standard Time",
"America/Moncton": "Atlantic Standard Time",
"America/Monterrey": "Central Standard Time (Mexico)",
"America/Montevideo": "Montevideo Standard Time",
"America/Montreal": "Eastern Standard Time",
"America/Montserrat": "SA Western Standard Time",
"America/Nassau": "Eastern Standard Time",
"America/New_York": "Eastern Standard Time",
"America/Nipigon": "Eastern Standard Time",
"America/Nome": "Alaskan Standard Time",
"America/Noronha": "UTC-02",
"America/North_Dakota/Beulah": "Central Standard Time",
"America/North_Dakota/Center": "Central Standard Time",
"America/North_Dakota/New_Salem": "Central Standard Time",
"America/Nuuk": "Greenland Standard Time",
"America/Ojinaga": "Central Standard Time",
"America/Panama": "SA Pacific Standard Time",
"America/Pangnirtung": "Eastern Standard Time",
"America/Paramaribo": "SA Eastern Standard Time",
"America/Phoenix": "US Mountain Standard Time",
"America/Port-au-Prince": "Haiti Standard Time",
"America/Port_of_Spain": "SA Western Standard Time",
"America/Porto_Acre": "SA Pacific Standard Time",
"America/Porto_Velho": "SA Western Standard Time",
"America/Puerto_Rico": "SA Western Standard Time",
"America/Punta_Arenas": "Magallanes Standard Time",
"America/Rainy_River": "Manitoba Standard Time",
"America/Rankin_Inlet": "Central Standard Time",
"America/Recife": "SA Eastern Standard Time",
"America/Regina": "Canada Central Standard Time",
"America/Resolute": "Central Standard Time",
"America/Rio_Branco": "SA Pacific Standard Time",
"America/Santa_Isabel": "Pacific Standard Time (Mexico)",
"America/Santarem": "SA Eastern Standard Time",
"America/Santiago": "Pacific SA Standard Time",
"America/Santo_Domingo": "SA Western Standard Time",
"America/Sao_Paulo": "E. South America Standard Time",
"America/Scoresbysund": "Azores Standard Time",
"America/Shiprock": "Mountain Standard Time",
"America/Sitka": "Alaskan Standard Time",
"America/St_Barthelemy": "SA Western Standard Time",
"America/St_Johns": "Newfoundland Standard Time",
"America/St_Kitts": "SA Western Standard Time",
"America/St_Lucia": "SA Western Standard Time",
"America/St_Thomas": "SA Western Standard Time",
"America/St_Vincent": "SA Western Standard Time",
"America/Swift_Current": "Canada Central Standard Time",
"America/Tegucigalpa": "Central America Standard Time",
"America/Thule": "Atlantic Standard Time",
"America/Thunder_Bay": "Eastern Standard Time",
"America/Tijuana": "Pacific Standard Time (Mexico)",
"America/Toronto": "Eastern Standard Time",
"America/Tortola": "SA Western Standard Time",
"America/Vancouver": "British Columbia Standard Time",
"America/Virgin": "SA Western Standard Time",
"America/Whitehorse": "Yukon Standard Time",
"America/Winnipeg": "Manitoba Standard Time",
"America/Yakutat": "Alaskan Standard Time",
"America/Yellowknife": "Alberta Standard Time",
"Antarctica/Casey": "Central Pacific Standard Time",
"Antarctica/Davis": "SE Asia Standard Time",
"Antarctica/DumontDUrville": "West Pacific Standard Time",
"Antarctica/Macquarie": "Tasmania Standard Time",
"Antarctica/Mawson": "West Asia Standard Time",
"Antarctica/McMurdo": "New Zealand Standard Time",
"Antarctica/Palmer": "SA Eastern Standard Time",
"Antarctica/Rothera": "SA Eastern Standard Time",
"Antarctica/South_Pole": "New Zealand Standard Time",
"Antarctica/Syowa": "E. Africa Standard Time",
"Antarctica/Vostok": "Central Asia Standard Time",
"Arctic/Longyearbyen": "W. Europe Standard Time",
"Asia/Aden": "Arab Standard Time",
"Asia/Almaty": "West Asia Standard Time",
"Asia/Amman": "Jordan Standard Time",
"Asia/Anadyr": "Russia Time Zone 11",
"Asia/Aqtau": "West Asia Standard Time",
"Asia/Aqtobe": "West Asia Standard Time",
"Asia/Ashgabat": "West Asia Standard Time",
"Asia/Ashkhabad": "West Asia Standard Time",
"Asia/Atyrau": "West Asia Standard Time",
"Asia/Baghdad": "Arabic Standard Time",
"Asia/Bahrain": "Arab Standard Time",
"Asia/Baku": "Azerbaijan Standard Time",
"Asia/Bangkok": "SE Asia Standard Time",
"Asia/Barnaul": "Altai Standard Time",
"Asia/Beirut": "Middle East Standard Time",
"Asia/Bishkek": "Central Asia Standard Time",
"Asia/Brunei": "Singapore Standard Time",
"Asia/Calcutta": "India Standard Time",
"Asia/Chita": "Transbaikal Standard Time",
"Asia/Choibalsan": "Ulaanbaatar Standard Time",
"Asia/Chongqing": "China Standard Time",
"Asia/Chungking": "China Standard Time",
"Asia/Colombo": "Sri Lanka Standard Time",
"Asia/Dacca": "Bangladesh Standard Time",
"Asia/Damascus": "Syria Standard Time",
"Asia/Dhaka": "Bangladesh Standard Time",
"Asia/Dili": "Tokyo Standard Time",
"Asia/Dubai": "Arabian Standard Time",
"Asia/Dushanbe": "West Asia Standard Time",
"Asia/Famagusta": "GTB Standard Time",
"Asia/Gaza": "West Bank Standard Time",
"Asia/Harbin": "China Standard Time",
"Asia/Hebron": "West Bank Standard Time",
"Asia/Ho_Chi_Minh": "SE Asia Standard Time",
"Asia/Hong_Kong": "China Standard Time",
"Asia/Hovd": "W. Mongolia Standard Time",
"Asia/Irkutsk": "North Asia East Standard Time",
"Asia/Istanbul": "Turkey Standard Time",
"Asia/Jakarta": "SE Asia Standard Time",
"Asia/Jayapura": "Tokyo Standard Time",
"Asia/Jerusalem": "Israel Standard Time",
"Asia/Kabul": "Afghanistan Standard Time",
"Asia/Kamchatka": "Russia Time Zone 11",
"Asia/Karachi": "Pakistan Standard Time",
"Asia/Kashgar": "Central Asia Standard Time",
"Asia/Kathmandu": "Nepal Standard Time",
"Asia/Katmandu": "Nepal Standard Time",
"Asia/Khandyga": "Yakutsk Standard Time",
"Asia/Kolkata": "India Standard Time",
"Asia/Krasnoyarsk": "North Asia Standard Time",
"Asia/Kuala_Lumpur": "Singapore Standard Time",
"Asia/Kuching": "Singapore Standard Time",
"Asia/Kuwait": "Arab Standard Time",
"Asia/Macao": "China Standard Time",
"Asia/Macau": "China Standard Time",
"Asia/Magadan": "Magadan Standard Time",
"Asia/Makassar": "Singapore Standard Time",
"Asia/Manila": "Singapore Standard Time",
"Asia/Muscat": "Arabian Standard Time",
"Asia/Nicosia": "GTB Standard Time",
"Asia/Novokuznetsk": "North Asia Standard Time",
"Asia/Novosibirsk": "N. Central Asia Standard Time",
"Asia/Omsk": "Omsk Standard Time",
"Asia/Oral": "West Asia Standard Time",
"Asia/Phnom_Penh": "SE Asia Standard Time",
"Asia/Pontianak": "SE Asia Standard Time",
"Asia/Pyongyang": "North Korea Standard Time",
"Asia/Qatar": "Arab Standard Time",
"Asia/Qostanay": "West Asia Standard Time",
"Asia/Qyzylorda": "Qyzylorda Standard Time",
"Asia/Rangoon": "Myanmar Standard Time",
"Asia/Riyadh": "Arab Standard Time",
"Asia/Saigon": "SE Asia Standard Time",
"Asia/Sakhalin": "Sakhalin Standard Time",
"Asia/Samarkand": "West Asia Standard Time",
"Asia/Seoul": "Korea Standard Time",
"Asia/Shanghai": "China Standard Time",
"Asia/Singapore": "Singapore Standard Time",
"Asia/Srednekolymsk": "Russia Time Zone 10",
"Asia/Taipei": "Taipei Standard Time",
"Asia/Tashkent": "West Asia Standard Time",
"Asia/Tbilisi": "Georgian Standard Time",
"Asia/Tehran": "Iran Standard Time",
"Asia/Tel_Aviv": "Israel Standard Time",
"Asia/Thimbu": "Bangladesh Standard Time",
"Asia/Thimphu": "Bangladesh Standard Time",
"Asia/Tokyo": "Tokyo Standard Time",
"Asia/Tomsk": "Tomsk Standard Time",
"Asia/Ujung_Pandang": "Singapore Standard Time",
"Asia/Ulaanbaatar": "Ulaanbaatar Standard Time",
"Asia/Ulan_Bator": "Ulaanbaatar Standard Time",
"Asia/Urumqi": "Central Asia Standard Time",
"Asia/Ust-Nera": "Vladivostok Standard Time",
"Asia/Vientiane": "SE Asia Standard Time",
"Asia/Vladivostok": "Vladivostok Standard Time",
"Asia/Yakutsk": "Yakutsk Standard Time",
"Asia/Yangon": "Myanmar Standard Time",
"Asia/Yekaterinburg": "Ekaterinburg Standard Time",
"Asia/Yerevan": "Caucasus Standard Time",
"Atlantic/Azores": "Azores Standard Time",
"Atlantic/Bermuda": "Atlantic Standard Time",
"Atlantic/Canary": "GMT Standard Time",
"Atlantic/Cape_Verde": "Cape Verde Standard Time",
"Atlantic/Faeroe": "GMT Standard Time",
"Atlantic/Faroe": "GMT Standard Time",
"Atlantic/Jan_Mayen": "W. Europe Standard Time",
"Atlantic/Madeira": "GMT Standard Time",
"Atlantic/Reykjavik": "Greenwich Standard Time",
"Atlantic/South_Georgia": "UTC-02",
"Atlantic/St_Helena": "Greenwich Standard Time",
"Atlantic/Stanley": "SA Eastern Standard Time",
"Australia/ACT": "AUS Eastern Standard Time",
"Australia/Adelaide": "Cen. Australia Standard Time",
"Australia/Brisbane": "E. Australia Standard Time",
"Australia/Broken_Hill": "Cen. Australia Standard Time",
"Australia/Canberra": "AUS Eastern Standard Time",
"Australia/Currie": "Tasmania Standard Time",
"Australia/Darwin": "AUS Central Standard Time",
"Australia/Eucla": "Aus Central W. Standard Time",
"Australia/Hobart": "Tasmania Standard Time",
"Australia/LHI": "Lord Howe Standard Time",
"Australia/Lindeman": "E. Australia Standard Time",
"Australia/Lord_Howe": "Lord Howe Standard Time",
"Australia/Melbourne": "AUS Eastern Standard Time",
"Australia/NSW": "AUS Eastern Standard Time",
"Australia/North": "AUS Central Standard Time",
"Australia/Perth": "W. Australia Standard Time",
"Australia/Queensland": "E. Australia Standard Time",
"Australia/South": "Cen. Australia Standard Time",
"Australia/Sydney": "AUS Eastern Standard Time",
"Australia/Tasmania": "Tasmania Standard Time",
"Australia/Victoria": "AUS Eastern Standard Time",
"Australia/West": "W. Australia Standard Time",
"Australia/Yancowinna": "Cen. Australia Standard Time",
"Brazil/Acre": "SA Pacific Standard Time",
"Brazil/DeNoronha": "UTC-02",
"Brazil/East": "E. South America Standard Time",
"Brazil/West": "SA Western Standard Time",
"Canada/Atlantic": "Atlantic Standard Time",
"Canada/Central": "Manitoba Standard Time",
"Canada/Eastern": "Eastern Standard Time",
"Canada/Mountain": "Alberta Standard Time",
"Canada/Newfoundland": "Newfoundland Standard Time",
"Canada/Pacific": "British Columbia Standard Time",
"Canada/Saskatchewan": "Canada Central Standard Time",
"Canada/Yukon": "Yukon Standard Time",
"Chile/Continental": "Pacific SA Standard Time",
"Chile/EasterIsland": "Easter Island Standard Time",
"Cuba": "Cuba Standard Time",
"Egypt": "Egypt Standard Time",
"Eire": "GMT Standard Time",
"Etc/GMT": "UTC",
"Etc/GMT+0": "UTC",
"Etc/GMT+1": "Cape Verde Standard Time",
"Etc/GMT+10": "Hawaiian Standard Time",
"Etc/GMT+11": "UTC-11",
"Etc/GMT+12": "Dateline Standard Time",
"Etc/GMT+2": "UTC-02",
"Etc/GMT+3": "SA Eastern Standard Time",
"Etc/GMT+4": "SA Western Standard Time",
"Etc/GMT+5": "SA Pacific Standard Time",
"Etc/GMT+6": "Central America Standard Time",
"Etc/GMT+7": "US Mountain Standard Time",
"Etc/GMT+8": "UTC-08",
"Etc/GMT+9": "UTC-09",
"Etc/GMT-0": "UTC",
"Etc/GMT-1": "W. Central Africa Standard Time",
"Etc/GMT-10": "West Pacific Standard Time",
"Etc/GMT-11": "Central Pacific Standard Time",
"Etc/GMT-12": "UTC+12",
"Etc/GMT-13": "UTC+13",
"Etc/GMT-14": "Line Islands Standard Time",
"Etc/GMT-2": "South Africa Standard Time",
"Etc/GMT-3": "E. Africa Standard Time",
"Etc/GMT-4": "Arabian Standard Time",
"Etc/GMT-5": "West Asia Standard Time",
"Etc/GMT-6": "Central Asia Standard Time",
"Etc/GMT-7": "SE Asia Standard Time",
"Etc/GMT-8": "Singapore Standard Time",
"Etc/GMT-9": "Tokyo Standard Time",
"Etc/GMT0": "UTC",
"Etc/Greenwich": "UTC",
"Etc/UCT": "UTC",
"Etc/UTC": "UTC",
"Etc/Universal": "UTC",
"Etc/Zulu": "UTC",
"Europe/Amsterdam": "W. Europe Standard Time",
"Europe/Andorra": "W. Europe Standard Time",
"Europe/Astrakhan": "Astrakhan Standard Time",
"Europe/Athens": "GTB Standard Time",
"Europe/Belfast": "GMT Standard Time",
"Europe/Belgrade": "Central Europe Standard Time",
"Europe/Berlin": "W. Europe Standard Time",
"Europe/Bratislava": "Central Europe Standard Time",
"Europe/Brussels": "Romance Standard Time",
"Europe/Bucharest": "GTB Standard Time",
"Europe/Budapest": "Central Europe Standard Time",
"Europe/Busingen": "W. Europe Standard Time",
"Europe/Chisinau": "E. Europe Standard Time",
"Europe/Copenhagen": "Romance Standard Time",
"Europe/Dublin": "GMT Standard Time",
"Europe/Gibraltar": "W. Europe Standard Time",
"Europe/Guernsey": "GMT Standard Time",
"Europe/Helsinki": "FLE Standard Time",
"Europe/Isle_of_Man": "GMT Standard Time",
"Europe/Istanbul": "Turkey Standard Time",
"Europe/Jersey": "GMT Standard Time",
"Europe/Kaliningrad": "Kaliningrad Standard Time",
"Europe/Kiev": "FLE Standard Time",
"Europe/Kirov": "Russian Standard Time",
"Europe/Kyiv": "FLE Standard Time",
"Europe/Lisbon": "GMT Standard Time",
"Europe/Ljubljana": "Central Europe Standard Time",
"Europe/London": "GMT Standard Time",
"Europe/Luxembourg": "W. Europe Standard Time",
"Europe/Madrid": "Romance Standard Time",
"Europe/Malta": "W. Europe Standard Time",
"Europe/Mariehamn": "FLE Standard Time",
"Europe/Minsk": "Belarus Standard Time",
"Europe/Monaco": "W. Europe Standard Time",
"Europe/Moscow": "Russian Standard Time",
"Europe/Nicosia": "GTB Standard Time",
"Europe/Oslo": "W. Europe Standard Time",
"Europe/Paris": "Romance Standard Time",
"Europe/Podgorica": "Central Europe Standard Time",
"Europe/Prague": "Central Europe Standard Time",
"Europe/Riga": "FLE Standard Time",
"Europe/Rome": "W. Europe Standard Time",
"Europe/Samara": "Russia Time Zone 3",
"Europe/San_Marino": "W. Europe Standard Time",
"Europe/Sarajevo": "Central European Standard Time",
"Europe/Saratov": "Saratov Standard Time",
"Europe/Simferopol": "Russian Standard Time",
"Europe/Skopje": "Central European Standard Time",
"Europe/Sofia": "FLE Standard Time",
"Europe/Stockholm": "W. Europe Standard Time",
"Europe/Tallinn": "FLE Standard Time",
"Europe/Tirane": "Central Europe Standard Time",
"Europe/Tiraspol": "E. Europe Standard Time",
"Europe/Ulyanovsk": "Astrakhan Standard Time",
"Europe/Vaduz": "W. Europe Standard Time",
"Europe/Vatican": "W. Europe Standard Time",
"Europe/Vienna": "W. Europe Standard Time",
"Europe/Vilnius": "FLE Standard Time",
"Europe/Volgograd": "Volgograd Standard Time",
"Europe/Warsaw": "Central European Standard Time",
"Europe/Zagreb": "Central European Standard Time",
"Europe/Zurich": "W. Europe Standard Time",
"GB": "GMT Standard Time",
"GB-Eire": "GMT Standard Time",
"GMT": "UTC",
"GMT+0": "UTC",
"GMT-0": "UTC",
"GMT0": "UTC",
"Greenwich": "UTC",
"Hongkong": "China Standard Time",
"Iceland": "Greenwich Standard Time",
"Indian/Antananarivo": "E. Africa Standard Time",
"Indian/Chagos": "Central Asia Standard Time",
"Indian/Christmas": "SE Asia Standard Time",
"Indian/Cocos": "Myanmar Standard Time",
"Indian/Comoro": "E. Africa Standard Time",
"Indian/Kerguelen": "West Asia Standard Time",
"Indian/Mahe": "Mauritius Standard Time",
"Indian/Maldives": "West Asia Standard Time",
"Indian/Mauritius": "Mauritius Standard Time",
"Indian/Mayotte": "E. Africa Standard Time",
"Indian/Reunion": "Mauritius Standard Time",
"Iran": "Iran Standard Time",
"Israel": "Israel Standard Time",
"Jamaica": "SA Pacific Standard Time",
"Japan": "Tokyo Standard Time",
"Kwajalein": "UTC+12",
"Libya": "Libya Standard Time",
"Mexico/BajaNorte": "Pacific Standard Time (Mexico)",
"Mexico/BajaSur": "Mountain Standard Time (Mexico)",
"Mexico/General": "Central Standard Time (Mexico)",
"NZ": "New Zealand Standard Time",
"NZ-CHAT": "Chatham Islands Standard Time",
"Navajo": "Mountain Standard Time",
"PRC": "China Standard Time",
"Pacific/Apia": "Samoa Standard Time",
"Pacific/Auckland": "New Zealand Standard Time",
"Pacific/Bougainville": "Bougainville Standard Time",
"Pacific/Chatham": "Chatham Islands Standard Time",
"Pacific/Chuuk": "West Pacific Standard Time",
"Pacific/Easter": "Easter Island Standard Time",
"Pacific/Efate": "Central Pacific Standard Time",
"Pacific/Enderbury": "UTC+13",
"Pacific/Fakaofo": "UTC+13",
"Pacific/Fiji": "Fiji Standard Time",
"Pacific/Funafuti": "UTC+12",
"Pacific/Galapagos": "Central America Standard Time",
"Pacific/Gambier": "UTC-09",
"Pacific/Guadalcanal": "Central Pacific Standard Time",
"Pacific/Guam": "West Pacific Standard Time",
"Pacific/Honolulu": "Hawaiian Standard Time",
"Pacific/Johnston": "Hawaiian Standard Time",
"Pacific/Kanton": "UTC+13",
"Pacific/Kiritimati": "Line Islands Standard Time",
"Pacific/Kosrae": "Central Pacific Standard Time",
"Pacific/Kwajalein": "UTC+12",
"Pacific/Majuro": "UTC+12",
"Pacific/Marquesas": "Marquesas Standard Time",
"Pacific/Midway": "UTC-11",
"Pacific/Nauru": "UTC+12",
"Pacific/Niue": "UTC-11",
"Pacific/Norfolk": "Norfolk Standard Time",
"Pacific/Noumea": "Central Pacific Standard Time",
"Pacific/Pago_Pago": "UTC-11",
"Pacific/Palau": "Tokyo Standard Time",
"Pacific/Pitcairn": "UTC-08",
"Pacific/Pohnpei": "Central Pacific Standard Time",
"Pacific/Ponape": "Central Pacific Standard Time",
"Pacific/Port_Moresby": "West Pacific Standard Time",
"Pacific/Rarotonga": "Hawaiian Standard Time",
"Pacific/Saipan": "West Pacific Standard Time",
"Pacific/Samoa": "UTC-11",
"Pacific/Tahiti": "Hawaiian Standard Time",
"Pacific/Tarawa": "UTC+12",
"Pacific/Tongatapu": "Tonga Standard Time",
"Pacific/Truk": "West Pacific Standard Time",
"Pacific/Wake": "UTC+12",
"Pacific/Wallis": "UTC+12",
"Poland": "Central European Standard Time",
"Portugal": "GMT Standard Time",
"ROC": "Taipei Standard Time",
"ROK": "Korea Standard Time",
"Singapore": "Singapore Standard Time",
"Turkey": "Turkey Standard Time",
"UCT": "UTC",
"US/Alaska": "Alaskan Standard Time",
"US/Aleutian": "Aleutian Standard Time",
"US/Arizona": "US Mountain Standard Time",
"US/Central": "Central Standard Time",
"US/Eastern": "Eastern Standard Time",
"US/Hawaii": "Hawaiian Standard Time",
"US/Indiana-Starke": "Central Standard Time",
"US/Michigan": "Eastern Standard Time",
"US/Mountain": "Mountain Standard Time",
"US/Pacific": "Pacific Standard Time",
"US/Samoa": "UTC-11",
"UTC": "UTC",
"Universal": "UTC",
"W-SU": "Russian Standard Time",
"Zulu": "UTC",
}
+28
View File
@@ -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."""
+230
View File
@@ -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"))
+143
View File
@@ -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"))
+119
View File
@@ -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))
+159
View File
@@ -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"))
+461
View File
@@ -0,0 +1,461 @@
"""Scheduled jobs on Windows: the Task Scheduler over PowerShell Remoting (#8).
:class:`WindowsScheduledJobsMixin` implements napalm-device-types'
:class:`~napalm_device_types.scheduled_jobs.ScheduledJobsMixin` for the driver,
which carries each script across ``PsrpTransport.run``.
**Reading** is one script: every task (``Get-ScheduledTask``) with what the host
says of its runs (``Get-ScheduledTaskInfo``), projected onto flat fields, and the
host's time zone; Python only normalises. Every task is a job ``task:<path><name>``
whose schedule is a summary of its triggers. A task under ``\\Microsoft\\`` is the
``platform``'s, any other the ``admin``'s -- Windows does not say which software
installed a task -- and a task in the root folder whose description starts with
``napalm-scheduled-job: <its name>`` is an ``application``'s, read back as the cron
expression and command it was written with (:mod:`napalm_windows.task_xml`). Its
digest covers its triggers as well, so triggers changed by hand are a change. A
reading whose task count does not match, or whose JSON is cut short, raises.
**Switching** is the task's own flag (``Enable-`` / ``Disable-ScheduledTask``);
**running** is ``Start-ScheduledTask``, which returns once the task has started: how
the run ends shows in the next reading. A disabled task, or one that does not allow a
start on demand, is not offered ``run``. A task is addressed by its exact path and
name, never by ``-TaskName``, which takes wildcards.
**An application's own job** is registered from XML (``Register-ScheduledTask -Xml
-Force``), so creating it and changing it write the whole definition the same way;
``delete_scheduled_job`` unregisters it. Before every write the job is read again
and compared with the digest the caller saw; a task of the same name that an
application did not write is never overwritten. Every value goes into PowerShell
single-quoted, its quotes doubled.
"""
from __future__ import annotations
import json
import re
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any, NamedTuple
from napalm_device_types import (
ScheduledJobChanged,
ScheduledJobDict,
ScheduledJobRefused,
ScheduledJobResultDict,
ScheduledJobsMixin,
ScheduledJobSpecDict,
ScheduledJobsReadingDict,
job_digest,
)
from napalm_device_types.scheduled_jobs import ACTIONS, DELETE, EDIT, check_spec
from napalm_windows._powershell import _as_list, _ps_quote
from napalm_windows.task_xml import JOB_MARKER, SCHEDULE_LINE, own_command, task_xml
from napalm_windows.time_zones import iana_time_zone
from napalm_windows.transport import PowerShellError
# Every task with its run info. Times leave the host as ISO 8601 in UTC; a task
# whose run info cannot be read keeps its definition and loses only its times.
_PS_SCHEDULED_TASKS = r"""
$ErrorActionPreference = 'Stop'
function U($d) { if ($d) { ([datetime]$d).ToUniversalTime().ToString('o') } }
$tasks = @(Get-ScheduledTask)
$rows = @($tasks | ForEach-Object {
$t = $_
$i = $t | Get-ScheduledTaskInfo -ErrorAction SilentlyContinue
[pscustomobject]@{
path = $t.TaskPath
name = $t.TaskName
state = [string]$t.State
user = $t.Principal.UserId
group = $t.Principal.GroupId
on_demand = $t.Settings.AllowDemandStart
description = $t.Description
actions = @($t.Actions | ForEach-Object {
[pscustomobject]@{
class = $_.CimClass.CimClassName
execute = $_.Execute
arguments = $_.Arguments
class_id = $_.ClassId
}
})
triggers = @($t.Triggers | ForEach-Object {
[pscustomobject]@{
class = $_.CimClass.CimClassName
enabled = $_.Enabled
start = [string]$_.StartBoundary
days_interval = $_.DaysInterval
weeks_interval = $_.WeeksInterval
days_of_week = $_.DaysOfWeek
interval = [string]$_.Repetition.Interval
duration = [string]$_.Repetition.Duration
delay = [string]$_.Delay
}
})
last_run = U $i.LastRunTime
last_result = $i.LastTaskResult
next_run = U $i.NextRunTime
}
})
ConvertTo-Json -Compress -Depth 5 -InputObject ([pscustomobject]@{
time_zone = [System.TimeZoneInfo]::Local.Id
count = $tasks.Count
tasks = $rows
})
"""
# One task by its exact path and name, handed to a cmdlet.
_PS_TASK_CMDLET = r"""
$ErrorActionPreference = 'Stop'
$task = @(Get-ScheduledTask | Where-Object {{ $_.TaskPath -eq {path} -and $_.TaskName -eq {name} }})
if ($task.Count -ne 1) {{ throw ('no single scheduled task ' + {path} + {name}) }}
$task[0] | {cmdlet} | Out-Null
"""
_PS_REGISTER = r"""
$ErrorActionPreference = 'Stop'
Register-ScheduledTask -TaskPath {path} -TaskName {name} -Xml {xml} -Force | Out-Null
"""
_PS_UNREGISTER = r"""
$ErrorActionPreference = 'Stop'
Unregister-ScheduledTask -TaskPath {path} -TaskName {name} -Confirm:$false
"""
_CMDLETS = {
"enable": ("Enable-ScheduledTask", "enabled"),
"disable": ("Disable-ScheduledTask", "disabled"),
"run": (
"Start-ScheduledTask",
"started; Start-ScheduledTask returns once it has started, so how the run "
"ends shows in the next reading",
),
}
_ROOT = "\\"
_JOB_NAME = re.compile(r"[a-z0-9][a-z0-9-]{0,62}")
_DOTNET_DATE = re.compile(r"^/Date\((-?\d+)(?:[+-]\d{4})?\)/$")
_BOUNDARY = re.compile(r"^(\d{4}-\d\d-\d\d)T(\d\d:\d\d)(?::\d\d(?:\.\d+)?)?(Z|[+-]\d\d:\d\d)?$")
_DURATION = re.compile(r"^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$")
_DURATION_UNITS = ("day", "hour", "minute", "second")
#: LastTaskResult: SCHED_S_TASK_RUNNING and SCHED_S_TASK_HAS_NOT_RUN.
_RUNNING = 0x41301
_NEVER_RAN = 0x41303
_WEEKDAYS = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
_EVENT_TRIGGERS = {
"MSFT_TaskBootTrigger": "at startup",
"MSFT_TaskLogonTrigger": "at logon",
"MSFT_TaskIdleTrigger": "on idle",
"MSFT_TaskEventTrigger": "on an event",
"MSFT_TaskSessionStateChangeTrigger": "session state change",
"MSFT_TaskRegistrationTrigger": "at registration",
}
# ---------------------------------------------------------------------------
# Reading
# ---------------------------------------------------------------------------
def _timestamp(value: Any) -> str | None:
"""A time as the host gave it -- ISO 8601, ``/Date(ms)/`` or epoch seconds -- as
ISO 8601 in UTC; None for none, and for Task Scheduler's never (30 November 1999)."""
if value is None or value == "":
return None
if isinstance(value, int | float):
at = datetime.fromtimestamp(value, UTC)
elif match := _DOTNET_DATE.match(str(value).strip()):
at = datetime.fromtimestamp(int(match[1]) / 1000, UTC)
else:
try:
at = datetime.fromisoformat(str(value).strip())
except ValueError:
return None
at = (at if at.tzinfo else at.replace(tzinfo=UTC)).astimezone(UTC)
return None if at.year < 2000 else at.isoformat()
def _last_result(code: Any, last_run: str | None) -> str | None:
if last_run is None or code is None:
return None
code = int(code) & 0xFFFFFFFF
if code == _NEVER_RAN:
return None
if code == _RUNNING:
return "running"
return "success" if code == 0 else f"0x{code:X}"
def _readable_duration(value: str) -> str:
"""``PT1H30M`` → ``1 hour 30 minutes``; anything else as it is."""
match = _DURATION.match(value)
if not match or not any(match.groups()):
return value
parts = [
f"{n} {unit}{'' if n == '1' else 's'}"
for n, unit in zip(match.groups(), _DURATION_UNITS, strict=True)
if n
]
return " ".join(parts)
def _clock(start: str) -> tuple[str, str]:
"""A trigger's start boundary as its date and its time of day (with its offset)."""
match = _BOUNDARY.match(start)
if not match:
return "", start
return match[1], match[2] + (match[3] or "")
def _every(count: Any, unit: str) -> str:
return f"{unit}ly" if count in (None, 0, 1) else f"every {count} {unit}s"
def _calendar(trigger: dict[str, Any], cls: str) -> str:
date, time = _clock(str(trigger.get("start") or ""))
at = f" at {time}" if time else ""
if cls == "MSFT_TaskDailyTrigger":
days = trigger.get("days_interval")
return ("daily" if days in (None, 0, 1) else f"every {days} days") + at
if cls == "MSFT_TaskWeeklyTrigger":
mask = int(trigger.get("days_of_week") or 0)
days = ",".join(d for i, d in enumerate(_WEEKDAYS) if mask & (1 << i))
return f"{_every(trigger.get('weeks_interval'), 'week')} on {days}{at}"
if cls == "MSFT_TaskTimeTrigger":
return f"once at {date} {time}".rstrip()
return f"trigger{at}"
def _trigger(trigger: dict[str, Any]) -> str:
"""One trigger as a short sentence: its kind, when, how it repeats."""
cls = str(trigger.get("class") or "")
text = _EVENT_TRIGGERS.get(cls) or _calendar(trigger, cls)
if trigger.get("delay"):
text += f" after {_readable_duration(str(trigger['delay']))}"
if trigger.get("interval"):
text += f", every {_readable_duration(str(trigger['interval']))}"
if trigger.get("duration"):
text += f" for {_readable_duration(str(trigger['duration']))}"
if trigger.get("enabled") is False:
text += " (disabled)"
return text
def _action(action: dict[str, Any]) -> str:
if action.get("execute"):
return " ".join(str(p) for p in (action["execute"], action.get("arguments")) if p)
if action.get("class_id"):
return f"COM handler {action['class_id']}"
return str(action.get("class") or "")
class _Own(NamedTuple):
"""What an application's task description and action say of the job."""
name: str
description: str
schedule: str | None
command: str | None
def _own(path: str, name: str, task: dict[str, Any]) -> _Own | None:
"""The application's job this task is; None for any other task."""
lines = str(task.get("description") or "").splitlines()
if path != _ROOT or not lines or not lines[0].startswith(JOB_MARKER):
return None
job_name, _, description = lines[0][len(JOB_MARKER) :].partition(" ")
if job_name != name or not _JOB_NAME.fullmatch(name):
return None
schedule = next(
(ln[len(SCHEDULE_LINE) :] for ln in lines[1:] if ln.startswith(SCHEDULE_LINE)), None
)
actions = _as_list(task.get("actions"))
command = (
own_command(actions[0].get("execute"), actions[0].get("arguments"))
if len(actions) == 1
else None
)
return _Own(name, description.strip(), schedule, command)
def _verbs(task: dict[str, Any], enabled: bool, own: bool) -> list[str]:
verbs = ["enable", "disable"]
if enabled and task.get("on_demand") is not False:
verbs.append("run")
return [*verbs, EDIT, DELETE] if own else verbs
class _Definition(NamedTuple):
"""What a task's fields say it does, as the job shows it."""
schedule: str
schedule_kind: str
command: str
managed_by: str
description: str
def _definition(path: str, task: dict[str, Any], triggers: str, own: _Own | None) -> _Definition:
command = "\n".join(_action(a) for a in _as_list(task.get("actions")))
if own is not None:
kind = "cron" if own.schedule else "triggers"
return _Definition(
own.schedule or triggers, kind, own.command or command, "application", own.description
)
platform = path.lower().startswith("\\microsoft\\")
return _Definition(
triggers,
"triggers",
command,
"platform" if platform else "admin",
str(task.get("description") or "").strip(),
)
def _task_job(task: dict[str, Any]) -> ScheduledJobDict:
path, name = str(task.get("path") or _ROOT), str(task.get("name") or "")
triggers = "; ".join(_trigger(t) for t in _as_list(task.get("triggers")))
enabled = str(task.get("state") or "").lower() != "disabled"
own = _own(path, name, task)
found = _definition(path, task, triggers, own)
last_run = _timestamp(task.get("last_run"))
job: ScheduledJobDict = {
"key": f"task:{path}{name}",
"kind": "task",
"source": f"{path}{name}",
"run_as": str(task.get("user") or task.get("group") or ""),
"schedule": found.schedule,
"schedule_kind": found.schedule_kind,
"command": found.command,
"enabled": enabled,
"managed_by": found.managed_by,
"digest": "",
"actions": _verbs(task, enabled, own is not None),
"last_run": last_run,
"last_result": _last_result(task.get("last_result"), last_run),
"next_run": _timestamp(task.get("next_run")),
}
# An application's task shows its cron line; its triggers are what runs.
job["digest"] = job_digest(dict(job), content=triggers if own else "")
if own is not None:
job["name"] = own.name
if found.description:
job["description"] = found.description
return job
def parse_reading(output: str) -> tuple[list[ScheduledJobDict], str | None]:
"""The jobs and the IANA time zone in what :data:`_PS_SCHEDULED_TASKS` printed.
:raises ValueError: when the reading is cut short or holds fewer tasks than counted.
"""
raw = json.loads(output)
if not isinstance(raw, dict):
raise ValueError("not a scheduled-tasks reading")
tasks = _as_list(raw.get("tasks"))
count = int(raw.get("count") or 0)
if len(tasks) != count:
raise ValueError(f"the reading holds {len(tasks)} of {count} scheduled tasks")
return [_task_job(t) for t in tasks], iana_time_zone(raw.get("time_zone"))
def _path_and_name(source: str) -> tuple[str, str]:
path, _, name = source.rpartition("\\")
return path + "\\", name
# ---------------------------------------------------------------------------
# The mixin
# ---------------------------------------------------------------------------
class WindowsScheduledJobsMixin(ScheduledJobsMixin):
"""The Task Scheduler as scheduled jobs; the driver carries the scripts."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def _sj_read(self) -> tuple[list[ScheduledJobDict], str | None]:
return parse_reading(self._run_raw(_PS_SCHEDULED_TASKS))
def get_scheduled_jobs(self) -> ScheduledJobsReadingDict:
"""Every task of the host, in one round trip.
:raises ValueError: when the reading came back cut short.
"""
jobs, time_zone = self._sj_read()
return {"jobs": jobs, "time_zone": time_zone}
def _sj_job(self, key: str, digest: str) -> ScheduledJobDict:
jobs, _ = self._sj_read()
job = next((j for j in jobs if j["key"] == key), None)
if job is None:
raise LookupError(f"no scheduled job {key}")
if job["digest"] != digest:
raise ScheduledJobChanged(f"{key} changed on the host since it was read")
return job
def _sj_send(self, script: str, done: str) -> ScheduledJobResultDict:
try:
self._run_raw(script)
except PowerShellError as exc:
return {"success": False, "output": str(exc)}
return {"success": True, "output": done}
def manage_scheduled_job(self, key: str, action: str, *, digest: str) -> ScheduledJobResultDict:
"""Enable, disable or start the task *key*; see :class:`ScheduledJobsMixin`."""
if action not in ACTIONS:
raise ScheduledJobRefused(f"unknown action {action!r}; allowed: {list(ACTIONS)}")
job = self._sj_job(key, digest)
if action not in job["actions"]:
raise ScheduledJobRefused(
f"{key} cannot be told to {action}: it is disabled or "
"does not allow a start on demand"
)
cmdlet, done = _CMDLETS[action]
path, name = _path_and_name(job["source"])
script = _PS_TASK_CMDLET.format(path=_ps_quote(path), name=_ps_quote(name), cmdlet=cmdlet)
return self._sj_send(script, f"{key} {done}")
def _sj_own(self, spec: ScheduledJobSpecDict, digest: str | None) -> ScheduledJobDict | None:
key = f"task:{_ROOT}{spec['name']}"
jobs, _ = self._sj_read()
# Task names are case-insensitive: Register -Force would replace "\Name" too.
current = next((j for j in jobs if j["key"].lower() == key), None)
if digest is None:
if current is not None:
raise ScheduledJobChanged(f"a task {current['source']} is there already")
return None
if current is None:
raise LookupError(f"no scheduled job {key}")
if current["managed_by"] != "application":
raise ScheduledJobRefused(f"{current['key']} was not written by an application")
if current["digest"] != digest:
raise ScheduledJobChanged(f"{key} changed on the host since it was read")
return current
def put_scheduled_job(
self, spec: ScheduledJobSpecDict, *, digest: str | None = None
) -> ScheduledJobResultDict:
"""Register or change the application's own task; see :class:`ScheduledJobsMixin`."""
check_spec(spec)
xml = task_xml(spec)
current = self._sj_own(spec, digest)
script = _PS_REGISTER.format(
path=_ps_quote(_ROOT), name=_ps_quote(spec["name"]), xml=_ps_quote(xml)
)
verb = "changed" if current else "created"
return self._sj_send(script, f"task:{_ROOT}{spec['name']} {verb}")
def delete_scheduled_job(self, key: str, *, digest: str) -> ScheduledJobResultDict:
"""Unregister the application's task *key*; see :class:`ScheduledJobsMixin`."""
job = self._sj_job(key, digest)
if job["managed_by"] != "application":
raise ScheduledJobRefused(
f"{key} was not written by an application; it is only switched"
)
path, name = _path_and_name(job["source"])
script = _PS_UNREGISTER.format(path=_ps_quote(path), name=_ps_quote(name))
return self._sj_send(script, f"{key} deleted")
+85
View File
@@ -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")
)
+249
View File
@@ -0,0 +1,249 @@
"""An application's scheduled job as Task Scheduler XML (#8). Pure: no I/O.
:meth:`~napalm_windows.scheduled_tasks.WindowsScheduledJobsMixin.put_scheduled_job`
registers the task this module writes, in the root folder ``\\``, named by the job.
**The cron expression becomes triggers, exactly or not at all.** A day schedule is
one of Task Scheduler's: every day (``ScheduleByDay``), weekdays
(``ScheduleByWeek``), or days of the month in some months (``ScheduleByMonth``).
The times of day become one trigger at the first time with a repetition when they
are three or more evenly spaced (``*/5``, ``*/15 8-17``, ``0 */6``), else one trigger per time,
else one repeating trigger per hour when the minutes are evenly spaced (``*/7``) --
at most 48 triggers, Task Scheduler's limit. ``@reboot`` is a boot trigger. What
Task Scheduler cannot say is refused, naming why: cron's *either* rule (both day
fields set), a weekday together with days of the month or with months, and times
that need more than 48 triggers. A trigger's start is a local time without an
offset, so it follows the host's clock as cron does; a repetition counts elapsed
time, so on the day summer time starts or ends its later runs shift by the hour.
**The command runs in ``cmd.exe``**: ``cmd.exe /d /s /c "<command>"`` -- ``/d``
skips AutoRun, ``/s`` keeps the command as it is between the outer quotes. One line,
as a command line is; the reading gives it back as it was written.
**The principal** is ``SYSTEM`` (the local system account) or a local user, who
runs it whether logged on or not without a stored password (``S4U``): such a run
has no network credentials, so a share needs the computer's access.
**The description** is ``napalm-scheduled-job: <name> <description>`` and a second
line ``schedule: <cron expression>``: the job's name, and its schedule as the
application gave it.
"""
from __future__ import annotations
import html
from itertools import pairwise
from napalm_device_types import ScheduledJobRefused, ScheduledJobSpecDict
from napalm_device_types.cron import CronSchedule, is_reboot, parse_cron
#: The first line of an application's task description, before its name.
JOB_MARKER = "napalm-scheduled-job: "
#: The line of an application's task description that holds its cron expression.
SCHEDULE_LINE = "schedule: "
CMD = "%SystemRoot%\\System32\\cmd.exe"
_CMD_PREFIX = '/d /s /c "'
#: Task Scheduler's limit of triggers on one task.
MAX_TRIGGERS = 48
_START_DATE = "2020-01-01"
_SYSTEM_SID = "S-1-5-18"
_NAMESPACE = "http://schemas.microsoft.com/windows/2004/02/mit/task"
_WEEKDAYS = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
_MONTHS = (
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
)
_ALL_DAYS = frozenset(range(1, 32))
_ALL_MONTHS = frozenset(range(1, 13))
_ALL_WEEKDAYS = frozenset(range(7))
#: (minute of the day it starts, repetition interval, repetition duration) in minutes.
_Clock = tuple[int, int | None, int | None]
# -- the command ---------------------------------------------------------------------------------
def _escape(text: str) -> str:
"""*text* as XML character data."""
return html.escape(text, quote=False)
def _check_text(what: str, text: str) -> None:
if "\n" in text or "\r" in text:
raise ScheduledJobRefused(f"a task's {what} is one line")
if any(ord(c) < 32 and c != "\t" for c in text):
raise ScheduledJobRefused(f"a task's {what} cannot hold a control character")
def command_action(command: str) -> tuple[str, str]:
"""The ``Exec`` action's command and arguments that run *command* in ``cmd.exe``."""
command = command.strip()
_check_text("command", command)
return CMD, f'{_CMD_PREFIX}{command}"'
def own_command(execute: str | None, arguments: str | None) -> str | None:
"""The command :func:`command_action` wrapped; None for any other action."""
args = arguments or ""
if (execute or "").lower() != CMD.lower():
return None
if not (args.startswith(_CMD_PREFIX) and args.endswith('"') and len(args) > len(_CMD_PREFIX)):
return None
return args[len(_CMD_PREFIX) : -1]
def description(spec: ScheduledJobSpecDict) -> str:
"""The task's description: the job's name and description, then its cron expression."""
first = f"{JOB_MARKER}{spec['name']} {spec.get('description') or ''}".rstrip()
return f"{first}\n{SCHEDULE_LINE}{spec['schedule'].strip()}"
# -- the schedule --------------------------------------------------------------------------------
def _evenly_spaced(values: list[int]) -> int | None:
"""The step between *values*, two or more; None when they are not evenly spaced."""
if len(values) < 2:
return None
step = values[1] - values[0]
return step if all(b - a == step for a, b in pairwise(values)) else None
def _clocks(s: CronSchedule) -> list[_Clock]:
times = sorted(h * 60 + m for h in s.hours for m in s.minutes)
step = _evenly_spaced(times)
if step is not None and len(times) > 2:
return [(times[0], step, times[-1] - times[0] + 1)]
if len(times) <= MAX_TRIGGERS:
return [(t, None, None) for t in times]
minutes = sorted(s.minutes)
step = _evenly_spaced(minutes)
if step is not None and len(s.hours) <= MAX_TRIGGERS:
span = minutes[-1] - minutes[0] + 1
return [(h * 60 + minutes[0], step, span) for h in sorted(s.hours)]
raise ScheduledJobRefused(
f"these times of day need more than {MAX_TRIGGERS} triggers, Task Scheduler's limit"
)
def _names(names: tuple[str, ...], values: frozenset[int], first: int) -> str:
return "".join(f"<{names[v - first]} />" for v in sorted(values))
def _day_schedule(s: CronSchedule) -> str:
if s.either_day:
raise ScheduledJobRefused(
"Task Scheduler cannot fire on either a day of the month or a weekday, "
"as cron does when both are set"
)
every_date = s.days == _ALL_DAYS and s.months == _ALL_MONTHS
if s.weekdays == _ALL_WEEKDAYS and every_date:
return "<ScheduleByDay><DaysInterval>1</DaysInterval></ScheduleByDay>"
if every_date:
days = _names(_WEEKDAYS, s.weekdays, 0)
return (
f"<ScheduleByWeek><DaysOfWeek>{days}</DaysOfWeek>"
"<WeeksInterval>1</WeeksInterval></ScheduleByWeek>"
)
if s.weekdays == _ALL_WEEKDAYS:
days = "".join(f"<Day>{d}</Day>" for d in sorted(s.days))
months = _names(_MONTHS, s.months, 1)
return (
f"<ScheduleByMonth><DaysOfMonth>{days}</DaysOfMonth>"
f"<Months>{months}</Months></ScheduleByMonth>"
)
raise ScheduledJobRefused(
"Task Scheduler cannot combine a weekday with days of the month or with months"
)
def _duration(minutes: int) -> str:
hours, rest = divmod(minutes, 60)
return "PT" + (f"{hours}H" if hours else "") + (f"{rest}M" if rest or not hours else "")
def _calendar_trigger(clock: _Clock, day_schedule: str) -> str:
start, interval, duration = clock
repetition = ""
if interval is not None and duration is not None:
repetition = (
f"<Repetition><Interval>{_duration(interval)}</Interval>"
f"<Duration>{_duration(duration)}</Duration>"
"<StopAtDurationEnd>false</StopAtDurationEnd></Repetition>"
)
hour, minute = divmod(start, 60)
return (
f"<CalendarTrigger>{repetition}"
f"<StartBoundary>{_START_DATE}T{hour:02d}:{minute:02d}:00</StartBoundary>"
f"<Enabled>true</Enabled>{day_schedule}</CalendarTrigger>"
)
def triggers(schedule: str) -> list[str]:
"""The triggers that fire exactly when the cron expression *schedule* does.
:raises ScheduledJobRefused: for a shape Task Scheduler cannot express, or an
expression cron would not take.
"""
if is_reboot(schedule):
return ["<BootTrigger><Enabled>true</Enabled></BootTrigger>"]
try:
s = parse_cron(schedule)
except ValueError as exc:
raise ScheduledJobRefused(str(exc)) from exc
day_schedule = _day_schedule(s)
return [_calendar_trigger(clock, day_schedule) for clock in _clocks(s)]
# -- the task ------------------------------------------------------------------------------------
def _principal(run_as: str) -> str:
if run_as.upper() == "SYSTEM":
return f"<UserId>{_SYSTEM_SID}</UserId><RunLevel>HighestAvailable</RunLevel>"
return (
f"<UserId>{_escape(run_as)}</UserId><LogonType>S4U</LogonType>"
"<RunLevel>LeastPrivilege</RunLevel>"
)
def task_xml(spec: ScheduledJobSpecDict) -> str:
"""The whole task for *spec*, as ``Register-ScheduledTask -Xml`` takes it.
:raises ScheduledJobRefused: for a schedule, command or description a task
cannot hold.
"""
execute, arguments = command_action(spec["command"])
_check_text("description", spec.get("description") or "")
trigger_xml = "".join(triggers(spec["schedule"]))
enabled = "true" if spec["enabled"] else "false"
return (
f'<Task version="1.2" xmlns="{_NAMESPACE}">'
f"<RegistrationInfo><Description>{_escape(description(spec))}</Description>"
"</RegistrationInfo>"
f"<Triggers>{trigger_xml}</Triggers>"
f'<Principals><Principal id="Author">{_principal(spec["run_as"])}</Principal></Principals>'
"<Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>"
"<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>"
"<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>"
"<StartWhenAvailable>false</StartWhenAvailable>"
"<AllowStartOnDemand>true</AllowStartOnDemand>"
f"<Enabled>{enabled}</Enabled></Settings>"
f'<Actions Context="Author"><Exec><Command>{_escape(execute)}</Command>'
f"<Arguments>{_escape(arguments)}</Arguments></Exec></Actions>"
"</Task>"
)
+221
View File
@@ -0,0 +1,221 @@
"""Time sync on Windows: the Windows Time service (w32time) and the time zone (NetOrk/netork#2367).
:class:`WindowsTimeSyncMixin` implements napalm-device-types'
:class:`~napalm_device_types.time_sync.TimeSyncMixin` for the driver, which carries
each script across ``PsrpTransport.run``.
**Reading** is one script. The servers and the mode are w32time's registry values
(``Type``, ``NtpServer``), where group policy's override the local ones -- the
registry, not ``w32tm /query /configuration``, whose text is in the host's language.
``NtpServer`` lists ``name,0xFLAGS`` pairs; the flags are dropped. ``Type NoSync``
takes time from nowhere: no servers. Synchronised is the leap indicator of
``w32tm /query /status`` (``3`` = not synchronised), the one value on the first line
whatever the language; a stopped service is not synchronised. The zone is what
``tzutil /g`` reads, the registry's ``TimeZoneInformation`` (``TimeZoneKeyName``), as an
IANA name (:mod:`napalm_windows.time_zones`); one with summer time switched off
(``DynamicDaylightTimeDisabled``, tzutil's ``_dstoff``) is not that zone, and reads as
None. The registry is read anew each time, where ``[TimeZoneInfo]::Local`` is cached
for the life of the remote session.
**Writing the servers** is what ``w32tm /config /manualpeerlist:"a,0x8 b,0x8"
/syncfromflags:manual`` writes -- ``NtpServer`` (``0x8``: client mode, which public
servers answer) and ``Type NTP`` -- set with ``Set-ItemProperty``, then
``w32tm /config /update``, after starting the service where it is stopped. No value
goes through a native command line, whose quoting Windows PowerShell 5.1 mangles.
Two kinds of host are refused before anything is written: a domain member that takes
its time from the domain hierarchy (``NT5DS``, ``AllSync``) -- the domain sets its
time, not the host -- and a host whose w32time settings come from group policy, which
would override the write.
**Writing the zone** is ``Set-TimeZone -Id`` (``tzutil /s``), which also switches summer
time back on. Windows keeps a Windows zone, which stands for
several IANA zones; the IANA name written is kept beside it
(``HKLM:\\SOFTWARE\\napalm-windows``, ``IanaTimeZone``) and read back while the
host is still in its Windows zone, so the zone reads back as written. A zone changed
by hand since reads as its CLDR name.
Each write is skipped where the host already has what it would write.
"""
from __future__ import annotations
import json
import re
from typing import TYPE_CHECKING, Any, ClassVar
from napalm_device_types.models import FixStepOutcomeDict
from napalm_device_types.time_sync import TIME_SYNC_VALUES, TimeSyncDict, TimeSyncMixin
from napalm_windows._powershell import _ps_quote
from napalm_windows.time_zones import IANA_TO_WINDOWS, iana_time_zone, windows_time_zone
_W32TIME = r"HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\Parameters"
_TZ_INFO = r"HKLM:\SYSTEM\CurrentControlSet\Control\TimeZoneInformation"
_POLICY = r"HKLM:\SOFTWARE\Policies\Microsoft\W32Time\Parameters"
#: Where the IANA name of the zone written is kept.
MARKER_KEY = r"HKLM:\SOFTWARE\napalm-windows"
#: w32time's modes that take time from the domain hierarchy.
_DOMAIN_TYPES = frozenset({"nt5ds", "allsync"})
# w32tm runs inside cmd.exe with its stderr merged: in a remote session a line on
# stderr would be an error record, and the whole reading would fail.
_PS_TIME_SYNC = rf"""
$ErrorActionPreference = 'Stop'
function V($path, $name) {{
$item = Get-ItemProperty -Path $path -Name $name -ErrorAction SilentlyContinue
if ($item) {{ [string]$item.$name }}
}}
$svc = Get-Service -Name W32Time -ErrorAction SilentlyContinue
$status = $null
if ($svc -and [string]$svc.Status -eq 'Running') {{
$status = @(cmd.exe /c 'w32tm /query /status 2>&1') -join "`n"
}}
[pscustomobject]@{{
type = V '{_W32TIME}' 'Type'
ntp_server = V '{_W32TIME}' 'NtpServer'
policy_type = V '{_POLICY}' 'Type'
policy_server = V '{_POLICY}' 'NtpServer'
service = if ($svc) {{ [string]$svc.Status }} else {{ $null }}
status = $status
zone = V '{_TZ_INFO}' 'TimeZoneKeyName'
dst_off = V '{_TZ_INFO}' 'DynamicDaylightTimeDisabled'
iana_zone = V '{MARKER_KEY}' 'IanaTimeZone'
}} | ConvertTo-Json -Compress
"""
_PS_SET_SERVERS = f"""
$ErrorActionPreference = 'Stop'
Set-ItemProperty -Path '{_W32TIME}' -Name NtpServer -Value {{peers}}
Set-ItemProperty -Path '{_W32TIME}' -Name Type -Value 'NTP'
if ([string](Get-Service -Name W32Time).Status -ne 'Running') {{{{ Start-Service -Name W32Time }}}}
$out = @(cmd.exe /c 'w32tm /config /update 2>&1')
if ($LASTEXITCODE -ne 0) {{{{ throw ('w32tm /config /update: ' + ($out -join ' ')) }}}}
"""
_PS_SET_ZONE = """
$ErrorActionPreference = 'Stop'
Set-TimeZone -Id {windows}
"""
_PS_MARK_ZONE = """
if (-not (Test-Path -Path '{key}')) {{ New-Item -Path '{key}' | Out-Null }}
Set-ItemProperty -Path '{key}' -Name IanaTimeZone -Value {zone}
"""
_LEAP = re.compile(r":\s*([0-3])\b")
def _servers(value: str | None) -> list[str]:
"""``NtpServer``'s names in order, without their ``,0xFLAGS``, each once."""
names: list[str] = []
for entry in (value or "").split():
name = entry.split(",", 1)[0].strip()
if name and name.lower() not in (n.lower() for n in names):
names.append(name)
return names
def _synchronized(service: str | None, status: str | None) -> bool | None:
"""The leap indicator, the first line of ``w32tm /query /status``: 3 is unsynchronised."""
if service is None:
return None
if service.lower() != "running":
return False
first = (status or "").strip().splitlines()[:1]
match = _LEAP.search(first[0]) if first else None
return None if match is None else match.group(1) != "3"
def _windows_zone(raw: dict[str, Any]) -> str:
"""``TimeZoneKeyName``, which older Windows pad with NULs."""
return str(raw.get("zone") or "").split("\x00", 1)[0].strip()
def _time_zone(raw: dict[str, Any]) -> str | None:
"""The host's zone as an IANA name: the one written while the host keeps its Windows
zone, else CLDR's; None for summer time switched off or a zone not in the table."""
windows, marker = _windows_zone(raw), str(raw.get("iana_zone") or "")
if not windows or str(raw.get("dst_off") or "0").strip() != "0":
return None
if marker and IANA_TO_WINDOWS.get(marker) == windows:
return marker
return iana_time_zone(windows)
class _Reading:
"""What the reading script said, with group policy applied."""
def __init__(self, raw: dict[str, Any]) -> None:
self.raw = raw
self.by_policy = bool(raw.get("policy_type") or raw.get("policy_server"))
self.type = str(raw.get("policy_type") or raw.get("type") or "").strip().lower()
self.servers = _servers(raw.get("policy_server") or raw.get("ntp_server"))
def time_sync(self) -> TimeSyncDict:
return {
"ntp_servers": [] if self.type == "nosync" else self.servers,
"timezone": _time_zone(self.raw),
"synchronized": _synchronized(self.raw.get("service"), self.raw.get("status")),
"daemon": "w32time",
}
class WindowsTimeSyncMixin(TimeSyncMixin):
"""w32time's servers and the time zone; the driver carries the scripts."""
time_sync_writes: ClassVar[frozenset[str]] = TIME_SYNC_VALUES
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def _ts_read(self) -> _Reading:
out = self._run_raw(_PS_TIME_SYNC).strip()
raw = json.loads(out) if out else None
if not isinstance(raw, dict):
raise ValueError("the time sync reading came back empty")
return _Reading(raw)
def get_time_sync(self) -> TimeSyncDict:
"""w32time's servers, whether it is synchronised, and the zone; one round trip.
:raises ValueError: when the reading came back empty.
"""
return self._ts_read().time_sync()
def _write_ntp_servers(self, servers: list[str]) -> FixStepOutcomeDict:
"""``w32tm /config`` with *servers* as manual peers; see the module."""
now = self._ts_read()
if now.by_policy:
return {
"ok": False,
"output": "the Windows Time settings come from group policy; "
"they are changed there, not on the host",
}
if now.type in _DOMAIN_TYPES:
return {
"ok": False,
"output": "the host takes its time from the domain hierarchy "
f"(w32time Type {now.raw.get('type')}); the domain sets its time sources",
}
if now.type == "ntp" and [s.lower() for s in now.servers] == [s.lower() for s in servers]:
return {"ok": True, "output": "w32time already has these servers"}
peers = " ".join(f"{server},0x8" for server in servers)
self._run_raw(_PS_SET_SERVERS.format(peers=_ps_quote(peers)))
return {"ok": True, "output": f"w32time set to {', '.join(servers)}"}
def _write_time_zone(self, zone: str) -> FixStepOutcomeDict:
"""``Set-TimeZone`` to *zone*'s Windows zone, and *zone* kept beside it; see the module."""
windows = windows_time_zone(zone)
if windows is None:
return {"ok": False, "output": f"there is no Windows time zone for {zone}"}
now = self._ts_read().raw
script = ""
if _windows_zone(now) != windows or str(now.get("dst_off") or "0").strip() != "0":
script += _PS_SET_ZONE.format(windows=_ps_quote(windows))
if script or now.get("iana_zone") != zone:
script += _PS_MARK_ZONE.format(key=MARKER_KEY, zone=_ps_quote(zone))
if not script:
return {"ok": True, "output": f"the host is in {zone} already"}
self._run_raw(script)
return {"ok": True, "output": f"time zone set to {windows} ({zone})"}
+31
View File
@@ -0,0 +1,31 @@
"""Windows time zone ids and IANA names, both ways.
Windows names its zones by their standard-time name (``W. Europe Standard Time``);
the contracts want an IANA name. The tables are CLDR's ``windowsZones.xml``,
generated into :mod:`napalm_windows._windows_zones` by ``tools/windows_zones.py``
and never fetched at runtime:
* reading, a Windows zone is the zone CLDR names for its territory ``001`` -- one
of several a Windows zone stands for (``W. Europe Standard Time`` is Berlin,
Vienna, Rome, ...). A zone not in the table is ``None``: the reading says it does
not know rather than guess;
* writing, every IANA name CLDR maps, and the tzdata links to and from them, has
its Windows zone.
"""
from __future__ import annotations
from napalm_windows._windows_zones import IANA_TO_WINDOWS, WINDOWS_TO_IANA
def iana_time_zone(windows_id: str | None) -> str | None:
"""The IANA name of the Windows zone *windows_id*; None for one the table lacks."""
return WINDOWS_TO_IANA.get(windows_id or "")
def windows_time_zone(iana: str | None) -> str | None:
"""The Windows zone that keeps the IANA zone *iana*; None for one Windows lacks."""
return IANA_TO_WINDOWS.get(iana or "")
__all__ = ["IANA_TO_WINDOWS", "WINDOWS_TO_IANA", "iana_time_zone", "windows_time_zone"]
+16
View File
@@ -104,6 +104,22 @@ class PsrpTransport:
raise PowerShellError(message or "PowerShell reported an error")
return "\n".join(str(o) for o in output if o is not None)
def run_last(self, script: str) -> bool:
"""Run a script after which the host may stop answering: a restart, a shutdown.
True when the script finished. False when the connection broke before the
answer came, which for such a script means the host went down first; the
transport is closed then. An error the script wrote still raises
:class:`PowerShellError`: the host answered, and refused.
"""
try:
self.run(script)
except (requests.RequestException, WinRMError, OSError) as exc:
logger.debug("Connection to %s broke during its last script: %s", self.host, exc)
self._drop()
return False
return True
def close(self) -> None:
if self._pool is not None:
try:
+47 -21
View File
@@ -26,6 +26,10 @@ from napalm.base.exceptions import ConnectionClosedException
from napalm_device_types import FingerprintRule, OSDriver, PortSpec
from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict, ServiceDict
from napalm_windows._powershell import _as_list, _ps_quote
from napalm_windows.host_basics import WindowsHostBasicsMixin
from napalm_windows.scheduled_tasks import WindowsScheduledJobsMixin
from napalm_windows.time_sync import WindowsTimeSyncMixin
from napalm_windows.transport import PowerShellError, PsrpTransport
logger = logging.getLogger(__name__)
@@ -178,13 +182,16 @@ _SERVICE_COMMANDS = {
"disable": "Set-Service -Name {name} -StartupType Disabled",
}
# The host's own restart and shutdown, without -Force: Windows asks running programs to
# close and refuses while other users are logged on, instead of throwing away what they
# have not saved. Both start the shutdown and return; WinRM goes later, with the services.
_PS_REBOOT = "Restart-Computer -Confirm:$false -ErrorAction Stop"
_PS_SHUTDOWN = "Stop-Computer -Confirm:$false -ErrorAction Stop"
# Service key names, not display names: letters, digits and the few symbols
# real services use (MSSQL$SQLEXPRESS, CDPUserSvc_4a5b6, {GUID}-style names).
_SERVICE_NAME_RE = re.compile(r"^[\w.$@{}\-]+$", re.ASCII)
# PowerShell accepts these as single-quote delimiters alongside the ASCII one.
_PS_SINGLE_QUOTES = ("'", "‘", "’", "‚", "‛")
_ROUTE_PROTOCOLS = {
"local": "connected",
"routeradvertisement": "connected",
@@ -204,22 +211,6 @@ _DEAD_NEIGHBOUR_STATES = {"unreachable", "incomplete"}
# ---------------------------------------------------------------------------
def _as_list(value: Any) -> list[Any]:
"""Undo ConvertTo-Json unwrapping a one-element array into a bare value."""
if value is None:
return []
if isinstance(value, list):
return value
return [value]
def _ps_quote(value: str) -> str:
"""Quote ``value`` as a PowerShell single-quoted (verbatim) string."""
for q in _PS_SINGLE_QUOTES:
value = value.replace(q, q + q)
return f"'{value}'"
def _mac(value: str | None) -> str:
"""``00-15-5d-01-02-03`` → ``00:15:5D:01:02:03``."""
if not value:
@@ -271,7 +262,9 @@ def _is_noise_route(destination: str) -> bool:
# ---------------------------------------------------------------------------
class WindowsDriver(OSDriver):
class WindowsDriver(
WindowsHostBasicsMixin, WindowsScheduledJobsMixin, WindowsTimeSyncMixin, OSDriver
):
"""NAPALM driver for Windows Server 2016+ and Windows 10/11.
``optional_args``:
@@ -369,6 +362,15 @@ class WindowsDriver(OSDriver):
raise ConnectionClosedException("WinRM connection is not open")
return self._transport.run(script)
def _run_power(self, script: str, what: str) -> None:
"""Send a restart or shutdown; the connection the host drops counts as accepted."""
if self._transport is None:
raise ConnectionClosedException("WinRM connection is not open")
try:
self._transport.run_last(script)
except PowerShellError as exc:
raise RuntimeError(f"The host refused to {what}: {exc}") from exc
# ------------------------------------------------------------------
# NAPALM getters
# ------------------------------------------------------------------
@@ -436,6 +438,8 @@ class WindowsDriver(OSDriver):
return result
def get_arp_table(self, vrf: str = "") -> list[dict[str, Any]]:
"""Get-NetNeighbor's IPv4 neighbours. It reports a state but no age, so
``age`` is ``-1.0`` (unknown, napalm-device-types' ``ARP_AGE_UNKNOWN``)."""
entries = []
for n in _as_list(self._run_ps(_PS_ARP)):
if (n.get("state") or "").lower() in _DEAD_NEIGHBOUR_STATES:
@@ -443,7 +447,7 @@ class WindowsDriver(OSDriver):
mac = _mac(n.get("mac"))
if not _is_real_neighbour_mac(mac):
continue
entries.append({"interface": n["interface"], "mac": mac, "ip": n["ip"], "age": 0.0})
entries.append({"interface": n["interface"], "mac": mac, "ip": n["ip"], "age": -1.0})
return entries
def get_route_to(
@@ -520,6 +524,28 @@ class WindowsDriver(OSDriver):
sockets.sort(key=lambda s: (s["proto"], s["port"], s["address"], s["interface"] or ""))
return {"attributed": True, "sockets": sockets}
def reboot_host(self) -> None:
"""Restart the host cleanly (``HostRebootMixin``) with ``Restart-Computer``.
Not forced: programs are asked to close, and Windows refuses while other users
are logged on, a disconnected session included. Returns once the restart is
under way; a connection the host drops before answering counts as that.
:raises RuntimeError: when the host refuses, with its answer.
"""
self._run_power(_PS_REBOOT, "restart")
def shutdown_host(self) -> None:
"""Shut the host down cleanly and power it off (``HostShutdownMixin``) with
``Stop-Computer``.
Not forced, as :meth:`reboot_host`. Returns once the shutdown is under way; a
connection the host drops before answering counts as that.
:raises RuntimeError: when the host refuses, with its answer.
"""
self._run_power(_PS_SHUTDOWN, "shut down")
def manage_service(self, name: str, action: str) -> dict[str, Any]:
template = _SERVICE_COMMANDS.get(action)
if template is None:
+5 -7
View File
@@ -7,7 +7,7 @@ name = "napalm-windows"
version = "0.2.0"
description = "NAPALM driver for Windows hosts via PowerShell Remoting (WinRM)"
readme = "README.md"
requires-python = ">=3.10"
requires-python = ">=3.12"
license = "Apache-2.0"
authors = [
{ name = "Christian Manivong", email = "christian@manivong.de" },
@@ -28,8 +28,6 @@ classifiers = [
"Intended Audience :: System Administrators",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Topic :: System :: Networking",
@@ -37,8 +35,8 @@ classifiers = [
"Typing :: Typed",
]
dependencies = [
"napalm>=4.0",
"napalm-device-types>=4.21.1",
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
"napalm-device-types>=4.35.0", # TimeSyncMixin
"pypsrp>=0.8",
]
@@ -67,7 +65,7 @@ napalm_windows = ["py.typed"]
[tool.ruff]
line-length = 100
target-version = "py310"
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
@@ -77,7 +75,7 @@ select = ["E", "F", "I", "UP", "B"]
"tests/**" = ["E501"]
[tool.mypy]
python_version = "3.10"
python_version = "3.12"
strict = true
# napalm itself is untyped, so every driver subclasses Any.
disallow_subclassing_any = false
+1
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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}]}
+100
View File
@@ -0,0 +1,100 @@
{
"time_zone": "W. Europe Standard Time",
"count": 5,
"tasks": [
{
"path": "\\Microsoft\\Windows\\Defrag\\",
"name": "ScheduledDefrag",
"state": "Ready",
"user": "SYSTEM",
"group": null,
"on_demand": true,
"description": "This task optimizes local storage drives.",
"actions": [
{"class": "MSFT_TaskExecAction", "execute": "%windir%\\system32\\defrag.exe", "arguments": "-c -h -o -$", "class_id": null}
],
"triggers": [
{"class": "MSFT_TaskWeeklyTrigger", "enabled": true, "start": "2026-01-01T01:00:00", "days_interval": null, "weeks_interval": 1, "days_of_week": 1, "interval": "", "duration": "", "delay": ""}
],
"last_run": "2026-11-01T00:00:12.0000000Z",
"last_result": 0,
"next_run": "2026-11-08T00:00:00.0000000Z"
},
{
"path": "\\Microsoft\\Windows\\UpdateOrchestrator\\",
"name": "Reboot",
"state": "Disabled",
"user": "SYSTEM",
"group": null,
"on_demand": true,
"description": null,
"actions": [
{"class": "MSFT_TaskExecAction", "execute": "%systemroot%\\system32\\MusNotification.exe", "arguments": "RebootDialog", "class_id": null}
],
"triggers": [
{"class": "MSFT_TaskTimeTrigger", "enabled": true, "start": "2026-11-04T03:00:00+01:00", "days_interval": null, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""}
],
"last_run": "1999-11-29T23:00:00.0000000Z",
"last_result": 267011,
"next_run": null
},
{
"path": "\\",
"name": "Admin's backup",
"state": "Ready",
"user": "Administrator",
"group": null,
"on_demand": true,
"description": "Copies D:\\data to the NAS",
"actions": [
{"class": "MSFT_TaskExecAction", "execute": "robocopy.exe", "arguments": "D:\\data \\\\nas\\backup /MIR", "class_id": null},
{"class": "MSFT_TaskExecAction", "execute": "C:\\scripts\\notify.cmd", "arguments": null, "class_id": null}
],
"triggers": [
{"class": "MSFT_TaskDailyTrigger", "enabled": true, "start": "2026-01-01T00:00:00", "days_interval": 1, "weeks_interval": null, "days_of_week": null, "interval": "PT1H", "duration": "P1D", "delay": ""},
{"class": "MSFT_TaskDailyTrigger", "enabled": false, "start": "2026-01-01T12:30:00", "days_interval": 2, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""}
],
"last_run": "/Date(1793854800000)/",
"last_result": 2147942402,
"next_run": "/Date(1793858400000)/"
},
{
"path": "\\",
"name": "nightly-dump",
"state": "Ready",
"user": "backup",
"group": null,
"on_demand": true,
"description": "napalm-scheduled-job: nightly-dump Dump the database\nschedule: 30 2 * * *",
"actions": [
{"class": "MSFT_TaskExecAction", "execute": "%SystemRoot%\\System32\\cmd.exe", "arguments": "/d /s /c \"pg_dump -f D:\\dump.sql app\"", "class_id": null}
],
"triggers": [
{"class": "MSFT_TaskTrigger", "enabled": true, "start": "2020-01-01T02:30:00", "days_interval": 1, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""}
],
"last_run": "2026-11-03T01:30:04.1234567Z",
"last_result": 1,
"next_run": "2026-11-04T01:30:00Z"
},
{
"path": "\\Vendor\\",
"name": "Updater",
"state": "Running",
"user": null,
"group": "Users",
"on_demand": false,
"description": "",
"actions": [
{"class": "MSFT_TaskComHandlerAction", "execute": null, "arguments": null, "class_id": "{A6BA00FE-40E8-477C-B713-C64A14F18ADB}"}
],
"triggers": [
{"class": "MSFT_TaskLogonTrigger", "enabled": true, "start": "", "days_interval": null, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": "PT15M"},
{"class": "MSFT_TaskBootTrigger", "enabled": null, "start": "", "days_interval": null, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""},
{"class": "MSFT_TaskSessionStateChangeTrigger", "enabled": true, "start": "", "days_interval": null, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""}
],
"last_run": "2026-11-03T06:00:00Z",
"last_result": 267009,
"next_run": null
}
]
}
+1
View File
@@ -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
View File
@@ -0,0 +1 @@
{"type":"NTP","ntp_server":"time.windows.com,0x9","policy_type":null,"policy_server":null,"service":"Running","status":"Leap Indicator: 0(no warning)\nStratum: 4 (secondary reference - syncd by (S)NTP)\nPrecision: -23 (119.209ns per tick)\nRoot Delay: 0.0312500s\nRoot Dispersion: 7.9876543s\nReferenceId: 0x14650039 (source IP: 20.101.57.9)\nLast Successful Sync Time: 11/11/2026 10:00:00 AM\nSource: time.windows.com,0x9\nPoll Interval: 10 (1024s)\n","zone":"W. Europe Standard Time","dst_off":"0","iana_zone":null}
+211
View File
@@ -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
+103
View File
@@ -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
+123
View File
@@ -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() == []
+125
View File
@@ -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()
+639
View File
@@ -0,0 +1,639 @@
"""Scheduled jobs on Windows: the Task Scheduler over PowerShell Remoting (#8).
The reading is one script whose JSON a fake transport answers from
tests/fixtures/synthetic/scheduled_tasks.json; every write is one script, read
here as text. What a real host does with those scripts the fixtures cannot
prove -- see the README there.
"""
from __future__ import annotations
import copy
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_device_types import (
ScheduledJobChanged,
ScheduledJobRefused,
ScheduledJobsMixin,
job_digest,
)
from napalm_windows import WindowsDriver, task_xml
from napalm_windows import scheduled_tasks as mod
from napalm_windows.time_zones import iana_time_zone
from napalm_windows.transport import PowerShellError
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "scheduled_tasks.json"
DEFRAG = "task:\\Microsoft\\Windows\\Defrag\\ScheduledDefrag"
REBOOT = "task:\\Microsoft\\Windows\\UpdateOrchestrator\\Reboot"
BACKUP = "task:\\Admin's backup"
DUMP = "task:\\nightly-dump"
UPDATER = "task:\\Vendor\\Updater"
def _reading() -> dict[str, Any]:
return json.loads(FIXTURE.read_text())
class FakeTransport:
"""Answers the reading script with *reading*; records every other script."""
def __init__(self, reading: Any, fail: str | None = None):
self.reading = reading
self.fail = fail
self.sent: list[str] = []
self.is_open = True
def run(self, script: str) -> str:
self.sent.append(script)
if script == mod._PS_SCHEDULED_TASKS:
return self.reading if isinstance(self.reading, str) else json.dumps(self.reading)
if self.fail:
raise PowerShellError(self.fail)
return ""
def close(self) -> None:
self.is_open = False
@property
def writes(self) -> list[str]:
return [s for s in self.sent if s != mod._PS_SCHEDULED_TASKS]
def _driver(reading: Any = None, fail: str | None = None) -> WindowsDriver:
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(_reading() if reading is None else reading, fail) # type: ignore[assignment]
return d
def _jobs(reading: Any = None) -> dict[str, dict[str, Any]]:
return {j["key"]: dict(j) for j in _driver(reading).get_scheduled_jobs()["jobs"]}
def _digest(key: str, reading: Any = None) -> str:
return str(_jobs(reading)[key]["digest"])
def _spec(**changes: Any) -> dict[str, Any]:
spec = {
"name": "nightly-dump",
"schedule": "30 2 * * *",
"run_as": "backup",
"command": "pg_dump -f D:\\dump.sql app",
"enabled": True,
"description": "Dump the database",
}
spec.update(changes)
return spec
def _without_dump() -> dict[str, Any]:
reading = _reading()
reading["tasks"] = [t for t in reading["tasks"] if t["name"] != "nightly-dump"]
reading["count"] = len(reading["tasks"])
return reading
# ---------------------------------------------------------------------------
# The contract
# ---------------------------------------------------------------------------
def test_a_windows_host_offers_every_verb():
assert issubclass(WindowsDriver, ScheduledJobsMixin)
for verb in (
"get_scheduled_jobs",
"manage_scheduled_job",
"put_scheduled_job",
"delete_scheduled_job",
):
assert callable(getattr(WindowsDriver, verb))
# ---------------------------------------------------------------------------
# Reading
# ---------------------------------------------------------------------------
class TestReading:
def test_every_task_in_one_round_trip(self):
d = _driver()
reading = d.get_scheduled_jobs()
assert len(reading["jobs"]) == 5
assert d._transport.sent == [mod._PS_SCHEDULED_TASKS]
def test_the_script_joins_the_task_and_its_run_info_and_changes_nothing(self):
script = mod._PS_SCHEDULED_TASKS
assert "Get-ScheduledTask" in script
assert "Get-ScheduledTaskInfo" in script
assert "ConvertTo-Json" in script
for verb in ("Set-", "Register-", "Unregister-", "Enable-", "Disable-", "Start-"):
assert verb not in script
def test_a_platform_task(self):
job = _jobs()[DEFRAG]
assert {k: job[k] for k in job if k != "digest"} == {
"key": DEFRAG,
"kind": "task",
"source": "\\Microsoft\\Windows\\Defrag\\ScheduledDefrag",
"run_as": "SYSTEM",
"schedule": "weekly on Sun at 01:00",
"schedule_kind": "triggers",
"command": "%windir%\\system32\\defrag.exe -c -h -o -$",
"enabled": True,
"managed_by": "platform",
"actions": ["enable", "disable", "run"],
"description": "This task optimizes local storage drives.",
"last_run": "2026-11-01T00:00:12+00:00",
"last_result": "success",
"next_run": "2026-11-08T00:00:00+00:00",
}
def test_the_digest_is_the_contracts(self):
job = _jobs()[DEFRAG]
assert job["digest"] == job_digest(job)
def test_a_disabled_task_is_not_enabled_and_cannot_be_run(self):
job = _jobs()[REBOOT]
assert job["enabled"] is False
assert job["actions"] == ["enable", "disable"]
def test_a_task_that_never_ran_has_no_last_run_or_result(self):
"""Task Scheduler says 30 November 1999 for never, and 0x41303 for its result."""
job = _jobs()[REBOOT]
assert (job["last_run"], job["last_result"], job["next_run"]) == (None, None, None)
def test_a_task_without_a_description_has_none(self):
assert "description" not in _jobs()[REBOOT]
def test_a_once_trigger_keeps_its_offset(self):
assert _jobs()[REBOOT]["schedule"] == "once at 2026-11-04 03:00+01:00"
def test_an_admins_task_with_two_actions_and_two_triggers(self):
job = _jobs()[BACKUP]
assert job["managed_by"] == "admin"
assert job["run_as"] == "Administrator"
assert (
job["command"] == "robocopy.exe D:\\data \\\\nas\\backup /MIR\nC:\\scripts\\notify.cmd"
)
assert job["schedule"] == (
"daily at 00:00, every 1 hour for 1 day; every 2 days at 12:30 (disabled)"
)
assert job["actions"] == ["enable", "disable", "run"]
def test_json_dates_are_iso_utc(self):
job = _jobs()[BACKUP]
assert job["last_run"] == "2026-11-05T05:00:00+00:00"
assert job["next_run"] == "2026-11-05T06:00:00+00:00"
def test_a_failure_code_is_hex(self):
assert _jobs()[BACKUP]["last_result"] == "0x80070002"
def test_an_applications_task(self):
job = _jobs()[DUMP]
assert job["managed_by"] == "application"
assert job["name"] == "nightly-dump"
assert job["description"] == "Dump the database"
assert (job["schedule"], job["schedule_kind"]) == ("30 2 * * *", "cron")
assert job["command"] == "pg_dump -f D:\\dump.sql app"
assert job["run_as"] == "backup"
assert job["actions"] == ["enable", "disable", "run", "edit", "delete"]
assert job["last_result"] == "0x1"
assert job["last_run"] == "2026-11-03T01:30:04.123456+00:00"
def test_an_applications_digest_covers_its_triggers(self):
"""Triggers changed by hand change the digest, although the cron line stays."""
changed = _reading()
changed["tasks"][3]["triggers"][0]["start"] = "2020-01-01T03:30:00"
assert _digest(DUMP, changed) != _digest(DUMP)
assert _jobs(changed)[DUMP]["schedule"] == "30 2 * * *"
def test_an_application_task_without_its_schedule_line_shows_its_triggers(self):
reading = _reading()
reading["tasks"][3]["description"] = "napalm-scheduled-job: nightly-dump"
job = _jobs(reading)[DUMP]
assert (job["managed_by"], job["name"]) == ("application", "nightly-dump")
assert "description" not in job
assert (job["schedule"], job["schedule_kind"]) == ("trigger at 02:30", "triggers")
def test_an_application_task_whose_action_was_changed_shows_it(self):
reading = _reading()
reading["tasks"][3]["actions"][0]["arguments"] = "/c whoami"
assert _jobs(reading)[DUMP]["command"] == "%SystemRoot%\\System32\\cmd.exe /c whoami"
@pytest.mark.parametrize(
("path", "name"),
[("\\Vendor\\", "nightly-dump"), ("\\", "other-name"), ("\\", "Nightly Dump")],
)
def test_the_marker_counts_only_on_the_root_task_of_that_name(self, path, name):
reading = _reading()
reading["tasks"][3].update(path=path, name=name)
job = _jobs(reading)[f"task:{path}{name}"]
assert job["managed_by"] == "admin"
assert "edit" not in job["actions"]
assert "name" not in job
def test_a_group_principal_a_com_handler_and_event_triggers(self):
job = _jobs()[UPDATER]
assert job["run_as"] == "Users"
assert job["command"] == "COM handler {A6BA00FE-40E8-477C-B713-C64A14F18ADB}"
assert job["schedule"] == "at logon after 15 minutes; at startup; session state change"
assert job["enabled"] is True
assert job["last_result"] == "running"
def test_a_task_that_cannot_be_started_on_demand_does_not_offer_run(self):
assert _jobs()[UPDATER]["actions"] == ["enable", "disable"]
def test_the_time_zone_is_iana(self):
assert _driver().get_scheduled_jobs()["time_zone"] == "Europe/Berlin"
def test_an_unknown_time_zone_is_none(self):
reading = _reading()
reading["time_zone"] = "Mars Standard Time"
assert _driver(reading).get_scheduled_jobs()["time_zone"] is None
def test_one_task_arrives_as_a_bare_object(self):
"""ConvertTo-Json unwraps a one-element array, nested ones too."""
task = _reading()["tasks"][2]
task["actions"] = task["actions"][0]
task["triggers"] = task["triggers"][0]
reading = {"time_zone": "UTC", "count": 1, "tasks": task}
(job,) = _driver(reading).get_scheduled_jobs()["jobs"]
assert job["key"] == BACKUP
assert job["command"] == "robocopy.exe D:\\data \\\\nas\\backup /MIR"
assert job["schedule"] == "daily at 00:00, every 1 hour for 1 day"
def test_a_host_without_tasks(self):
reading = {"time_zone": None, "count": 0, "tasks": None}
assert _driver(reading).get_scheduled_jobs() == {"jobs": [], "time_zone": None}
def test_a_reading_cut_short_raises(self):
with pytest.raises(ValueError):
_driver(json.dumps(_reading())[:-40]).get_scheduled_jobs()
def test_a_reading_with_fewer_tasks_than_counted_raises(self):
reading = _reading()
reading["count"] = 6
with pytest.raises(ValueError, match="6"):
_driver(reading).get_scheduled_jobs()
def test_an_empty_answer_raises(self):
with pytest.raises(ValueError):
_driver("").get_scheduled_jobs()
def test_a_failed_reading_raises(self):
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(_reading()) # type: ignore[assignment]
d._transport.reading = None
d._transport.run = lambda script: (_ for _ in ()).throw(PowerShellError("Access denied")) # type: ignore[method-assign]
with pytest.raises(PowerShellError):
d.get_scheduled_jobs()
class TestOddTasks:
def _job(self, **changes: Any) -> dict[str, Any]:
task = _reading()["tasks"][0]
task.update(changes)
return _jobs({"time_zone": None, "count": 1, "tasks": [task]})[DEFRAG]
def test_an_action_without_a_command_or_handler_names_its_class(self):
job = self._job(actions=[{"class": "MSFT_TaskSendEmailAction"}])
assert job["command"] == "MSFT_TaskSendEmailAction"
def test_a_start_and_delay_it_cannot_read_are_kept_as_they_are(self):
trigger = {"class": "MSFT_TaskDailyTrigger", "start": "soon", "delay": "a while"}
assert self._job(triggers=[trigger])["schedule"] == "daily at soon after a while"
def test_a_task_that_never_ran_since_it_was_read_has_no_result(self):
job = self._job(last_result=267011)
assert job["last_run"] is not None
assert job["last_result"] is None
def test_a_negative_result_is_the_same_code(self):
assert self._job(last_result=-2147024894)["last_result"] == "0x80070002"
def test_a_reading_that_is_not_an_object_raises(self):
with pytest.raises(ValueError, match="reading"):
_driver("[]").get_scheduled_jobs()
class TestTimestamps:
@pytest.mark.parametrize(
("value", "iso"),
[
(None, None),
("", None),
("2026-11-03T01:30:00Z", "2026-11-03T01:30:00+00:00"),
("2026-11-03T02:30:00+01:00", "2026-11-03T01:30:00+00:00"),
("2026-11-03T01:30:00", "2026-11-03T01:30:00+00:00"),
("/Date(1793854800000)/", "2026-11-05T05:00:00+00:00"),
("/Date(1793854800000+0100)/", "2026-11-05T05:00:00+00:00"),
(1793854800, "2026-11-05T05:00:00+00:00"),
("1999-11-30T00:00:00", None),
("/Date(943916400000)/", None),
("not a date", None),
],
)
def test_to_iso_utc(self, value, iso):
assert mod._timestamp(value) == iso
class TestTimeZones:
@pytest.mark.parametrize(
("windows", "iana"),
[
("W. Europe Standard Time", "Europe/Berlin"),
("GMT Standard Time", "Europe/London"),
("Eastern Standard Time", "America/New_York"),
("UTC", "Etc/UTC"),
("Tokyo Standard Time", "Asia/Tokyo"),
("Mars Standard Time", None),
(None, None),
],
)
def test_a_windows_zone_id_as_iana(self, windows, iana):
assert iana_time_zone(windows) == iana
def test_every_name_in_the_table_is_a_real_zone(self):
from zoneinfo import ZoneInfo
from napalm_windows.time_zones import WINDOWS_TO_IANA
for name in WINDOWS_TO_IANA.values():
ZoneInfo(name)
# ---------------------------------------------------------------------------
# Enable, disable, run
# ---------------------------------------------------------------------------
class TestManage:
@pytest.mark.parametrize(
("action", "cmdlet"),
[("enable", "Enable-ScheduledTask"), ("disable", "Disable-ScheduledTask")],
)
def test_switches_the_tasks_own_flag(self, action, cmdlet):
d = _driver()
result = d.manage_scheduled_job(DEFRAG, action, digest=_digest(DEFRAG))
(script,) = d._transport.writes
assert cmdlet in script
assert "'\\Microsoft\\Windows\\Defrag\\'" in script
assert "'ScheduledDefrag'" in script
assert result == {"success": True, "output": f"{DEFRAG} {action}d"}
def test_run_says_the_task_was_started_not_that_it_finished(self):
d = _driver()
result = d.manage_scheduled_job(DEFRAG, "run", digest=_digest(DEFRAG))
(script,) = d._transport.writes
assert "Start-ScheduledTask" in script
assert result["success"] is True
assert "started" in result["output"]
assert "next reading" in result["output"]
def test_reads_again_before_it_writes(self):
d = _driver()
d.manage_scheduled_job(DEFRAG, "disable", digest=_digest(DEFRAG))
assert d._transport.sent[0] == mod._PS_SCHEDULED_TASKS
def test_the_task_is_found_by_exact_path_and_name(self):
"""Not by -TaskName, which takes wildcards."""
d = _driver()
d.manage_scheduled_job(DEFRAG, "disable", digest=_digest(DEFRAG))
script = d._transport.writes[0]
assert "-eq '\\Microsoft\\Windows\\Defrag\\'" in script
assert "-eq 'ScheduledDefrag'" in script
assert "-TaskName" not in script
def test_a_quote_in_a_task_name_is_doubled(self):
d = _driver()
d.manage_scheduled_job(BACKUP, "disable", digest=_digest(BACKUP))
assert "'Admin''s backup'" in d._transport.writes[0]
def test_a_changed_task_is_not_switched(self):
d = _driver()
with pytest.raises(ScheduledJobChanged):
d.manage_scheduled_job(DEFRAG, "disable", digest="0" * 16)
assert d._transport.writes == []
def test_an_unknown_task_raises_lookup_error(self):
with pytest.raises(LookupError):
_driver().manage_scheduled_job("task:\\nope", "run", digest="0" * 16)
def test_an_unknown_action_is_refused_before_anything_is_sent(self):
d = _driver()
with pytest.raises(ScheduledJobRefused, match="action"):
d.manage_scheduled_job(DEFRAG, "delete", digest=_digest(DEFRAG))
assert d._transport.writes == []
def test_a_disabled_task_is_not_run(self):
d = _driver()
with pytest.raises(ScheduledJobRefused, match="run"):
d.manage_scheduled_job(REBOOT, "run", digest=_digest(REBOOT))
assert d._transport.writes == []
def test_what_powershell_says_is_the_result(self):
d = _driver(fail="Access is denied.")
result = d.manage_scheduled_job(DEFRAG, "disable", digest=_digest(DEFRAG))
assert result == {"success": False, "output": "Access is denied."}
# ---------------------------------------------------------------------------
# An application's own task
# ---------------------------------------------------------------------------
class TestPut:
def test_creates_the_task_in_the_root_folder_from_xml(self):
d = _driver(_without_dump())
result = d.put_scheduled_job(_spec()) # type: ignore[arg-type]
(script,) = d._transport.writes
assert "Register-ScheduledTask -TaskPath '\\' -TaskName 'nightly-dump' -Xml '" in script
assert "-Force" in script
assert result == {"success": True, "output": f"{DUMP} created"}
def test_the_xml_carries_the_definition(self):
d = _driver(_without_dump())
d.put_scheduled_job(_spec()) # type: ignore[arg-type]
script = d._transport.writes[0]
assert task_xml.task_xml(_spec()).replace("'", "''") in script # type: ignore[arg-type]
def test_a_task_of_that_name_there_already(self):
d = _driver()
with pytest.raises(ScheduledJobChanged, match="already"):
d.put_scheduled_job(_spec()) # type: ignore[arg-type]
assert d._transport.writes == []
def test_an_admins_root_task_of_that_name_is_not_overwritten(self):
reading = _reading()
reading["tasks"][3]["description"] = "mine"
d = _driver(reading)
with pytest.raises(ScheduledJobChanged, match="already"):
d.put_scheduled_job(_spec()) # type: ignore[arg-type]
with pytest.raises(ScheduledJobRefused, match="application"):
d.put_scheduled_job(_spec(), digest=_digest(DUMP, reading)) # type: ignore[arg-type]
assert d._transport.writes == []
def test_changes_its_own_task_with_the_digest_it_saw(self):
d = _driver()
result = d.put_scheduled_job(_spec(schedule="*/5 * * * *"), digest=_digest(DUMP)) # type: ignore[arg-type]
assert "Register-ScheduledTask" in d._transport.writes[0]
assert "<Interval>PT5M</Interval>" in d._transport.writes[0]
assert result == {"success": True, "output": f"{DUMP} changed"}
def test_a_changed_task_is_not_overwritten(self):
d = _driver()
with pytest.raises(ScheduledJobChanged):
d.put_scheduled_job(_spec(), digest="0" * 16) # type: ignore[arg-type]
assert d._transport.writes == []
def test_a_task_that_went_away_is_not_changed(self):
d = _driver(_without_dump())
with pytest.raises(LookupError):
d.put_scheduled_job(_spec(), digest="0" * 16) # type: ignore[arg-type]
def test_a_spec_the_contract_refuses_is_refused_before_anything_is_sent(self):
d = _driver()
with pytest.raises(ScheduledJobRefused, match="name"):
d.put_scheduled_job(_spec(name="Nightly Dump")) # type: ignore[arg-type]
assert d._transport.sent == []
def test_a_schedule_task_scheduler_cannot_take_is_refused_before_anything_is_sent(self):
d = _driver(_without_dump())
with pytest.raises(ScheduledJobRefused, match="weekday"):
d.put_scheduled_job(_spec(schedule="0 0 1 * 1")) # type: ignore[arg-type]
assert d._transport.sent == []
def test_quotes_in_the_command_are_doubled_for_powershell(self):
d = _driver(_without_dump())
d.put_scheduled_job(_spec(command="echo it's done’")) # type: ignore[arg-type]
script = d._transport.writes[0]
assert "echo it''s done’’" in script
body = script.split("-Xml '", 1)[1].rsplit("' -Force", 1)[0]
for quote in ("'", "‘", "’", "‚", "‛"):
assert quote not in body.replace(quote * 2, "")
def test_what_powershell_says_is_the_result(self):
d = _driver(_without_dump(), fail="The user name or password is incorrect.")
result = d.put_scheduled_job(_spec()) # type: ignore[arg-type]
assert result == {"success": False, "output": "The user name or password is incorrect."}
class TestDelete:
def test_unregisters_its_own_task(self):
d = _driver()
result = d.delete_scheduled_job(DUMP, digest=_digest(DUMP))
(script,) = d._transport.writes
assert (
"Unregister-ScheduledTask -TaskPath '\\' -TaskName 'nightly-dump' -Confirm:$false"
in script
)
assert result == {"success": True, "output": f"{DUMP} deleted"}
@pytest.mark.parametrize("key", [DEFRAG, BACKUP])
def test_a_task_an_application_did_not_write_is_refused(self, key):
d = _driver()
with pytest.raises(ScheduledJobRefused, match="application"):
d.delete_scheduled_job(key, digest=_digest(key))
assert d._transport.writes == []
def test_a_changed_task_is_not_deleted(self):
d = _driver()
with pytest.raises(ScheduledJobChanged):
d.delete_scheduled_job(DUMP, digest="0" * 16)
assert d._transport.writes == []
def test_an_unknown_task_raises_lookup_error(self):
with pytest.raises(LookupError):
_driver().delete_scheduled_job("task:\\nope", digest="0" * 16)
def test_what_powershell_says_is_the_result(self):
d = _driver(fail="Access is denied.")
result = d.delete_scheduled_job(DUMP, digest=_digest(DUMP))
assert result == {"success": False, "output": "Access is denied."}
def test_a_written_task_reads_back_as_the_spec():
"""What put writes, the reading parses back to the same cron line and command."""
spec = _spec(command='"C:\\Program Files\\app\\run.exe" --quiet & echo done')
xml = task_xml.task_xml(spec) # type: ignore[arg-type]
execute, arguments = task_xml.command_action(spec["command"])
reading = _reading()
task = copy.deepcopy(reading["tasks"][3])
task["actions"] = [{"class": "MSFT_TaskExecAction", "execute": execute, "arguments": arguments}]
task["description"] = task_xml.description(spec) # type: ignore[arg-type]
reading["tasks"][3] = task
job = _jobs(reading)[DUMP]
assert (job["command"], job["schedule"], job["description"]) == (
spec["command"],
spec["schedule"],
spec["description"],
)
assert f"<Command>{execute}</Command>" in xml
+93
View File
@@ -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()
+260
View File
@@ -0,0 +1,260 @@
"""An application's task as Task Scheduler XML, and a cron expression as its triggers (#8).
A cron shape Task Scheduler can express exactly becomes triggers; every other
shape is refused, naming why.
"""
from __future__ import annotations
import xml.etree.ElementTree as ET # noqa: S405 - parses only what the tests built
from typing import Any
import pytest
from napalm_device_types import ScheduledJobRefused
from napalm_windows import task_xml
NS = {"t": "http://schemas.microsoft.com/windows/2004/02/mit/task"}
def _spec(**changes: Any) -> Any:
spec = {
"name": "nightly-dump",
"schedule": "30 2 * * *",
"run_as": "backup",
"command": "pg_dump -f D:\\dump.sql app",
"enabled": True,
"description": "Dump the database",
}
spec.update(changes)
return spec
def _task(**changes: Any) -> ET.Element:
return ET.fromstring(task_xml.task_xml(_spec(**changes))) # noqa: S314
def _text(task: ET.Element, path: str) -> str | None:
found = task.find(path, NS)
return None if found is None else found.text
def _triggers(schedule: str) -> list[dict[str, Any]]:
"""Each trigger as start, repetition and day schedule, for comparing."""
triggers = []
found = _task(schedule=schedule).find("t:Triggers", NS)
assert found is not None
for trigger in found:
tag = trigger.tag.split("}")[1]
entry: dict[str, Any] = {"type": tag}
if tag == "CalendarTrigger":
entry["start"] = _text(trigger, "t:StartBoundary")
entry["repeat"] = (
_text(trigger, "t:Repetition/t:Interval"),
_text(trigger, "t:Repetition/t:Duration"),
)
schedule_by = next(c for c in trigger if c.tag.split("}")[1].startswith("Schedule"))
entry["by"] = schedule_by.tag.split("}")[1]
entry["days"] = [d.text for d in schedule_by.iter(f"{{{NS['t']}}}Day")]
entry["names"] = [
c.tag.split("}")[1]
for part in ("DaysOfWeek", "Months")
for parent in schedule_by.iter(f"{{{NS['t']}}}{part}")
for c in parent
]
triggers.append(entry)
return triggers
class TestTriggers:
def test_daily_at_one_time(self):
assert _triggers("30 2 * * *") == [
{
"type": "CalendarTrigger",
"start": "2020-01-01T02:30:00",
"repeat": (None, None),
"by": "ScheduleByDay",
"days": [],
"names": [],
}
]
def test_the_daily_alias(self):
assert [t["start"] for t in _triggers("@daily")] == ["2020-01-01T00:00:00"]
def test_weekdays_at_two_times_are_two_weekly_triggers(self):
triggers = _triggers("0 8,17 * * 1-5")
assert [t["start"] for t in triggers] == ["2020-01-01T08:00:00", "2020-01-01T17:00:00"]
assert {t["by"] for t in triggers} == {"ScheduleByWeek"}
assert triggers[0]["names"] == ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
def test_sunday_is_0_and_7(self):
assert _triggers("0 0 * * 0")[0]["names"] == _triggers("0 0 * * 7")[0]["names"]
assert _triggers("0 0 * * 7")[0]["names"] == ["Sunday"]
def test_every_five_minutes_is_one_repetition(self):
assert _triggers("*/5 * * * *") == [
{
"type": "CalendarTrigger",
"start": "2020-01-01T00:00:00",
"repeat": ("PT5M", "PT23H56M"),
"by": "ScheduleByDay",
"days": [],
"names": [],
}
]
def test_every_quarter_hour_in_working_hours(self):
(trigger,) = _triggers("*/15 8-17 * * 1-5")
assert (trigger["start"], trigger["repeat"]) == (
"2020-01-01T08:00:00",
("PT15M", "PT9H46M"),
)
assert trigger["by"] == "ScheduleByWeek"
def test_every_six_hours(self):
(trigger,) = _triggers("0 */6 * * *")
assert trigger["repeat"] == ("PT6H", "PT18H1M")
def test_every_minute(self):
(trigger,) = _triggers("* * * * *")
assert (trigger["start"], trigger["repeat"]) == ("2020-01-01T00:00:00", ("PT1M", "PT24H"))
def test_a_step_that_does_not_divide_the_hour_repeats_within_each_hour(self):
"""*/7 fires at :56 and then at :00 -- four minutes, not seven: one repetition per hour."""
triggers = _triggers("*/7 * * * *")
assert len(triggers) == 24
assert triggers[1]["start"] == "2020-01-01T01:00:00"
assert {t["repeat"] for t in triggers} == {("PT7M", "PT57M")}
def test_two_hours_of_every_other_minute(self):
triggers = _triggers("*/2 8,17 * * *")
assert [(t["start"], t["repeat"]) for t in triggers] == [
("2020-01-01T08:00:00", ("PT2M", "PT59M")),
("2020-01-01T17:00:00", ("PT2M", "PT59M")),
]
def test_days_of_the_month(self):
(trigger,) = _triggers("0 3 1,15 * *")
assert (trigger["by"], trigger["days"]) == ("ScheduleByMonth", ["1", "15"])
assert len(trigger["names"]) == 12
def test_some_months_only(self):
(trigger,) = _triggers("0 0 * 1,jul *")
assert trigger["by"] == "ScheduleByMonth"
assert trigger["days"] == [str(d) for d in range(1, 32)]
assert trigger["names"] == ["January", "July"]
def test_reboot_is_a_boot_trigger(self):
assert _triggers("@reboot") == [{"type": "BootTrigger"}]
@pytest.mark.parametrize(
("schedule", "why"),
[
("0 0 1 * 1", "either"),
("0 0 */2 * 1", "weekday"),
("0 0 * 1 1", "weekday"),
("0,1,5 * * * *", "48"),
],
)
def test_a_shape_task_scheduler_cannot_take_is_refused(self, schedule, why):
with pytest.raises(ScheduledJobRefused, match=why):
task_xml.task_xml(_spec(schedule=schedule))
def test_an_expression_cron_would_not_take_is_refused(self):
with pytest.raises(ScheduledJobRefused, match="range"):
task_xml.triggers("61 * * * *")
def test_at_most_48_triggers(self):
assert len(_triggers("0,30 0-23 * * *")) == 1 # one repetition
assert len(_triggers("0,20 0-11,13-23 * * *")) == 46
with pytest.raises(ScheduledJobRefused, match="48"):
task_xml.task_xml(_spec(schedule="0,20,30 0-11,13-23 * * *"))
class TestTask:
def test_the_description_names_the_job_and_keeps_its_cron_line(self):
assert _text(_task(), "t:RegistrationInfo/t:Description") == (
"napalm-scheduled-job: nightly-dump Dump the database\nschedule: 30 2 * * *"
)
def test_a_job_without_a_description(self):
assert task_xml.description(_spec(description="")) == (
"napalm-scheduled-job: nightly-dump\nschedule: 30 2 * * *"
)
def test_the_command_runs_in_cmd(self):
task = _task(command='"C:\\Program Files\\app.exe" -x & echo <done>')
assert _text(task, "t:Actions/t:Exec/t:Command") == "%SystemRoot%\\System32\\cmd.exe"
assert _text(task, "t:Actions/t:Exec/t:Arguments") == (
'/d /s /c ""C:\\Program Files\\app.exe" -x & echo <done>"'
)
def test_the_xml_is_escaped(self):
raw = task_xml.task_xml(_spec(command="a & b < c", description="x > y & z"))
assert "a &amp; b &lt; c" in raw
assert "x &gt; y &amp; z" in raw
def test_a_user_runs_without_a_stored_password(self):
task = _task(run_as="backup")
assert _text(task, "t:Principals/t:Principal/t:UserId") == "backup"
assert _text(task, "t:Principals/t:Principal/t:LogonType") == "S4U"
assert _text(task, "t:Principals/t:Principal/t:RunLevel") == "LeastPrivilege"
@pytest.mark.parametrize("run_as", ["SYSTEM", "system"])
def test_system_is_the_local_system_account(self, run_as):
task = _task(run_as=run_as)
assert _text(task, "t:Principals/t:Principal/t:UserId") == "S-1-5-18"
assert _text(task, "t:Principals/t:Principal/t:LogonType") is None
assert _text(task, "t:Principals/t:Principal/t:RunLevel") == "HighestAvailable"
@pytest.mark.parametrize("enabled", [True, False])
def test_enabled_is_the_tasks_flag(self, enabled):
assert _text(_task(enabled=enabled), "t:Settings/t:Enabled") == str(enabled).lower()
def test_runs_like_cron_on_battery_and_without_catching_up(self):
task = _task()
assert _text(task, "t:Settings/t:DisallowStartIfOnBatteries") == "false"
assert _text(task, "t:Settings/t:StopIfGoingOnBatteries") == "false"
assert _text(task, "t:Settings/t:StartWhenAvailable") == "false"
assert _text(task, "t:Settings/t:MultipleInstancesPolicy") == "IgnoreNew"
def test_a_command_is_one_line(self):
with pytest.raises(ScheduledJobRefused, match="one line"):
task_xml.task_xml(_spec(command="echo a\necho b"))
def test_a_control_character_is_refused(self):
with pytest.raises(ScheduledJobRefused, match="control"):
task_xml.task_xml(_spec(command="echo \x07"))
def test_trailing_whitespace_of_the_command_is_dropped(self):
assert task_xml.command_action("echo hi\n") == (
"%SystemRoot%\\System32\\cmd.exe",
'/d /s /c "echo hi"',
)
@pytest.mark.parametrize(
("execute", "arguments", "command"),
[
("%SystemRoot%\\System32\\cmd.exe", '/d /s /c "echo hi"', "echo hi"),
("%systemroot%\\system32\\CMD.EXE", '/d /s /c "echo hi"', "echo hi"),
("%SystemRoot%\\System32\\cmd.exe", "/c echo hi", None),
("powershell.exe", '/d /s /c "echo hi"', None),
("%SystemRoot%\\System32\\cmd.exe", None, None),
],
)
def test_the_command_back_from_the_action(self, execute, arguments, command):
assert task_xml.own_command(execute, arguments) == command
+289
View File
@@ -0,0 +1,289 @@
"""Time sync on Windows: w32time and the time zone over PowerShell Remoting (NetOrk/netork#2367).
The reading is one script whose JSON a fake host answers, starting from
tests/fixtures/synthetic/time_sync.json (a workgroup host as Windows installs it:
``time.windows.com,0x9``, Type NTP). The fake host applies what the write scripts
say, so ``verify`` reads back what a host would. The status text is
``w32tm /query /status`` as Windows prints it, in English and in German.
"""
from __future__ import annotations
import json
import re
from pathlib import Path
from typing import Any
import pytest
from napalm_device_types import TimeSyncMixin
from napalm_windows import WindowsDriver
from napalm_windows import time_sync as mod
from napalm_windows.time_zones import IANA_TO_WINDOWS, WINDOWS_TO_IANA, windows_time_zone
from napalm_windows.transport import PowerShellError
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "time_sync.json"
UNSYNCED = (
"Leap Indicator: 3(not synchronized)\nStratum: 0 (unspecified)\n"
"Precision: -23 (119.209ns per tick)\nSource: Local CMOS Clock\n"
)
GERMAN = "Sprungindikator: 0(keine Warnung)\nStratum: 3 (Sekundärreferenz - synchr. über (S)NTP)\n"
NOT_STARTED = "Folgender Fehler ist aufgetreten: Der Dienst wurde nicht gestartet. (0x80070426)\n"
class FakeHost:
"""Answers the reading from *state*; applies the write scripts to it."""
def __init__(self, **changes: Any) -> None:
self.state: dict[str, Any] = {**json.loads(FIXTURE.read_text()), **changes}
self.sent: list[str] = []
self.fail: str | None = None
self.is_open = True
def run(self, script: str) -> str:
self.sent.append(script)
if script == mod._PS_TIME_SYNC:
return json.dumps(self.state)
if self.fail:
raise PowerShellError(self.fail)
peers = re.search(r"-Name NtpServer -Value '([^']*)'", script)
if peers and "-Name Type -Value 'NTP'" in script and "w32tm /config /update" in script:
self.state.update(type="NTP", ntp_server=peers.group(1), service="Running")
zone = re.search(r"Set-TimeZone -Id '([^']*)'", script)
if zone:
self.state.update(zone=zone.group(1), dst_off="0")
marker = re.search(r"-Name IanaTimeZone -Value '([^']*)'", script)
if marker:
self.state["iana_zone"] = marker.group(1)
return ""
def close(self) -> None:
self.is_open = False
@property
def writes(self) -> list[str]:
return [s for s in self.sent if s != mod._PS_TIME_SYNC]
def _driver(**changes: Any) -> tuple[WindowsDriver, FakeHost]:
host = FakeHost(**changes)
d = WindowsDriver("win01", "admin", "secret")
d._transport = host # type: ignore[assignment]
return d, host
# ---------------------------------------------------------------------------
# The zone table (CLDR windowsZones.xml, generated)
# ---------------------------------------------------------------------------
class TestZoneTable:
def test_every_windows_zone_reads_back_as_itself(self):
"""The name a zone is read as is a name that writes that zone."""
for windows, iana in WINDOWS_TO_IANA.items():
assert IANA_TO_WINDOWS[iana] == windows
def test_every_name_is_a_real_zone(self):
from zoneinfo import ZoneInfo
for name in [*WINDOWS_TO_IANA.values(), *IANA_TO_WINDOWS]:
ZoneInfo(name)
@pytest.mark.parametrize(
("iana", "windows"),
[
("Europe/Berlin", "W. Europe Standard Time"),
("Europe/Vienna", "W. Europe Standard Time"),
("Europe/London", "GMT Standard Time"),
("Asia/Kolkata", "India Standard Time"), # CLDR keeps Asia/Calcutta
("Asia/Calcutta", "India Standard Time"),
("Europe/Kyiv", "FLE Standard Time"),
("America/New_York", "Eastern Standard Time"),
("Etc/UTC", "UTC"),
("UTC", "UTC"), # a tzdata link to Etc/UTC
("CET", None), # not a zone CLDR maps
],
)
def test_an_iana_name_as_windows_zone(self, iana, windows):
assert windows_time_zone(iana) == windows
def test_renamed_zones_read_as_their_current_name(self):
assert WINDOWS_TO_IANA["India Standard Time"] == "Asia/Kolkata"
assert WINDOWS_TO_IANA["FLE Standard Time"] == "Europe/Kyiv"
assert WINDOWS_TO_IANA["Greenland Standard Time"] == "America/Nuuk"
# A merge in tzdata is no rename: Reykjavik keeps its name.
assert WINDOWS_TO_IANA["Greenwich Standard Time"] == "Atlantic/Reykjavik"
# ---------------------------------------------------------------------------
# Reading
# ---------------------------------------------------------------------------
class TestRead:
def test_is_offered_and_writes_both(self):
assert issubclass(WindowsDriver, TimeSyncMixin)
assert callable(WindowsDriver.get_time_sync)
assert WindowsDriver.time_sync_writes == frozenset({"ntp_servers", "timezone"})
def test_a_workgroup_host_as_installed(self):
d, host = _driver()
assert d.get_time_sync() == {
"ntp_servers": ["time.windows.com"],
"timezone": "Europe/Berlin",
"synchronized": True,
"daemon": "w32time",
}
assert host.sent == [mod._PS_TIME_SYNC]
def test_servers_without_their_flags_in_order(self):
d, _ = _driver(ntp_server="ntp1.example.org,0x8 10.0.0.1,0x8 ntp1.example.org,0x1")
assert d.get_time_sync()["ntp_servers"] == ["ntp1.example.org", "10.0.0.1"]
def test_a_domain_member_reports_the_servers_configured(self):
d, _ = _driver(type="NT5DS")
assert d.get_time_sync()["ntp_servers"] == ["time.windows.com"]
assert d.get_time_sync()["daemon"] == "w32time"
def test_group_policy_overrides_the_local_settings(self):
d, _ = _driver(policy_type="NTP", policy_server="ntp.corp.example,0x8")
assert d.get_time_sync()["ntp_servers"] == ["ntp.corp.example"]
def test_nosync_has_no_source(self):
d, _ = _driver(type="NoSync")
assert d.get_time_sync()["ntp_servers"] == []
@pytest.mark.parametrize(
("service", "status", "synchronized"),
[
("Running", UNSYNCED, False),
("Running", GERMAN, True),
("Running", NOT_STARTED, None),
("Running", None, None),
("Stopped", None, False),
(None, None, None),
],
)
def test_synchronized_from_the_leap_indicator(self, service, status, synchronized):
d, _ = _driver(service=service, status=status)
assert d.get_time_sync()["synchronized"] is synchronized
@pytest.mark.parametrize(
("zone", "marker", "iana"),
[
("W. Europe Standard Time", "Europe/Vienna", "Europe/Vienna"),
("GMT Standard Time", "Europe/Vienna", "Europe/London"), # changed by hand since
("W. Europe Standard Time\u0000\u0000", None, "Europe/Berlin"),
("Some Custom Standard Time", None, None),
("", None, None),
],
)
def test_the_zone(self, zone, marker, iana):
d, _ = _driver(zone=zone, iana_zone=marker)
assert d.get_time_sync()["timezone"] == iana
def test_summer_time_switched_off_is_not_the_zone(self):
d, _ = _driver(dst_off="1", iana_zone="Europe/Berlin")
assert d.get_time_sync()["timezone"] is None
def test_a_cut_reading_raises(self):
d, host = _driver()
host.run = lambda script: "" # type: ignore[method-assign]
with pytest.raises(ValueError):
d.get_time_sync()
# ---------------------------------------------------------------------------
# Writing
# ---------------------------------------------------------------------------
class TestWriteServers:
def test_sets_manual_peers_in_client_mode(self):
d, host = _driver()
result = d.configure_time_sync(ntp_servers=["ntp1.example.org", "10.0.0.1"])
assert result["success"], result["output"]
(script,) = host.writes
assert "-Name NtpServer -Value 'ntp1.example.org,0x8 10.0.0.1,0x8'" in script
assert "-Name Type -Value 'NTP'" in script
assert "Start-Service -Name W32Time" in script
assert script.index("Set-ItemProperty") < script.index("w32tm /config /update")
assert d.get_time_sync()["ntp_servers"] == ["ntp1.example.org", "10.0.0.1"]
def test_the_same_servers_again_write_nothing(self):
d, host = _driver(ntp_server="NTP1.example.org,0x8")
result = d.configure_time_sync(ntp_servers=["ntp1.example.org"])
assert result["success"], result["output"]
assert host.writes == []
def test_nosync_with_the_same_servers_is_written(self):
d, host = _driver(type="NoSync", ntp_server="ntp1.example.org,0x8")
assert d.configure_time_sync(ntp_servers=["ntp1.example.org"])["success"]
assert len(host.writes) == 1
@pytest.mark.parametrize("kind", ["NT5DS", "AllSync"])
def test_a_domain_member_is_refused(self, kind):
d, host = _driver(type=kind)
result = d.configure_time_sync(ntp_servers=["10.0.0.1"])
assert not result["success"]
assert "domain" in result["steps"][0]["output"]
assert host.writes == []
def test_group_policy_is_refused(self):
d, host = _driver(policy_server="ntp.corp.example,0x8")
result = d.configure_time_sync(ntp_servers=["10.0.0.1"])
assert not result["success"]
assert "group policy" in result["steps"][0]["output"]
assert host.writes == []
def test_a_failed_script_fails_the_step(self):
d, host = _driver()
host.fail = "w32tm /config: The service cannot be started (0x80070422)"
result = d.configure_time_sync(ntp_servers=["10.0.0.1"])
assert not result["success"]
assert "0x80070422" in result["steps"][0]["output"]
class TestWriteZone:
def test_sets_the_windows_zone_and_remembers_the_name(self):
d, host = _driver(zone="GMT Standard Time")
result = d.configure_time_sync(timezone="Europe/Vienna")
assert result["success"], result["output"]
(script,) = host.writes
assert "Set-TimeZone -Id 'W. Europe Standard Time'" in script
assert "-Name IanaTimeZone -Value 'Europe/Vienna'" in script
assert d.get_time_sync()["timezone"] == "Europe/Vienna"
def test_the_same_windows_zone_only_remembers_the_name(self):
d, host = _driver()
result = d.configure_time_sync(timezone="Europe/Vienna")
assert result["success"], result["output"]
(script,) = host.writes
assert "Set-TimeZone" not in script
assert d.get_time_sync()["timezone"] == "Europe/Vienna"
def test_the_same_zone_again_writes_nothing(self):
d, host = _driver(iana_zone="Europe/Berlin")
assert d.configure_time_sync(timezone="Europe/Berlin")["success"]
assert host.writes == []
def test_summer_time_off_is_turned_on(self):
d, host = _driver(dst_off="1", iana_zone="Europe/Berlin")
result = d.configure_time_sync(timezone="Europe/Berlin")
assert result["success"], result["output"]
assert "Set-TimeZone -Id 'W. Europe Standard Time'" in host.writes[0]
def test_a_zone_windows_does_not_have_is_refused(self):
d, host = _driver()
result = d.configure_time_sync(timezone="CET")
assert not result["success"]
assert "no Windows time zone" in result["steps"][0]["output"]
assert host.writes == []
def test_servers_and_zone_together(self):
d, host = _driver()
result = d.configure_time_sync(ntp_servers=["10.0.0.1"], timezone="America/New_York")
assert result["success"], result["output"]
assert [s["step"] for s in result["steps"]] == ["ntp_servers", "timezone", "verify"]
assert d.get_time_sync()["timezone"] == "America/New_York"
+47 -1
View File
@@ -11,7 +11,7 @@ from unittest.mock import patch
import pytest
import requests
from napalm.base.exceptions import ConnectionClosedException, ConnectionException
from pypsrp.exceptions import AuthenticationError, WinRMTransportError
from pypsrp.exceptions import AuthenticationError, WinRMError, WinRMTransportError
from napalm_windows.transport import PowerShellError, PsrpTransport
@@ -120,6 +120,52 @@ class TestRun:
_transport().run("Get-Thing")
class TestRunLast:
"""A script that may take WinRM down with it: a restart, a shutdown."""
def test_a_finished_script_is_true(self, psrp):
psrp["ps"].return_value.invoke.return_value = []
psrp["ps"].return_value.had_errors = False
t = _transport()
t.open()
assert t.run_last("Restart-Computer") is True
psrp["ps"].return_value.add_script.assert_called_once_with("Restart-Computer")
assert t.is_open is True
def test_the_error_stream_still_raises_powershell_error(self, psrp):
psrp["ps"].return_value.invoke.return_value = []
psrp["ps"].return_value.had_errors = True
psrp["ps"].return_value.streams.error = ["other users logged on"]
t = _transport()
t.open()
with pytest.raises(PowerShellError, match="other users logged on"):
t.run_last("Restart-Computer")
@pytest.mark.parametrize(
"error",
[
requests.ConnectionError("connection reset by peer"),
requests.ReadTimeout("read timed out"),
WinRMTransportError("http", 503, "Service Unavailable"),
WinRMError("the shell was terminated"),
ConnectionResetError(104, "Connection reset by peer"),
],
)
def test_a_connection_that_breaks_is_false_and_closed(self, psrp, error):
psrp["ps"].return_value.invoke.side_effect = error
t = _transport()
t.open()
assert t.run_last("Restart-Computer") is False
assert t.is_open is False
def test_run_last_before_open_raises_connection_closed(self):
with pytest.raises(ConnectionClosedException):
_transport().run_last("Restart-Computer")
class TestClose:
def test_close_closes_pool_and_connection(self, psrp):
t = _transport()
+76 -3
View File
@@ -28,9 +28,15 @@ def _fixture(name: str) -> str:
class FakeTransport:
"""Answers the driver's scripts from fixtures and records what it was sent."""
def __init__(self, answers: dict[str, str] | None = None, error: str | None = None):
def __init__(
self,
answers: dict[str, str] | None = None,
error: str | None = None,
drops: bool = False,
):
self.answers = answers or {}
self.error = error
self.drops = drops
self.sent: list[str] = []
self.is_open = True
@@ -40,6 +46,14 @@ class FakeTransport:
raise PowerShellError(self.error)
return self.answers.get(script, "")
def run_last(self, script: str) -> bool:
self.sent.append(script)
if self.error:
raise PowerShellError(self.error)
if self.drops:
self.is_open = False
return not self.drops
def close(self) -> None:
self.is_open = False
@@ -297,10 +311,17 @@ class TestGetArpTable:
arp = _driver(_PS_ARP=_fixture("arp.json")).get_arp_table()
assert arp == [
{"interface": "Ethernet", "mac": "00:0D:B9:11:22:33", "ip": "10.0.0.1", "age": 0.0},
{"interface": "Ethernet", "mac": "00:15:5D:AA:BB:CC", "ip": "10.0.0.20", "age": 0.0},
{"interface": "Ethernet", "mac": "00:0D:B9:11:22:33", "ip": "10.0.0.1", "age": -1.0},
{"interface": "Ethernet", "mac": "00:15:5D:AA:BB:CC", "ip": "10.0.0.20", "age": -1.0},
]
def test_age_is_unknown(self):
"""Get-NetNeighbor has a state but no age; 0.0 would read as "confirmed
just now" to a caller ranking sightings by freshness (NetOrk/netork#1327)."""
arp = _driver(_PS_ARP=_fixture("arp.json")).get_arp_table()
assert {entry["age"] for entry in arp} == {-1.0}
class TestGetRouteTo:
def test_maps_protocols_and_drops_noise(self):
@@ -483,3 +504,55 @@ class TestManageService:
"success": False,
"output": "Cannot find any service with service name 'nope'.",
}
class TestHostPower:
"""``reboot_host`` and ``shutdown_host``: the clean restart and shutdown of the host
itself, never a forced one (NetOrk/netork#2841)."""
@pytest.mark.parametrize(
("method", "cmdlet"),
[("reboot_host", "Restart-Computer"), ("shutdown_host", "Stop-Computer")],
)
def test_sends_the_cmdlet_without_force(self, method, cmdlet):
d = _driver()
getattr(d, method)()
(script,) = d._transport.sent
assert script.startswith(cmdlet)
assert "-ErrorAction Stop" in script
assert "-Force" not in script
@pytest.mark.parametrize(
("method", "what"), [("reboot_host", "restart"), ("shutdown_host", "shut down")]
)
def test_a_refusal_raises_with_the_hosts_answer(self, method, what):
answer = (
"Failed to restart the computer WIN01 with the following error message: The "
"system shutdown cannot be initiated because there are other users logged on "
"to the computer."
)
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(error=answer)
with pytest.raises(RuntimeError, match=f"refused to {what}: Failed to restart"):
getattr(d, method)()
@pytest.mark.parametrize("method", ["reboot_host", "shutdown_host"])
def test_a_connection_dropped_by_the_host_counts_as_accepted(self, method):
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(drops=True)
getattr(d, method)()
assert len(d._transport.sent) == 1
@pytest.mark.parametrize("method", ["reboot_host", "shutdown_host"])
def test_before_open_raises_connection_closed(self, method):
with pytest.raises(ConnectionClosedException):
getattr(WindowsDriver("win01", "admin", "secret"), method)()
@pytest.mark.parametrize("method", ["reboot_host", "shutdown_host"])
def test_the_capability_is_there_for_introspection(self, method):
assert callable(getattr(WindowsDriver("win01", "admin", "secret"), method, None))
+62
View File
@@ -0,0 +1,62 @@
"""tools/windows_zones.py: the generator of napalm_windows/_windows_zones.py."""
from __future__ import annotations
import importlib.util
from pathlib import Path
TOOL = Path(__file__).parent.parent / "tools" / "windows_zones.py"
_spec = importlib.util.spec_from_file_location("windows_zones_tool", TOOL)
assert _spec is not None and _spec.loader is not None
tool = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(tool)
XML = """<?xml version="1.0" encoding="UTF-8" ?>
<supplementalData><windowsZones><mapTimezones>
<mapZone other="India Standard Time" territory="001" type="Asia/Calcutta"/>
<mapZone other="India Standard Time" territory="IN" type="Asia/Calcutta"/>
<mapZone other="Greenwich Standard Time" territory="001" type="Atlantic/Reykjavik"/>
<mapZone other="Greenwich Standard Time" territory="CI" type="Africa/Abidjan"/>
<mapZone other="UTC" territory="001" type="Etc/UTC"/>
<mapZone other="UTC" territory="ZZ" type="Etc/UTC Etc/GMT"/>
</mapTimezones></windowsZones></supplementalData>
"""
TZDATA = """# version 2026e
Z Etc/UTC 0 - UTC
L Asia/Kolkata Asia/Calcutta
L Africa/Abidjan Atlantic/Reykjavik
L Etc/UTC UTC
"""
def _tables(tmp_path: Path) -> tuple[dict[str, str], dict[str, str]]:
(tmp_path / "w.xml").write_text(XML)
(tmp_path / "tzdata.zi").write_text(TZDATA)
primary, to_windows, _ = tool.read_cldr(tmp_path / "w.xml")
return tool.build(primary, to_windows, tool.read_links(tmp_path / "tzdata.zi"))
def test_a_renamed_zone_reads_as_its_new_name(tmp_path):
windows_to_iana, iana_to_windows = _tables(tmp_path)
assert windows_to_iana["India Standard Time"] == "Asia/Kolkata"
assert iana_to_windows["Asia/Kolkata"] == iana_to_windows["Asia/Calcutta"]
def test_a_merged_zone_keeps_its_name(tmp_path):
windows_to_iana, _ = _tables(tmp_path)
assert windows_to_iana["Greenwich Standard Time"] == "Atlantic/Reykjavik"
def test_links_to_a_mapped_zone_are_mapped(tmp_path):
_, iana_to_windows = _tables(tmp_path)
assert iana_to_windows["UTC"] == "UTC"
assert iana_to_windows["Etc/GMT"] == "UTC"
def test_the_module_names_its_sources(tmp_path):
text = tool.render(*_tables(tmp_path), "release-49", "abc", "2026e")
assert "CLDR release-49" in text and "sha256 abc" in text and "2026e" in text
namespace: dict[str, object] = {}
exec(compile(text, "generated", "exec"), namespace)
assert namespace["WINDOWS_TO_IANA"] == _tables(tmp_path)[0]
+17 -1
View File
@@ -14,7 +14,16 @@ import argparse
import getpass
import pathlib
from napalm_windows import WindowsDriver
from napalm_windows import (
WindowsDriver,
host_status,
os_users,
packages,
processes,
scheduled_tasks,
system_identity,
time_sync,
)
from napalm_windows import windows as mod
SCRIPTS = {
@@ -25,6 +34,13 @@ SCRIPTS = {
"routes": mod._PS_ROUTES,
"services": mod._PS_SERVICES,
"listening": mod._PS_LISTENING,
"scheduled_tasks": scheduled_tasks._PS_SCHEDULED_TASKS,
"time_sync": time_sync._PS_TIME_SYNC,
"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"
+109
View File
@@ -0,0 +1,109 @@
"""Generate napalm_windows/_windows_zones.py from CLDR's windowsZones.xml and tzdata's links.
python tools/windows_zones.py windowsZones.xml /usr/share/zoneinfo/tzdata.zi \\
--cldr release-49 > napalm_windows/_windows_zones.py
windowsZones.xml is CLDR's mapping of Windows zone ids to IANA names
(https://github.com/unicode-org/cldr/blob/<release>/common/supplemental/windowsZones.xml);
tzdata.zi is the compact form of the IANA database, read for its link lines (``L target
alias``). The driver never fetches either at runtime: rerun this when a new CLDR release
adds Windows zones, and commit the result.
* ``WINDOWS_TO_IANA``: each Windows zone's territory ``001`` zone -- the one name CLDR
gives it. CLDR keeps old names (``Asia/Calcutta``, ``Europe/Kiev``); one that is a
link in tzdata to a zone CLDR does not name is replaced by that zone (``Asia/Kolkata``).
A link to a zone CLDR does name is a merge, not a rename (``Atlantic/Reykjavik`` ->
``Africa/Abidjan``), and keeps its own name.
* ``IANA_TO_WINDOWS``: every IANA name CLDR maps, in any territory, to its Windows zone;
plus each tzdata link to or from such a name that CLDR does not map itself.
"""
from __future__ import annotations
import argparse
import hashlib
import pathlib
import xml.etree.ElementTree as ET # nosec B405 - a file the developer downloaded, not input
def read_cldr(path: pathlib.Path) -> tuple[dict[str, str], dict[str, str], set[str]]:
"""``(windows -> 001 zone, every CLDR zone -> windows, all CLDR names)``."""
primary: dict[str, str] = {}
to_windows: dict[str, str] = {}
for node in ET.parse(path).iter("mapZone"): # nosec B314
windows, names = node.attrib["other"], node.attrib["type"].split()
if node.attrib["territory"] == "001":
primary[windows] = names[0]
for name in names:
if to_windows.setdefault(name, windows) != windows:
raise SystemExit(f"{name} maps to {to_windows[name]} and {windows}")
return primary, to_windows, set(to_windows)
def read_links(path: pathlib.Path) -> list[tuple[str, str]]:
"""tzdata's ``(target, alias)`` links."""
links = []
for line in path.read_text().splitlines():
if line.startswith("L "):
_, target, alias = line.split()
links.append((target, alias))
return links
def build(
primary: dict[str, str], to_windows: dict[str, str], links: list[tuple[str, str]]
) -> tuple[dict[str, str], dict[str, str]]:
cldr = set(to_windows)
renamed = {alias: target for target, alias in links if target not in cldr}
windows_to_iana = {w: renamed.get(name, name) for w, name in sorted(primary.items())}
iana_to_windows = dict(to_windows)
for target, alias in links:
if target in to_windows and alias not in iana_to_windows:
iana_to_windows[alias] = to_windows[target]
elif alias in to_windows and target not in iana_to_windows:
iana_to_windows[target] = to_windows[alias]
return windows_to_iana, dict(sorted(iana_to_windows.items()))
def render(
windows_to_iana: dict[str, str],
iana_to_windows: dict[str, str],
cldr_release: str,
cldr_sha: str,
tz_version: str,
) -> str:
lines = [
'"""Windows time zones and IANA names. Generated by tools/windows_zones.py: do not edit.',
"",
f"Source: CLDR {cldr_release}, common/supplemental/windowsZones.xml",
f"(sha256 {cldr_sha}),",
f"with the link lines of the IANA time zone database {tz_version} (tzdata.zi).",
'"""',
"",
"WINDOWS_TO_IANA: dict[str, str] = {",
*(f' "{w}": "{name}",' for w, name in windows_to_iana.items()),
"}",
"",
"IANA_TO_WINDOWS: dict[str, str] = {",
*(f' "{name}": "{w}",' for name, w in iana_to_windows.items()),
"}",
"",
]
return "\n".join(lines)
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("windows_zones", type=pathlib.Path)
ap.add_argument("tzdata_zi", type=pathlib.Path)
ap.add_argument("--cldr", required=True, help="the CLDR release the XML is from")
args = ap.parse_args()
primary, to_windows, _ = read_cldr(args.windows_zones)
links = read_links(args.tzdata_zi)
tz_version = args.tzdata_zi.read_text().splitlines()[0].removeprefix("# version ").strip()
sha = hashlib.sha256(args.windows_zones.read_bytes()).hexdigest()
print(render(*build(primary, to_windows, links), args.cldr, sha, tz_version), end="")
if __name__ == "__main__":
main()