Author SHA1 Message Date
Christian Manivong 2b0bfac4f7 refactor(logins): keep the member and session parses within complexity 10 (NetOrk/netork#2895)
_member hands its name and kind to _member_name and _is_group;
parse_login_sessions hands the audit check to _audited_logons and the
sessions to _sessions. No change in behaviour.
2026-12-01 23:20:36 +01:00
Christian Manivong de6ab3c801 feat(logins): login accounts and console and Remote Desktop sessions (NetOrk/netork#2895)
get_login_accounts reads the host's own accounts (Get-LocalUser), their
last login and failed attempts from the account database, expiry and
lock, and whether each is an administrator (S-1-5-32-544, by SID) or may
log in over Remote Desktop (the logon right and its denial from
secedit, the host's fDenyTSConnections). groups lists the groups that
grant either, with every member, a domain's included. uid is the RID,
sid the SID. A domain controller's accounts are not read.

get_login_sessions reads logon events 4624 of type 2, 10 and 11 of the
last seven days from the Security log, ended by 4634/4647, an
administrator's two linked logons as one session. own_address is the
reading's own WinRM logon's address; records_since the log's oldest
event. A log without any logon raises LoginSessionsUnavailable.

Both scripts are in tools/harvest.py.
2026-12-01 12:55:49 +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
30 changed files with 5285 additions and 35 deletions

No files matched your search

+68
View File
@@ -6,6 +6,74 @@ All notable changes to this driver. The format follows
## [Unreleased]
### Added
- Who can log in to the host and who did, for the access review (NetOrk/netork#2895):
napalm-device-types' `get_login_accounts` and `get_login_sessions`.
- `get_login_accounts` lists the host's own accounts (`Get-LocalUser`) with their
last login and failed attempts since it from the account database (source `sam`),
password and account expiry, and whether each is locked (disabled, expired or locked
out). Each says whether it is an administrator and whether it may log in over
Remote Desktop: found by SID, so a German "Administratoren" counts, and from the
Remote Desktop logon right and its denial (`secedit /export`) with the host's
Remote Desktop setting. `groups` lists the groups granting either, with every
member, a domain's groups and accounts by name. `uid` is the RID, `sid` the SID. A
domain controller's accounts are the directory's and are not listed.
- `get_login_sessions` lists the console and Remote Desktop logons of the last seven
days from the Security log, each with its account, address, start and end; never a
network logon, so neither the driver's own WinRM connection nor SMB access shows.
`records_since` says how far back the log reaches, and a host that does not audit
logons raises `LoginSessionsUnavailable` rather than reporting nobody.
- 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.
+88 -1
View File
@@ -37,13 +37,100 @@ 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_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* |
| `get_login_accounts` | `Get-LocalUser`, `Win32_UserProfile`, `WinNT:` (`BadPasswordAttempts`, `IsAccountLocked`, group members), `secedit /export /areas USER_RIGHTS`, `fDenyTSConnections`. See *Logins* |
| `get_login_sessions` | Security log 4624 (logon types 2, 10, 11), 4634/4647, bounded to seven days on the host. See *Logins* |
`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.
### Logins
napalm-device-types' login readings, for the access review (NetOrk/netork#2895). Both
are read-only, one script each, and take an administrator.
* **Accounts** are the host's own (`Get-LocalUser`; without it, not supported), not the
system's `DefaultAccount` and `WDAGUtilityAccount`. `uid` is the RID, `sid` the SID;
`shell` is empty, `home` the profile folder. The last login and the failed attempts
since it (`BadPasswordAttempts`) are the account database's, source `sam`; an account
is `locked` when disabled, expired or locked out. A domain controller's accounts are
the directory's and are not read.
* **Administrators and Remote Desktop** go by SID, so a German host's "Administratoren"
is found: `administrator` is membership of `S-1-5-32-544`; `remote_desktop` that the
host takes Remote Desktop logins (`fDenyTSConnections`, group policy first) and the
account holds `SeRemoteInteractiveLogonRight` without being denied it, through
itself, a local group, or a SID every local logon carries (Everyone, Local account).
`groups` lists the groups that grant either, with every member as the host names it,
a domain's groups included. secedit's export goes to a file under
`%SystemRoot%\Temp`, removed at once.
* **Sessions** are logon events 4624 of type 2 (console), 10 (Remote Desktop) and 11
(cached, at the console) of the last seven days, the newest 1000, as `tty` `console`
or `rdp`; network logons (type 3) are not, since every WinRM and SMB connection is
one. A person's account only: not `DWM-n` or `UMFD-n`. An administrator's two linked
logons are one session; the end is its logoff (4634, 4647). `own_address` is the
address of the reading's own WinRM logon, found by its logon ID, else the one client
connected to WinRM; its sessions are left out. `records_since` is the Security log's
oldest event: the log rotates by size, so a login before it is unknown. A log that
holds no logon, not even the reading's own, raises `LoginSessionsUnavailable`.
* **Not read:** OpenSSH for Windows logins and the Remote Desktop session manager's own
log (`TerminalServices-LocalSessionManager`); the domain's accounts.
Not yet: packages, 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}'"
+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",
}
+424
View File
@@ -0,0 +1,424 @@
"""Who can log in to a Windows host, for the access review (NetOrk/netork#2895).
:class:`WindowsLoginAccountsMixin` fills napalm-device-types' ``get_login_accounts``
reading (``LoginAccountsDict``) from one script, read-only:
- **The accounts** are the host's own, ``Get-LocalUser`` (probed with ``Get-Command``
first: without it the reading is not supported). ``DefaultAccount`` and
``WDAGUtilityAccount`` (RIDs 503 and 504) are the system's and are left out, as Linux
leaves out its system accounts. ``uid`` is the RID, the SID's last part, and ``sid``
the whole SID. ``home`` is the profile's folder (``Win32_UserProfile``); Windows has no
login shell, so ``shell`` is empty.
- **The last login** is the account database's (``LastLogon``), source ``sam``; it knows
no address or terminal.
- **Lock and expiry:** an account is ``locked`` when it is disabled, expired or locked out
(``IsAccountLocked`` of the ``WinNT:`` provider); the password's last change and expiry
are ``Get-LocalUser``'s. A password that never expires has no ``PasswordExpires``.
- **The failed attempts since the last login** are ``BadPasswordAttempts`` (``WinNT:``),
which a successful login resets, source ``sam``.
- **Administrators and Remote Desktop** go by SID, never by name: the Administrators
group is ``S-1-5-32-544`` in every language ("Administratoren"). Its members, and those
of every local group that holds or is denied the right to log in through Remote Desktop
Services (``SeRemoteInteractiveLogonRight``, ``SeDenyRemoteInteractiveLogonRight``, from
``secedit /export``), are read through ``WinNT:``, a domain's groups and accounts by
name. An account may log in at a remote desktop when the host takes such logins
(``fDenyTSConnections``, group policy's first), one of its SIDs holds the right and
none is denied it. Its SIDs are its own, those every local account's logon carries
(Everyone, Authenticated Users, INTERACTIVE, REMOTE INTERACTIVE LOGON, Local account)
and the local groups it or one of those is a member of.
- **A domain controller** has no accounts of its own: they are the directory's, reviewed
there. Its accounts are not read; its groups are.
Each part that fails leaves its fields ``None`` (not read), never "no"; the script's
``errors`` say which.
"""
from __future__ import annotations
import json
import logging
from collections.abc import Iterable
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
from napalm_windows._powershell import _as_list
if TYPE_CHECKING: # pragma: no cover - the contract's newer keys, for type checkers only
from napalm_device_types.login_accounts import (
LoginAccountDict,
LoginAccountsDict,
LoginGroupDict,
LoginGroupMemberDict,
)
logger = logging.getLogger(__name__)
#: The account database: where the last logins and the failed attempts come from.
SOURCE = "sam"
ADMINISTRATORS = "S-1-5-32-544"
REMOTE_DESKTOP_USERS = "S-1-5-32-555"
#: The system's own accounts: DefaultAccount, WDAGUtilityAccount.
_SYSTEM_RIDS = frozenset({503, 504})
#: Win32_ComputerSystem.DomainRole of a backup and a primary domain controller.
_DOMAIN_CONTROLLER = 4
#: The SIDs every local account's remote desktop logon carries: Everyone, Authenticated
#: Users, INTERACTIVE, REMOTE INTERACTIVE LOGON, Local account.
_LOGON_SIDS = frozenset({"S-1-1-0", "S-1-5-11", "S-1-5-4", "S-1-5-14", "S-1-5-113"})
#: Local account and member of the Administrators group.
_LOCAL_ADMIN = "S-1-5-114"
#: The SIDs of a domain's or the host's own accounts and groups, and of Entra ID's; any
#: other SID is a principal of the host itself (Everyone, INTERACTIVE, the BUILTIN groups).
_ACCOUNT_SIDS = ("S-1-5-21-", "S-1-12-")
_PS_LOGIN_ACCOUNTS = r"""
$ErrorActionPreference = 'Stop'
$errors = @()
$tsKey = 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server'
$tsPolicy = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services'
$rdpRight = 'SeRemoteInteractiveLogonRight'
function Ms($t) { if ($null -ne $t) { ([DateTimeOffset]$t).ToUnixTimeMilliseconds() } }
function V($path, $name) {
$item = Get-ItemProperty -Path $path -Name $name -ErrorAction SilentlyContinue
if ($item) { [string]$item.$name }
}
function Prop($o, $name) { $o.GetType().InvokeMember($name, 'GetProperty', $null, $o, $null) }
function Sid($value) { New-Object Security.Principal.SecurityIdentifier $value }
function UserFlag($name, $prop) {
try {
$entry = [ADSI]('WinNT://' + $env:COMPUTERNAME + '/' + $name + ',user')
$entry.psbase.InvokeGet($prop)
} catch { $null }
}
function GroupMember($m) {
$bytes = $null
try { $bytes = [byte[]](Prop $m 'objectSid') } catch { }
$sid = $null
if ($bytes) { $sid = [Security.Principal.SecurityIdentifier]::new($bytes, 0).Value }
[pscustomobject]@{
path = [string](Prop $m 'ADsPath')
class = [string](Prop $m 'Class')
sid = $sid
}
}
function LocalGroup($sid) {
$account = (Sid $sid).Translate([Security.Principal.NTAccount]).Value
$domain, $name = $account.Split('\', 2)
if ($null -eq $name) { return }
if ($domain -ne 'BUILTIN' -and $domain -ne $env:COMPUTERNAME) { return }
$entry = [ADSI]('WinNT://' + $env:COMPUTERNAME + '/' + $name + ',group')
[pscustomobject]@{
sid = $sid
name = $name
members = @($entry.psbase.Invoke('Members') | ForEach-Object { GroupMember $_ })
}
}
function Holders($text) { @($text.Split(',') | ForEach-Object { $_.Trim() } | Where-Object { $_ }) }
function Rights {
$file = 'Temp\napalm-windows-' + [guid]::NewGuid().ToString('N') + '.inf'
$cfg = Join-Path $env:SystemRoot $file
try {
$null = cmd.exe /c ('secedit /export /areas USER_RIGHTS /cfg ' + $cfg + ' 2>&1')
if (-not (Test-Path -LiteralPath $cfg)) { return }
$allow = @(); $deny = @()
foreach ($line in Get-Content -LiteralPath $cfg) {
if ($line -match '^\s*(Se\w+)\s*=\s*(.*)$') {
if ($Matches[1] -eq $rdpRight) { $allow = Holders $Matches[2] }
if ($Matches[1] -eq ('SeDeny' + $rdpRight)) { $deny = Holders $Matches[2] }
}
}
[pscustomobject]@{ allow = $allow; deny = $deny }
} finally { Remove-Item -LiteralPath $cfg -ErrorAction SilentlyContinue }
}
$me = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
$role = [int](Get-CimInstance -ClassName Win32_ComputerSystem).DomainRole
$homes = @{}
try {
Get-CimInstance -ClassName Win32_UserProfile |
ForEach-Object { $homes[[string]$_.SID] = [string]$_.LocalPath }
} catch { $errors += 'profiles: ' + $_ }
$users = $null
if ($role -ge 4) { $users = @() }
elseif (Get-Command -Name Get-LocalUser -ErrorAction SilentlyContinue) {
$users = @(Get-LocalUser | ForEach-Object {
$sid = [string]$_.SID.Value
[pscustomobject]@{
name = $_.Name
sid = $sid
enabled = [bool]$_.Enabled
home = $homes[$sid]
last_logon = Ms $_.LastLogon
password_last_set = Ms $_.PasswordLastSet
password_expires = Ms $_.PasswordExpires
account_expires = Ms $_.AccountExpires
bad_passwords = UserFlag $_.Name 'BadPasswordAttempts'
locked_out = UserFlag $_.Name 'IsAccountLocked'
}
})
}
$rights = $null
try { $rights = Rights } catch { $errors += 'rights: ' + $_ }
$wanted = @('S-1-5-32-544', 'S-1-5-32-555')
if ($rights) {
$wanted += @(@($rights.allow) + @($rights.deny) | Where-Object { $_.StartsWith('*') } |
ForEach-Object { $_.Substring(1) })
}
$groups = @(foreach ($sid in @($wanted | Select-Object -Unique)) {
try { LocalGroup $sid } catch { $errors += 'group ' + $sid + ': ' + $_ }
})
[pscustomobject]@{
computer = $env:COMPUTERNAME
domain_role = $role
admin = [bool]$me.IsInRole((Sid 'S-1-5-32-544'))
now = Ms (Get-Date)
users = $users
groups = $groups
rights = $rights
rdp_deny = V $tsKey 'fDenyTSConnections'
rdp_deny_policy = V $tsPolicy 'fDenyTSConnections'
errors = $errors
} | ConvertTo-Json -Compress -Depth 6
"""
def _iso(ms: Any) -> str | None:
"""Milliseconds since the epoch as ISO 8601 in UTC; None for none."""
if not isinstance(ms, int | float) or isinstance(ms, bool):
return None
return datetime.fromtimestamp(ms / 1000, UTC).isoformat()
def _date(ms: Any) -> str | None:
iso = _iso(ms)
return None if iso is None else iso[:10]
def _rid(sid: str) -> int | None:
try:
return int(sid.rsplit("-", 1)[1])
except (IndexError, ValueError):
return None
def _local(sid: str | None, domain: str | None, computer: str, machine: str | None) -> bool | None:
"""Whether a member is the host's own: by its SID where it says, else by its path."""
if sid and not sid.upper().startswith(_ACCOUNT_SIDS):
return True
if sid and machine:
return sid.rsplit("-", 1)[0].upper() == machine
return None if domain is None else domain.upper() == computer.upper()
def _member_name(parts: list[str], sid: str | None) -> tuple[str, str | None]:
"""The member's name as ``DOMAIN\\name`` and its domain; a bare SID has none."""
if len(parts) >= 2:
return f"{parts[-2]}\\{parts[-1]}", parts[-2]
return (parts[0] if parts else str(sid or "")), None
def _is_group(raw: dict[str, Any]) -> bool | None:
kind = str(raw.get("class") or "").lower()
return {"group": True, "user": False}.get(kind)
def _member(raw: dict[str, Any], computer: str, machine: str | None) -> LoginGroupMemberDict:
"""A ``WinNT:`` member: ``WinNT://DOMAIN/name``, ``WinNT://WORKGROUP/HOST/name`` for
the host's own, ``WinNT://S-1-5-…`` for a SID the host can no longer resolve."""
parts = [p for p in str(raw.get("path") or "").removeprefix("WinNT://").split("/") if p]
sid = str(raw.get("sid") or "") or None
name, domain = _member_name(parts, sid)
return {
"name": name,
"sid": sid,
"local": _local(sid, domain, computer, machine),
"group": _is_group(raw),
}
class _Rights:
"""Who holds and who is denied a remote desktop login; None where not read."""
def __init__(self, raw: dict[str, Any]) -> None:
rights = raw.get("rights")
self.read = isinstance(rights, dict)
holders = rights if isinstance(rights, dict) else {}
self.allow = {h.lstrip("*").upper() for h in _as_list(holders.get("allow"))}
self.deny = {h.lstrip("*").upper() for h in _as_list(holders.get("deny"))}
value = raw.get("rdp_deny_policy")
value = raw.get("rdp_deny") if value in (None, "") else value
self.enabled: bool | None = None if value in (None, "") else str(value).strip() == "0"
def holds(self, names: set[str]) -> bool | None:
"""Whether one of *names* (SIDs, account names) may log in at a remote desktop."""
if self.enabled is False:
return False
if self.enabled is None or not self.read:
return None
names = {n.upper() for n in names}
return bool(names & self.allow) and not names & self.deny
class _Groups:
"""The local groups read, by SID, with their members' SIDs."""
def __init__(self, raw: dict[str, Any]) -> None:
self.raw = [g for g in _as_list(raw.get("groups")) if isinstance(g, dict) and g.get("sid")]
self.members = {
str(g["sid"]).upper(): {
str(m.get("sid")).upper() for m in _as_list(g.get("members")) if m.get("sid")
}
for g in self.raw
}
def of(self, sid: str) -> set[str]:
"""The SIDs a local account's remote desktop logon carries."""
own = {sid.upper(), *_LOGON_SIDS}
groups = {g for g, members in self.members.items() if members & own}
extra = {_LOCAL_ADMIN} if ADMINISTRATORS in groups else set()
return own | groups | extra
def administrator(self, sid: str) -> bool | None:
if ADMINISTRATORS not in self.members:
return None
return ADMINISTRATORS in self.of(sid)
def _locked(user: dict[str, Any], now: Any) -> bool | None:
expires = user.get("account_expires")
if user.get("enabled") is False:
return True
if isinstance(expires, int | float) and isinstance(now, int | float) and expires <= now:
return True
locked_out = user.get("locked_out")
return locked_out if isinstance(locked_out, bool) else None
def _failed(user: dict[str, Any]) -> int | None:
value = user.get("bad_passwords")
return value if isinstance(value, int) and not isinstance(value, bool) else None
def _password_expires(user: dict[str, Any]) -> str | None:
"""The date, or "never" for a password set that never expires; None when not set."""
expires = _date(user.get("password_expires"))
if expires is not None:
return expires
return "never" if user.get("password_last_set") is not None else None
def _account(
user: dict[str, Any], rid: int, raw: dict[str, Any], groups: _Groups, rights: _Rights
) -> LoginAccountDict:
sid = str(user["sid"])
last = _iso(user.get("last_logon"))
changed = _date(user.get("password_last_set"))
return {
"name": str(user.get("name") or ""),
"uid": rid,
"home": str(user.get("home") or ""),
"shell": "",
"last_login": last,
"last_login_from": None,
"last_login_port": None,
"last_login_source": SOURCE if last else None,
"password": "set" if changed else None,
"password_changed": changed,
"password_expires": _password_expires(user),
"account_expires": _date(user.get("account_expires")) or "never",
"locked": _locked(user, raw.get("now")),
"failed_logins": _failed(user),
"failed_logins_capped": False,
"sid": sid,
"administrator": groups.administrator(sid),
"remote_desktop": rights.holds(groups.of(sid) | {str(user.get("name") or "")}),
}
def _accounts(
users: Iterable[Any], raw: dict[str, Any], groups: _Groups, rights: _Rights
) -> list[LoginAccountDict]:
accounts = []
for user in users:
rid = _rid(str(user.get("sid") or "")) if isinstance(user, dict) else None
if rid is not None and rid not in _SYSTEM_RIDS:
accounts.append(_account(user, rid, raw, groups, rights))
return accounts
def _grants(sid: str, rights: _Rights) -> list[str]:
grants = ["administrator"] if sid.upper() == ADMINISTRATORS else []
if rights.holds({sid}):
grants.append("remote_desktop")
return grants
def _machine(users: Iterable[Any]) -> str | None:
"""The host's own SID, its accounts' SIDs without the RID; None without accounts."""
for user in users:
sid = str(user.get("sid") or "") if isinstance(user, dict) else ""
if sid.upper().startswith("S-1-5-21-"):
return sid.rsplit("-", 1)[0].upper()
return None
def _login_groups(raw: dict[str, Any], groups: _Groups, rights: _Rights) -> list[LoginGroupDict]:
computer = str(raw.get("computer") or "")
machine = _machine(_as_list(raw.get("users")))
found: list[LoginGroupDict] = []
for group in groups.raw:
grants = _grants(str(group["sid"]), rights)
if grants:
found.append(
{
"name": str(group.get("name") or ""),
"sid": str(group["sid"]),
"grants": grants,
"members": [
_member(m, computer, machine) for m in _as_list(group.get("members"))
],
}
)
return found
def parse_login_accounts(raw: dict[str, Any]) -> LoginAccountsDict:
"""What :data:`_PS_LOGIN_ACCOUNTS` emitted, as napalm-device-types' reading.
:raises NotImplementedError: when the host has no ``Get-LocalUser``.
"""
for error in _as_list(raw.get("errors")):
logger.info("login accounts: part not read: %s", error)
users = raw.get("users")
if users is None and int(raw.get("domain_role") or 0) < _DOMAIN_CONTROLLER:
raise NotImplementedError("Get-LocalUser is not available on this host")
groups, rights = _Groups(raw), _Rights(raw)
accounts = _accounts(_as_list(users), raw, groups, rights)
read = users is not None and int(raw.get("domain_role") or 0) < _DOMAIN_CONTROLLER
failures = any(a["failed_logins"] is not None for a in accounts)
return {
"accounts": accounts,
"login_sources": [SOURCE] if read else [],
"failed_logins_source": SOURCE if failures else None,
"privileged": raw.get("admin") is True,
"groups": _login_groups(raw, groups, rights),
}
class WindowsLoginAccountsMixin:
"""``get_login_accounts`` for the driver, which carries the script."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def get_login_accounts(self) -> LoginAccountsDict:
"""Every account of the host and who can administer it or log in at a remote
desktop, in napalm-device-types' ``LoginAccountsDict``; see the module.
:raises NotImplementedError: when the host has no ``Get-LocalUser``.
:raises ValueError: when the reading came back empty.
"""
out = self._run_raw(_PS_LOGIN_ACCOUNTS).strip()
raw = json.loads(out) if out else None
if not isinstance(raw, dict):
raise ValueError("the login account reading came back empty")
return parse_login_accounts(raw)
+265
View File
@@ -0,0 +1,265 @@
"""The logins a Windows host recorded, at its console and over Remote Desktop
(NetOrk/netork#2895).
:class:`WindowsLoginSessionsMixin` fills napalm-device-types' ``get_login_sessions``
reading (``LoginSessionsDict``) from the Security event log, in one script, read-only:
- **The logons** are event 4624 of the last :data:`SESSION_WINDOW_DAYS` days, bounded on
the host (``timediff``), the newest :data:`SESSIONS_READ`: logon type 2 (at the
console), 10 (Remote Desktop) and 11 (at the console with cached credentials), as
``tty`` ``console`` or ``rdp``. Not type 3 (network): every SMB access and every WinRM
connection is one, this reading's own included; nor 7, an unlock of a session already
read. Only a person's account counts -- a SID of the host, a domain (``S-1-5-21-``) or
Entra ID (``S-1-12-``) -- not the window manager's or the font driver's (``DWM-1``,
``UMFD-0``). An administrator's logon is two events, a full and a filtered token
linked to each other (``TargetLinkedLogonId``): one session.
- **The end** is the logoff of the logon (4634, or 4647 when the user logged off). The
account is ``DOMAIN\\name``, the host's own accounts by name alone. The address is the
event's ``IpAddress``; a console logon's loopback is none.
- **The reading's own address** is that of its own WinRM logon: the session's logon ID
(``Win32_SessionProcess``, else the logon SID ``S-1-5-5-X-Y`` of its token) names its
4624 event. Where that event has no address, the one client connected to WinRM's ports
(``Get-NetTCPConnection``); several, none. Remote Desktop sessions from it are left out,
as on Linux the reading's own SSH sessions are.
- **Coverage:** the Security log rotates by size, often within days. ``records_since`` is
its oldest event, so a login before it is unknown rather than absent. A host that holds
not even this reading's own logon and no other in the window does not audit logons:
:class:`LoginSessionsUnavailable`, never "nobody logged in".
``Get-WinEvent`` answers no match with an error (``NoMatchingEventsFound``); the script
takes that for none. Reading the Security log takes an administrator.
"""
from __future__ import annotations
import ipaddress
import json
from collections.abc import Iterable
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
from napalm_device_types.login_sessions import (
SESSION_WINDOW_DAYS,
SESSIONS_READ,
LoginSessionsUnavailable,
session_address,
)
from napalm_windows._powershell import _as_list
if TYPE_CHECKING: # pragma: no cover - the contract's newer keys, for type checkers only
from napalm_device_types.login_sessions import LoginSessionDict, LoginSessionsDict
#: Logon type → terminal: at the console, Remote Desktop, at the console with cached
#: credentials.
LOGON_TYPES = {"2": "console", "10": "rdp", "11": "console"}
#: The SIDs of a person's account: the host's or a domain's, and Entra ID's.
_PERSON_SIDS = ("S-1-5-21-", "S-1-12-")
_DAY_MS = 86_400_000
_PS_SESSIONS_TEMPLATE = r"""
$ErrorActionPreference = 'Stop'
function Ms($t) { if ($null -ne $t) { ([DateTimeOffset]$t).ToUnixTimeMilliseconds() } }
function Events($filter, $max, [switch]$Oldest) {
try { Get-WinEvent -LogName Security -FilterXPath $filter -MaxEvents $max -Oldest:$Oldest }
catch { if ($_.FullyQualifiedErrorId -notlike 'NoMatchingEventsFound*') { throw } }
}
function P($e, $i) { if ($e.Properties.Count -gt $i) { [string]$e.Properties[$i].Value } }
function Logon($t) { "Data[@Name='LogonType']='" + $t + "'" }
function Query($id, $data) {
$within = 'TimeCreated[timediff(@SystemTime) <= __WINDOW_MS__]'
$system = "*[System[EventID=" + $id + " and " + $within + "]"
if ($data) { $system + " and EventData[" + $data + "]]" } else { $system + "]" }
}
$types = (Logon 2) + ' or ' + (Logon 10) + ' or ' + (Logon 11)
$ownId = $null
try {
$query = "ASSOCIATORS OF {Win32_Process.Handle='" + $PID + "'}" +
" WHERE AssocClass=Win32_SessionProcess"
$session = @(Get-CimInstance -Query $query)
if ($session.Count -gt 0) { $ownId = [uint64]$session[0].LogonId }
} catch { }
if ($null -eq $ownId) {
$groups = [Security.Principal.WindowsIdentity]::GetCurrent().Groups
$logonSid = @($groups | Where-Object { $_.Value -like 'S-1-5-5-*' })
if ($logonSid.Count -gt 0) {
$parts = $logonSid[0].Value.Split('-')
$ownId = ([uint64]$parts[4] -shl 32) + [uint64]$parts[5]
}
}
$canary = $null; $ownIp = $null
if ($null -ne $ownId) {
$mine = "Data[@Name='TargetLogonId']='" + ('0x{0:x}' -f $ownId) + "'"
$within = 'TimeCreated[timediff(@SystemTime) <= __DAY_MS__]'
$own = @(Events ("*[System[EventID=4624 and " + $within + "] and EventData[" + $mine + "]]") 1)
$canary = $own.Count -gt 0
if ($canary) { $ownIp = P $own[0] 18 }
}
$peers = @()
try {
$winrm = Get-NetTCPConnection -State Established -LocalPort 5985, 5986 `
-ErrorAction SilentlyContinue
$peers = @($winrm | ForEach-Object { [string]$_.RemoteAddress } | Sort-Object -Unique)
} catch { }
$logons = @(Events (Query 4624 $types) __READ__ | ForEach-Object {
[pscustomobject]@{
t = Ms $_.TimeCreated; sid = P $_ 4; user = P $_ 5; domain = P $_ 6
id = P $_ 7; type = P $_ 8; ip = P $_ 18; linked = P $_ 25
}
})
$ended = @(Events (Query 4634 $types) __ENDS__) + @(Events (Query 4647 $null) __READ__)
$ends = @($ended | ForEach-Object { [pscustomobject]@{ t = Ms $_.TimeCreated; id = P $_ 3 } })
$first = @(Events '*' 1 -Oldest)
[pscustomobject]@{
computer = $env:COMPUTERNAME
canary = $canary
own_ip = $ownIp
winrm_peers = $peers
oldest = if ($first.Count -gt 0) { Ms $first[0].TimeCreated } else { $null }
logons = $logons
ends = $ends
} | ConvertTo-Json -Compress -Depth 4
"""
#: The script: the window, a day for its own logon, and the events read, filled in.
_PS_LOGIN_SESSIONS = (
_PS_SESSIONS_TEMPLATE.replace("__WINDOW_MS__", str(SESSION_WINDOW_DAYS * _DAY_MS))
.replace("__DAY_MS__", str(_DAY_MS))
.replace("__READ__", str(SESSIONS_READ))
.replace("__ENDS__", str(2 * SESSIONS_READ))
)
def _iso(ms: Any) -> str | None:
if not isinstance(ms, int | float) or isinstance(ms, bool):
return None
return datetime.fromtimestamp(ms / 1000, UTC).isoformat()
def _id(value: Any) -> int | None:
"""A logon ID as the event gives it, decimal; None for none or 0 (no linked logon)."""
try:
number = int(str(value))
except ValueError:
return None
return number or None
def _own_address(raw: dict[str, Any]) -> str | None:
"""Where this reading's own WinRM logon came from: its 4624 event's address, else the
one client connected to WinRM."""
own = session_address(raw.get("own_ip")) if raw.get("canary") else None
if own is not None:
return own
peers = {session_address(str(p)) for p in _as_list(raw.get("winrm_peers"))} - {None}
return peers.pop() if len(peers) == 1 else None
def _user(event: dict[str, Any], computer: str) -> str:
user, domain = str(event.get("user") or ""), str(event.get("domain") or "")
return user if not domain or domain.upper() == computer.upper() else f"{domain}\\{user}"
def _address(event: dict[str, Any], tty: str) -> str | None:
address = session_address(event.get("ip"))
if tty == "console" and address is not None:
try:
if ipaddress.ip_address(address).is_loopback:
return None
except ValueError:
return address
return address
def _ends(raw: dict[str, Any]) -> dict[int, list[int]]:
"""Each logon ID's logoffs, in milliseconds: an ID is used again after a restart."""
ends: dict[int, list[int]] = {}
for end in _as_list(raw.get("ends")):
logon, at = _id(end.get("id")), end.get("t")
if logon is not None and isinstance(at, int):
ends.setdefault(logon, []).append(at)
return ends
def _logons(events: list[dict[str, Any]]) -> Iterable[dict[str, Any]]:
"""The 4624 events of a person's interactive logon, one per linked pair."""
seen: set[int] = set()
for event in sorted(events, key=lambda e: int(e["t"])):
logon, linked = _id(event.get("id")), _id(event.get("linked"))
if logon is None or str(event.get("type")) not in LOGON_TYPES:
continue
if not str(event.get("sid") or "").upper().startswith(_PERSON_SIDS):
continue
key = min(logon, linked) if linked else logon
if key not in seen:
seen.add(key)
yield event
def _session(event: dict[str, Any], computer: str, ends: dict[int, list[int]]) -> LoginSessionDict:
tty = LOGON_TYPES[str(event.get("type"))]
started = int(event["t"])
ids = [i for i in (_id(event.get("id")), _id(event.get("linked"))) if i is not None]
ended = [at for i in ids for at in ends.get(i, ()) if at >= started]
return {
"user": _user(event, computer),
"tty": tty,
"address": _address(event, tty),
"started": _iso(started) or "",
"ended": _iso(min(ended)) if ended else None,
}
def _audited_logons(raw: dict[str, Any]) -> list[dict[str, Any]]:
"""The logon events read; raises when the log holds none, not even this reading's own."""
logons = [e for e in _as_list(raw.get("logons")) if isinstance(e, dict)]
if raw.get("canary") is False and not logons:
raise LoginSessionsUnavailable(
"the Security log holds no logon, not even this reading's own: logons are not audited"
)
return [e for e in logons if isinstance(e.get("t"), int)]
def _sessions(
logons: list[dict[str, Any]], raw: dict[str, Any], own: str | None
) -> list[LoginSessionDict]:
"""The sessions newest first, those from *own* left out, at most SESSIONS_READ."""
computer, ends = str(raw.get("computer") or ""), _ends(raw)
sessions = [_session(e, computer, ends) for e in _logons(logons)]
sessions = [s for s in sessions if own is None or s["address"] != own]
sessions.sort(key=lambda s: s["started"], reverse=True)
return sessions[:SESSIONS_READ]
def parse_login_sessions(raw: dict[str, Any]) -> LoginSessionsDict:
"""What :data:`_PS_LOGIN_SESSIONS` emitted, as napalm-device-types' reading.
:raises LoginSessionsUnavailable: when the host does not audit logons.
"""
logons = _audited_logons(raw)
own = _own_address(raw)
return {
"own_address": own,
"sessions": _sessions(logons, raw, own),
"records_since": _iso(raw.get("oldest")),
}
class WindowsLoginSessionsMixin:
"""``get_login_sessions`` for the driver, which carries the script."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def get_login_sessions(self) -> LoginSessionsDict:
"""The console and Remote Desktop logins of the last seven days, newest first, in
napalm-device-types' ``LoginSessionsDict``; see the module.
:raises LoginSessionsUnavailable: when the host does not audit logons.
:raises ValueError: when the reading came back empty.
"""
out = self._run_raw(_PS_LOGIN_SESSIONS).strip()
raw = json.loads(out) if out else None
if not isinstance(raw, dict):
raise ValueError("the login session reading came back empty")
return parse_login_sessions(raw)
+14
View File
@@ -0,0 +1,14 @@
"""Who can log in to a Windows host and who did, for the access review (NetOrk/netork#2895).
:class:`WindowsLoginsMixin` is both readings, :mod:`napalm_windows.login_accounts` and
:mod:`napalm_windows.login_sessions`, as one base of the driver.
"""
from __future__ import annotations
from napalm_windows.login_accounts import WindowsLoginAccountsMixin
from napalm_windows.login_sessions import WindowsLoginSessionsMixin
class WindowsLoginsMixin(WindowsLoginAccountsMixin, WindowsLoginSessionsMixin):
"""``get_login_accounts`` and ``get_login_sessions``; the driver carries the scripts."""
+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")
+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:
+45 -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.logins import WindowsLoginsMixin
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,7 @@ def _is_noise_route(destination: str) -> bool:
# ---------------------------------------------------------------------------
class WindowsDriver(OSDriver):
class WindowsDriver(WindowsLoginsMixin, WindowsScheduledJobsMixin, WindowsTimeSyncMixin, OSDriver):
"""NAPALM driver for Windows Server 2016+ and Windows 10/11.
``optional_args``:
@@ -369,6 +360,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 +436,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 +445,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 +522,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.55.0", # LoginSessionsUnavailable, session_address
"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
+5
View File
@@ -8,3 +8,8 @@ and the Python side is tested against it here.
What they cannot prove is that the scripts produce this shape on a real host
(property names, Windows PowerShell 5.1 serialisation quirks). They are to be
replaced by output recorded from a Windows Server and a Windows 11 client.
`login_accounts_server_de.json` is a German-language domain member and
`login_accounts_client.json` a Windows 11 workgroup client, `login_sessions.json` a
domain member's Security log; their account names, SIDs and addresses are made up
(documentation ranges).
+113
View File
@@ -0,0 +1,113 @@
{
"computer": "WIN11-01",
"domain_role": 0,
"admin": true,
"now": 1764547200000,
"users": [
{
"name": "Administrator",
"sid": "S-1-5-21-1004336348-1177238915-682003330-500",
"enabled": false,
"home": null,
"last_logon": null,
"password_last_set": null,
"password_expires": null,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "Guest",
"sid": "S-1-5-21-1004336348-1177238915-682003330-501",
"enabled": false,
"home": null,
"last_logon": null,
"password_last_set": null,
"password_expires": null,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "DefaultAccount",
"sid": "S-1-5-21-1004336348-1177238915-682003330-503",
"enabled": false,
"home": null,
"last_logon": null,
"password_last_set": null,
"password_expires": null,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "WDAGUtilityAccount",
"sid": "S-1-5-21-1004336348-1177238915-682003330-504",
"enabled": false,
"home": null,
"last_logon": null,
"password_last_set": 1738627200000,
"password_expires": 1766275200000,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "alice",
"sid": "S-1-5-21-1004336348-1177238915-682003330-1001",
"enabled": true,
"home": "C:\\Users\\alice",
"last_logon": 1764543600000,
"password_last_set": 1761955200000,
"password_expires": null,
"account_expires": null,
"bad_passwords": 1,
"locked_out": false
},
{
"name": "bob",
"sid": "S-1-5-21-1004336348-1177238915-682003330-1002",
"enabled": true,
"home": "C:\\Users\\bob",
"last_logon": 1763942400000,
"password_last_set": 1761955200000,
"password_expires": null,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
}
],
"groups": [
{
"sid": "S-1-5-32-544",
"name": "Administrators",
"members": [
{
"path": "WinNT://WORKGROUP/WIN11-01/Administrator",
"class": "User",
"sid": "S-1-5-21-1004336348-1177238915-682003330-500"
},
{
"path": "WinNT://WORKGROUP/WIN11-01/alice",
"class": "User",
"sid": "S-1-5-21-1004336348-1177238915-682003330-1001"
}
]
},
{
"sid": "S-1-5-32-555",
"name": "Remote Desktop Users",
"members": []
}
],
"rights": {
"allow": [
"*S-1-5-32-544",
"*S-1-5-32-555"
],
"deny": []
},
"rdp_deny": "1",
"rdp_deny_policy": null,
"errors": []
}
+147
View File
@@ -0,0 +1,147 @@
{
"computer": "SRV01",
"domain_role": 3,
"admin": true,
"now": 1764547200000,
"users": [
{
"name": "Administrator",
"sid": "S-1-5-21-1004336348-1177238915-682003330-500",
"enabled": true,
"home": "C:\\Users\\Administrator",
"last_logon": 1764374400000,
"password_last_set": 1747267200000,
"password_expires": null,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "Gast",
"sid": "S-1-5-21-1004336348-1177238915-682003330-501",
"enabled": false,
"home": null,
"last_logon": null,
"password_last_set": null,
"password_expires": null,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "DefaultAccount",
"sid": "S-1-5-21-1004336348-1177238915-682003330-503",
"enabled": false,
"home": null,
"last_logon": null,
"password_last_set": null,
"password_expires": null,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "WDAGUtilityAccount",
"sid": "S-1-5-21-1004336348-1177238915-682003330-504",
"enabled": false,
"home": null,
"last_logon": null,
"password_last_set": 1738627200000,
"password_expires": 1766275200000,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "helpdesk",
"sid": "S-1-5-21-1004336348-1177238915-682003330-1001",
"enabled": true,
"home": "C:\\Users\\helpdesk",
"last_logon": 1754179200000,
"password_last_set": 1753315200000,
"password_expires": 1761091200000,
"account_expires": null,
"bad_passwords": 7,
"locked_out": true
},
{
"name": "svc-backup",
"sid": "S-1-5-21-1004336348-1177238915-682003330-1002",
"enabled": true,
"home": null,
"last_logon": 1764460800000,
"password_last_set": 1763683200000,
"password_expires": null,
"account_expires": 1764115200000,
"bad_passwords": null,
"locked_out": null
}
],
"groups": [
{
"sid": "S-1-5-32-544",
"name": "Administratoren",
"members": [
{
"path": "WinNT://CONTOSO/SRV01/Administrator",
"class": "User",
"sid": "S-1-5-21-1004336348-1177238915-682003330-500"
},
{
"path": "WinNT://CONTOSO/Domänen-Admins",
"class": "Group",
"sid": "S-1-5-21-3623811015-3361044348-30300820-512"
},
{
"path": "WinNT://CONTOSO/jdoe",
"class": "User",
"sid": "S-1-5-21-3623811015-3361044348-30300820-1107"
},
{
"path": "WinNT://S-1-5-21-3623811015-3361044348-30300820-1290",
"class": "User",
"sid": "S-1-5-21-3623811015-3361044348-30300820-1290"
}
]
},
{
"sid": "S-1-5-32-555",
"name": "Remotedesktopbenutzer",
"members": [
{
"path": "WinNT://CONTOSO/SRV01/helpdesk",
"class": "User",
"sid": "S-1-5-21-1004336348-1177238915-682003330-1001"
},
{
"path": "WinNT://CONTOSO/RDP-Operators",
"class": "Group",
"sid": "S-1-5-21-3623811015-3361044348-30300820-1301"
}
]
},
{
"sid": "S-1-5-32-546",
"name": "Gäste",
"members": [
{
"path": "WinNT://CONTOSO/SRV01/Gast",
"class": "User",
"sid": "S-1-5-21-1004336348-1177238915-682003330-501"
}
]
}
],
"rights": {
"allow": [
"*S-1-5-32-544",
"*S-1-5-32-555"
],
"deny": [
"*S-1-5-32-546"
]
},
"rdp_deny": "0",
"rdp_deny_policy": null,
"errors": []
}
+109
View File
@@ -0,0 +1,109 @@
{
"computer": "SRV01",
"canary": true,
"own_ip": "198.51.100.2",
"winrm_peers": [
"198.51.100.2"
],
"oldest": 1764288000000,
"logons": [
{
"t": 1764543600000,
"sid": "S-1-5-21-3623811015-3361044348-30300820-1107",
"user": "jdoe",
"domain": "CONTOSO",
"id": "900001",
"type": "10",
"ip": "198.51.100.2",
"linked": "0"
},
{
"t": 1764529200000,
"sid": "S-1-5-21-3623811015-3361044348-30300820-1107",
"user": "jdoe",
"domain": "CONTOSO",
"id": "100001",
"type": "10",
"ip": "192.0.2.10",
"linked": "100002"
},
{
"t": 1764529200000,
"sid": "S-1-5-21-3623811015-3361044348-30300820-1107",
"user": "jdoe",
"domain": "CONTOSO",
"id": "100002",
"type": "10",
"ip": "192.0.2.10",
"linked": "100001"
},
{
"t": 1764529200000,
"sid": "S-1-5-90-0-2",
"user": "DWM-2",
"domain": "Window Manager",
"id": "100003",
"type": "2",
"ip": "-",
"linked": "0"
},
{
"t": 1764529200000,
"sid": "S-1-5-96-0-2",
"user": "UMFD-2",
"domain": "Font Driver Host",
"id": "100004",
"type": "2",
"ip": "-",
"linked": "0"
},
{
"t": 1764453600000,
"sid": "S-1-5-21-1004336348-1177238915-682003330-500",
"user": "Administrator",
"domain": "SRV01",
"id": "200001",
"type": "2",
"ip": "127.0.0.1",
"linked": "0"
},
{
"t": 1764367200000,
"sid": "S-1-5-21-3623811015-3361044348-30300820-1107",
"user": "jdoe",
"domain": "CONTOSO",
"id": "300001",
"type": "11",
"ip": "-",
"linked": "0"
},
{
"t": 1764540000000,
"sid": "S-1-5-21-1004336348-1177238915-682003330-1001",
"user": "helpdesk",
"domain": "SRV01",
"id": "400001",
"type": "10",
"ip": "2001:db8::10",
"linked": "0"
}
],
"ends": [
{
"t": 1764536400000,
"id": "100001"
},
{
"t": 1764536400005,
"id": "100002"
},
{
"t": 1764457200000,
"id": "200001"
},
{
"t": 1764187200000,
"id": "400001"
}
]
}
+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 @@
{"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}
+388
View File
@@ -0,0 +1,388 @@
"""Who can log in to a Windows host: local accounts, administrators, Remote Desktop
(NetOrk/netork#2895).
The reading is one script whose JSON a fake transport answers, from
tests/fixtures/synthetic/login_accounts_server_de.json (a German-language domain
member: "Administratoren", "Remotedesktopbenutzer", a domain group among the
administrators, Remote Desktop on, Guests denied it) and login_accounts_client.json (a
Windows 11 workgroup client, Remote Desktop off). What a real host emits 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_windows import WindowsDriver
from napalm_windows import login_accounts as mod
FIXTURES = Path(__file__).parent / "fixtures" / "synthetic"
MACHINE = "S-1-5-21-1004336348-1177238915-682003330"
DOMAIN = "S-1-5-21-3623811015-3361044348-30300820"
def _raw(name: str) -> dict[str, Any]:
return json.loads((FIXTURES / f"login_accounts_{name}.json").read_text())
class FakeTransport:
def __init__(self, answer: Any) -> None:
self.answer = answer
self.sent: list[str] = []
self.is_open = True
def run(self, script: str) -> str:
self.sent.append(script)
return self.answer if isinstance(self.answer, str) else json.dumps(self.answer)
def close(self) -> None:
self.is_open = False
def _read(raw: Any) -> tuple[dict[str, Any], FakeTransport]:
d = WindowsDriver("win01", "admin", "secret")
host = FakeTransport(raw)
d._transport = host # type: ignore[assignment]
return dict(d.get_login_accounts()), host
def _by_name(reading: dict[str, Any]) -> dict[str, dict[str, Any]]:
return {a["name"]: a for a in reading["accounts"]}
class TestGermanMemberServer:
def test_the_accounts_without_the_systems_own(self):
reading, _ = _read(_raw("server_de"))
assert [a["name"] for a in reading["accounts"]] == [
"Administrator",
"Gast",
"helpdesk",
"svc-backup",
]
def test_uid_is_the_rid_and_sid_the_whole_sid(self):
admin = _by_name(_read(_raw("server_de"))[0])["Administrator"]
assert admin["uid"] == 500
assert admin["sid"] == f"{MACHINE}-500"
assert admin["home"] == "C:\\Users\\Administrator"
assert admin["shell"] == ""
def test_the_last_login_is_the_account_databases(self):
reading, _ = _read(_raw("server_de"))
admin = _by_name(reading)["Administrator"]
assert admin["last_login"] == "2025-11-29T00:00:00+00:00"
assert admin["last_login_source"] == "sam"
assert admin["last_login_from"] is None
assert admin["last_login_port"] is None
assert reading["login_sources"] == ["sam"]
assert _by_name(reading)["Gast"]["last_login"] is None
assert _by_name(reading)["Gast"]["last_login_source"] is None
def test_administrators_are_found_by_sid_not_by_name(self):
"""The group is "Administratoren" here; S-1-5-32-544 finds it all the same."""
accounts = _by_name(_read(_raw("server_de"))[0])
assert accounts["Administrator"]["administrator"] is True
assert accounts["helpdesk"]["administrator"] is False
def test_remote_desktop_by_the_right_and_its_holders(self):
accounts = _by_name(_read(_raw("server_de"))[0])
assert accounts["Administrator"]["remote_desktop"] is True
assert accounts["helpdesk"]["remote_desktop"] is True # Remotedesktopbenutzer
assert accounts["svc-backup"]["remote_desktop"] is False # no group holds it
def test_a_denied_group_wins_over_the_right(self):
raw = _raw("server_de")
raw["groups"][2]["members"].append(
{"path": "WinNT://CONTOSO/SRV01/helpdesk", "class": "User", "sid": f"{MACHINE}-1001"}
)
assert _by_name(_read(raw)[0])["helpdesk"]["remote_desktop"] is False
def test_denying_every_local_account_denies_them_all(self):
"""``Local account`` (S-1-5-113), as Microsoft's security baseline denies it."""
raw = _raw("server_de")
raw["rights"]["deny"].append("*S-1-5-113")
accounts = _by_name(_read(raw)[0])
assert not any(a["remote_desktop"] for a in accounts.values())
def test_a_right_given_to_everyone_reaches_every_account(self):
raw = _raw("server_de")
raw["rights"]["allow"].append("*S-1-1-0")
assert _by_name(_read(raw)[0])["svc-backup"]["remote_desktop"] is True
def test_a_right_given_by_name_counts(self):
raw = _raw("server_de")
raw["rights"]["allow"].append("svc-backup")
assert _by_name(_read(raw)[0])["svc-backup"]["remote_desktop"] is True
def test_locked_disabled_expired_or_locked_out(self):
accounts = _by_name(_read(_raw("server_de"))[0])
assert accounts["Gast"]["locked"] is True # disabled
assert accounts["helpdesk"]["locked"] is True # locked out
assert accounts["svc-backup"]["locked"] is True # expired
assert accounts["Administrator"]["locked"] is False
def test_the_lock_out_not_read_is_none(self):
raw = _raw("server_de")
raw["users"][5]["account_expires"] = None
assert _by_name(_read(raw)[0])["svc-backup"]["locked"] is None
def test_password_and_account_expiry(self):
accounts = _by_name(_read(_raw("server_de"))[0])
assert accounts["Administrator"]["password"] == "set"
assert accounts["Administrator"]["password_changed"] == "2025-05-15"
assert accounts["Administrator"]["password_expires"] == "never"
assert accounts["Administrator"]["account_expires"] == "never"
assert accounts["helpdesk"]["password_expires"] == "2025-10-22"
assert accounts["svc-backup"]["account_expires"] == "2025-11-26"
assert accounts["Gast"]["password"] is None
assert accounts["Gast"]["password_expires"] is None
def test_failed_attempts_since_the_last_login(self):
reading, _ = _read(_raw("server_de"))
accounts = _by_name(reading)
assert accounts["helpdesk"]["failed_logins"] == 7
assert accounts["svc-backup"]["failed_logins"] is None
assert accounts["helpdesk"]["failed_logins_capped"] is False
assert reading["failed_logins_source"] == "sam"
def test_read_as_an_administrator(self):
assert _read(_raw("server_de"))[0]["privileged"] is True
class TestTheGroups:
def test_the_groups_that_grant_administration_or_remote_desktop(self):
groups = _read(_raw("server_de"))[0]["groups"]
assert [(g["name"], g["sid"], g["grants"]) for g in groups] == [
("Administratoren", "S-1-5-32-544", ["administrator", "remote_desktop"]),
("Remotedesktopbenutzer", "S-1-5-32-555", ["remote_desktop"]),
]
def test_a_domain_group_among_the_administrators_by_name(self):
admins = _read(_raw("server_de"))[0]["groups"][0]["members"]
assert admins == [
{
"name": "SRV01\\Administrator",
"sid": f"{MACHINE}-500",
"local": True,
"group": False,
},
{
"name": "CONTOSO\\Domänen-Admins",
"sid": f"{DOMAIN}-512",
"local": False,
"group": True,
},
{"name": "CONTOSO\\jdoe", "sid": f"{DOMAIN}-1107", "local": False, "group": False},
{"name": f"{DOMAIN}-1290", "sid": f"{DOMAIN}-1290", "local": False, "group": False},
]
def test_a_principal_of_the_host_itself_is_local(self):
raw = _raw("server_de")
raw["groups"][1]["members"] = [
{"path": "WinNT://NT-AUTORITÄT/INTERAKTIV", "class": "Group", "sid": "S-1-5-4"}
]
member = _read(raw)[0]["groups"][1]["members"][0]
assert member == {
"name": "NT-AUTORITÄT\\INTERAKTIV",
"sid": "S-1-5-4",
"local": True,
"group": True,
}
def test_without_a_sid_the_path_tells(self):
raw = _raw("server_de")
raw["groups"][1]["members"] = [
{"path": "WinNT://CONTOSO/SRV01/old", "class": "", "sid": None},
{"path": "WinNT://CONTOSO/someone", "class": "User", "sid": None},
{"path": "", "class": "", "sid": None},
]
raw["users"] = []
members = _read(raw)[0]["groups"][1]["members"]
assert [(m["name"], m["local"], m["group"]) for m in members] == [
("SRV01\\old", True, None),
("CONTOSO\\someone", False, False),
("", None, None),
]
def test_a_domain_sid_without_the_hosts_own_is_told_by_its_path(self):
raw = _raw("server_de")
raw["users"] = []
admins = _read(raw)[0]["groups"][0]["members"]
assert [m["local"] for m in admins] == [True, False, False, None]
class TestWindows11Client:
def test_remote_desktop_off_lets_no_one_in(self):
reading, _ = _read(_raw("client"))
accounts = _by_name(reading)
assert {a["remote_desktop"] for a in accounts.values()} == {False}
assert [g["sid"] for g in reading["groups"]] == ["S-1-5-32-544"]
assert reading["groups"][0]["grants"] == ["administrator"]
def test_the_owner_is_an_administrator_the_other_user_is_not(self):
accounts = _by_name(_read(_raw("client"))[0])
assert accounts["alice"]["administrator"] is True
assert accounts["bob"]["administrator"] is False
def test_group_policy_wins_over_the_local_setting(self):
raw = _raw("client")
raw["rdp_deny_policy"] = "0"
accounts = _by_name(_read(raw)[0])
assert accounts["alice"]["remote_desktop"] is True
assert accounts["bob"]["remote_desktop"] is False
class TestNotRead:
def test_rights_not_read_leave_remote_desktop_unknown(self):
raw = _raw("server_de")
raw["rights"] = None
raw["admin"] = False
reading, _ = _read(raw)
assert {a["remote_desktop"] for a in reading["accounts"]} == {None}
assert [g["grants"] for g in reading["groups"]] == [["administrator"]]
assert reading["privileged"] is False
def test_the_remote_desktop_setting_not_read_is_unknown(self):
raw = _raw("server_de")
raw["rdp_deny"] = None
assert {a["remote_desktop"] for a in _read(raw)[0]["accounts"]} == {None}
def test_administrators_not_read_is_unknown(self, caplog):
raw = _raw("server_de")
raw["groups"] = [g for g in raw["groups"] if g["sid"] != "S-1-5-32-544"]
raw["errors"] = ["group S-1-5-32-544: Zugriff verweigert"]
with caplog.at_level("INFO"):
reading, _ = _read(raw)
assert {a["administrator"] for a in reading["accounts"]} == {None}
assert "Zugriff verweigert" in caplog.text
def test_no_failed_attempts_read_has_no_source(self):
raw = _raw("server_de")
for user in raw["users"]:
user["bad_passwords"] = None
assert _read(raw)[0]["failed_logins_source"] is None
def test_one_group_member_arrives_as_an_object(self):
"""ConvertTo-Json writes a one-element array as its element."""
raw = _raw("server_de")
raw["groups"][1]["members"] = raw["groups"][1]["members"][0]
raw["users"] = raw["users"][0]
reading, _ = _read(raw)
assert [a["name"] for a in reading["accounts"]] == ["Administrator"]
assert len(reading["groups"][1]["members"]) == 1
def test_without_get_localuser_the_reading_is_not_supported(self):
raw = _raw("server_de")
raw["users"] = None
with pytest.raises(NotImplementedError, match="Get-LocalUser"):
_read(raw)
@pytest.mark.parametrize("answer", ["", "[]", "null"])
def test_an_empty_answer_raises(self, answer):
with pytest.raises(ValueError, match="empty"):
_read(answer)
def test_an_account_without_a_sid_is_left_out(self):
raw = _raw("server_de")
raw["users"].append({"name": "odd", "sid": None})
raw["users"].append("garbage")
assert "odd" not in _by_name(_read(raw)[0])
class TestDomainController:
def test_its_accounts_are_the_directorys_its_groups_are_read(self):
raw = copy.deepcopy(_raw("server_de"))
raw.update(domain_role=5, users=[])
reading, _ = _read(raw)
assert reading["accounts"] == []
assert reading["login_sources"] == []
assert reading["failed_logins_source"] is None
assert reading["groups"][0]["sid"] == "S-1-5-32-544"
def test_a_domain_controller_without_get_localuser_is_read_all_the_same(self):
raw = _raw("server_de")
raw.update(domain_role=4, users=None)
assert _read(raw)[0]["accounts"] == []
class TestTheScript:
def test_it_is_one_round_trip(self):
_, host = _read(_raw("server_de"))
assert host.sent == [mod._PS_LOGIN_ACCOUNTS]
def test_the_conventions(self):
script = mod._PS_LOGIN_ACCOUNTS
assert "$ErrorActionPreference = 'Stop'" in script
assert "Get-Command -Name Get-LocalUser" in script
assert "ToUnixTimeMilliseconds" in script
assert "ConvertTo-Json -Compress -Depth 6" in script
def test_groups_are_named_by_sid_never_by_their_english_name(self):
script = mod._PS_LOGIN_ACCOUNTS
assert "'S-1-5-32-544'" in script and "'S-1-5-32-555'" in script
assert "Translate([Security.Principal.NTAccount])" in script
assert "WinNT://' + $env:COMPUTERNAME + '/Administrators" not in script
def test_it_reads_no_secret_and_leaves_nothing_behind(self):
"""The only file is secedit's export of the user rights, removed in ``finally``."""
script = mod._PS_LOGIN_ACCOUNTS
assert "/areas USER_RIGHTS" in script
assert "finally { Remove-Item -LiteralPath $cfg" in script
for verb in (
"Set-LocalUser",
"Add-LocalGroupMember",
"net user",
"SetPassword",
"/configure",
):
assert verb not in script
def test_a_native_command_runs_inside_cmd_with_stderr_merged(self):
"""A line on stderr would be an error record in a remote session (time_sync.py)."""
assert "cmd.exe /c ('secedit " in mod._PS_LOGIN_ACCOUNTS
assert "' 2>&1')" in mod._PS_LOGIN_ACCOUNTS
+290
View File
@@ -0,0 +1,290 @@
"""The logins a Windows host recorded: console and Remote Desktop, from the Security log
(NetOrk/netork#2895).
The reading is one script whose JSON a fake transport answers, from
tests/fixtures/synthetic/login_sessions.json: a domain member with a Remote Desktop logon
of an administrator (two linked events), its window manager's and font driver's logons, a
local console logon, a cached one, one over IPv6 and one from the reading's own address.
What a real host emits the fixtures cannot prove -- see the README there.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_device_types import LoginSessionsUnavailable
from napalm_windows import WindowsDriver
from napalm_windows import login_sessions as mod
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "login_sessions.json"
def _raw() -> dict[str, Any]:
return json.loads(FIXTURE.read_text())
class FakeTransport:
def __init__(self, answer: Any) -> None:
self.answer = answer
self.sent: list[str] = []
self.is_open = True
def run(self, script: str) -> str:
self.sent.append(script)
return self.answer if isinstance(self.answer, str) else json.dumps(self.answer)
def close(self) -> None:
self.is_open = False
def _read(raw: Any) -> tuple[dict[str, Any], FakeTransport]:
d = WindowsDriver("srv01", "admin", "secret")
host = FakeTransport(raw)
d._transport = host # type: ignore[assignment]
return dict(d.get_login_sessions()), host
class TestTheSessions:
def test_console_and_remote_desktop_newest_first(self):
reading, _ = _read(_raw())
assert [(s["user"], s["tty"], s["address"]) for s in reading["sessions"]] == [
("helpdesk", "rdp", "2001:db8::10"),
("CONTOSO\\jdoe", "rdp", "192.0.2.10"),
("Administrator", "console", None),
("CONTOSO\\jdoe", "console", None),
]
def test_an_administrators_two_linked_logons_are_one_session(self):
rdp = _read(_raw())[0]["sessions"][1]
assert rdp == {
"user": "CONTOSO\\jdoe",
"tty": "rdp",
"address": "192.0.2.10",
"started": "2025-11-30T19:00:00+00:00",
"ended": "2025-11-30T21:00:00+00:00",
}
def test_the_window_manager_and_font_driver_are_no_one(self):
users = {s["user"] for s in _read(_raw())[0]["sessions"]}
assert not {"DWM-2", "UMFD-2"} & {u.split("\\")[-1] for u in users}
def test_the_hosts_own_accounts_go_by_name_alone(self):
users = [s["user"] for s in _read(_raw())[0]["sessions"]]
assert "Administrator" in users and "SRV01\\Administrator" not in users
def test_a_console_logon_ended_by_its_logoff(self):
console = _read(_raw())[0]["sessions"][2]
assert console["started"] == "2025-11-29T22:00:00+00:00"
assert console["ended"] == "2025-11-29T23:00:00+00:00"
def test_a_logon_still_running_has_no_end(self):
assert _read(_raw())[0]["sessions"][3]["ended"] is None
def test_a_logoff_before_the_logon_is_an_earlier_boots(self):
"""A logon ID is used again after a restart."""
assert _read(_raw())[0]["sessions"][0]["ended"] is None
def test_a_network_logon_or_an_unlock_is_not_a_session(self):
raw = _raw()
for kind in ("3", "7"):
raw["logons"].append(
{
"t": raw["oldest"],
"sid": "S-1-5-21-1-2-3-1001",
"user": "x",
"domain": "SRV01",
"id": f"5{kind}",
"type": kind,
"ip": "192.0.2.99",
"linked": "0",
}
)
assert all(s["user"] != "x" for s in _read(raw)[0]["sessions"])
def test_an_entra_id_account_is_a_person(self):
raw = _raw()
raw["logons"] = [
{
"t": raw["oldest"],
"sid": "S-1-12-1-111-222-333-444",
"user": "alice@contoso.com",
"domain": "AzureAD",
"id": "77",
"type": "2",
"ip": "-",
"linked": None,
}
]
assert [s["user"] for s in _read(raw)[0]["sessions"]] == ["AzureAD\\alice@contoso.com"]
def test_an_event_without_an_id_or_a_time_is_skipped(self):
raw = _raw()
raw["logons"] = [
{
"t": raw["oldest"],
"sid": "S-1-5-21-1-2-3-1001",
"user": "x",
"domain": "",
"id": "",
"type": "2",
"ip": "-",
"linked": "0",
},
{
"t": None,
"sid": "S-1-5-21-1-2-3-1001",
"user": "y",
"domain": "",
"id": "9",
"type": "2",
"ip": "-",
"linked": "0",
},
"garbage",
]
raw["ends"] = [{"t": None, "id": "9"}, {"t": 1, "id": None}]
assert _read(raw)[0]["sessions"] == []
def test_a_remote_desktop_logon_from_the_loopback_keeps_it(self):
raw = _raw()
raw["logons"] = [
{
"t": raw["oldest"],
"sid": "S-1-5-21-1-2-3-1001",
"user": "x",
"domain": "",
"id": "8",
"type": "10",
"ip": "127.0.0.1",
"linked": "0",
},
{
"t": raw["oldest"],
"sid": "S-1-5-21-1-2-3-1001",
"user": "y",
"domain": "",
"id": "9",
"type": "2",
"ip": "workstation-7",
"linked": "0",
},
]
sessions = {s["user"]: s["address"] for s in _read(raw)[0]["sessions"]}
assert sessions == {"x": "127.0.0.1", "y": "workstation-7"}
def test_the_cap(self, monkeypatch):
monkeypatch.setattr(mod, "SESSIONS_READ", 2)
assert len(_read(_raw())[0]["sessions"]) == 2
class TestOwnAddress:
def test_the_readings_own_winrm_logon_names_it(self):
reading, _ = _read(_raw())
assert reading["own_address"] == "198.51.100.2"
def test_its_remote_desktop_sessions_are_left_out(self):
reading, _ = _read(_raw())
assert all(s["address"] != "198.51.100.2" for s in reading["sessions"])
def test_without_an_address_on_its_logon_the_one_winrm_client(self):
raw = _raw()
raw.update(own_ip="-", winrm_peers=["::ffff:198.51.100.2"])
assert _read(raw)[0]["own_address"] == "198.51.100.2"
def test_several_winrm_clients_name_none(self):
raw = _raw()
raw.update(canary=None, own_ip=None, winrm_peers=["198.51.100.2", "198.51.100.3"])
reading, _ = _read(raw)
assert reading["own_address"] is None
assert len(reading["sessions"]) == 5
def test_one_winrm_client_arrives_as_a_string(self):
raw = _raw()
raw.update(canary=None, own_ip=None, winrm_peers="198.51.100.4")
assert _read(raw)[0]["own_address"] == "198.51.100.4"
class TestCoverage:
def test_the_oldest_event_the_log_holds(self):
assert _read(_raw())[0]["records_since"] == "2025-11-28T00:00:00+00:00"
def test_an_empty_log_has_none(self):
raw = _raw()
raw["oldest"] = None
assert _read(raw)[0]["records_since"] is None
def test_no_logon_not_even_its_own_is_no_audit(self):
raw = _raw()
raw.update(canary=False, logons=[])
with pytest.raises(LoginSessionsUnavailable, match="not audited"):
_read(raw)
def test_its_own_logon_not_found_with_others_is_read(self):
raw = _raw()
raw["canary"] = False
reading, _ = _read(raw)
assert reading["own_address"] == "198.51.100.2" # the one WinRM client
assert len(reading["sessions"]) == 4
def test_no_logon_while_its_own_was_not_looked_for_is_nobody(self):
raw = _raw()
raw.update(canary=None, logons=[])
assert _read(raw)[0]["sessions"] == []
@pytest.mark.parametrize("answer", ["", "[]"])
def test_an_empty_answer_raises(self, answer):
with pytest.raises(ValueError, match="empty"):
_read(answer)
class TestTheScript:
def test_it_is_one_round_trip(self):
_, host = _read(_raw())
assert host.sent == [mod._PS_LOGIN_SESSIONS]
def test_no_match_is_none_not_an_error(self):
assert "NoMatchingEventsFound" in mod._PS_LOGIN_SESSIONS
def test_the_window_is_bounded_on_the_host(self):
script = mod._PS_LOGIN_SESSIONS
assert "timediff(@SystemTime) <= 604800000" in script
assert "-MaxEvents $max" in script
assert "__" not in script
def test_only_console_remote_desktop_and_cached_logons(self):
script = mod._PS_LOGIN_SESSIONS
assert "$types = (Logon 2) + ' or ' + (Logon 10) + ' or ' + (Logon 11)" in script
assert "Logon 3" not in script and "Logon 7" not in script
def test_the_conventions(self):
script = mod._PS_LOGIN_SESSIONS
assert "$ErrorActionPreference = 'Stop'" in script
assert "ToUnixTimeMilliseconds" in script
assert "Clear-EventLog" not in script and "wevtutil" not in script
+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
+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]
+7 -2
View File
@@ -5,7 +5,8 @@
Asks for the password, runs every getter script over one WinRM connection and
writes the raw JSON to tools/harvest-out/<label>/<fixture>.json — the same file
names as tests/fixtures/synthetic/. harvest-out/ is gitignored: scrub serials,
MAC and IP addresses and host names before copying anything into tests/.
MAC and IP addresses, host names, account names and SIDs before copying anything into
tests/.
"""
from __future__ import annotations
@@ -14,7 +15,7 @@ import argparse
import getpass
import pathlib
from napalm_windows import WindowsDriver
from napalm_windows import WindowsDriver, login_accounts, login_sessions, scheduled_tasks, time_sync
from napalm_windows import windows as mod
SCRIPTS = {
@@ -25,6 +26,10 @@ 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,
"login_accounts": login_accounts._PS_LOGIN_ACCOUNTS,
"login_sessions": login_sessions._PS_LOGIN_SESSIONS,
}
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()