Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
89a52db1a5 | ||
|
|
21a21383ff | ||
|
|
84f6a3c3e3 | ||
|
|
977ddbd904 | ||
|
|
d7511efd43 | ||
|
|
442541d30a | ||
|
|
0b30ab00a5 | ||
|
|
37708009a0 | ||
|
|
74a8c53c7c | ||
|
|
a508b872b0 | ||
|
|
581c2df5e8 | ||
|
|
dacefaa606 | ||
|
|
7c985acfad | ||
|
|
cd50d3c102 | ||
|
|
15740f9e05 |
No files matched your search
@@ -6,6 +6,75 @@ All notable changes to this driver. The format follows
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- What the event log recorded that says something is wrong with the host
|
||||
(NetOrk/netork#2897): `get_host_events(since=None)`, napalm-device-types'
|
||||
`HostEventsMixin`. Unexpected shutdowns (Kernel-Power 41, EventLog 6008), bugchecks
|
||||
with their stop code (1001), fatal and corrected hardware errors (WHEA-Logger 18, 19,
|
||||
47), disk and file system errors (disk 7 and 153, Ntfs 55), crashing programs
|
||||
(Application Error 1000) and services that ended unexpectedly (Service Control
|
||||
Manager 7031, 7034), over the last seven days by default, in one script of three
|
||||
queries bounded by time and count. An empty log is no events, not an error
|
||||
(`NoMatchingEventsFound` is caught); a query that fails names its kinds `unread`.
|
||||
- The event channels as the host's log sources: `get_log_sources()` lists every channel
|
||||
that is switched on and holds records as a source of kind `eventlog`, named by its
|
||||
channel, with its `.evtx` file, size and last write (`Get-WinEvent -ListLog *`).
|
||||
Analytic and debug channels are left out.
|
||||
- `get_services()` says how each service's last run ended (`result`, `exit_code`, from
|
||||
`Win32_Service.ExitCode` and `ServiceSpecificExitCode`), whether a trigger starts it
|
||||
(`trigger_start`) and the account it runs as (`account`), so that an automatic service
|
||||
that died is told from one stopped on purpose. It moves into `WindowsServicesMixin`.
|
||||
- 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.
|
||||
|
||||
@@ -36,14 +36,102 @@ handshake once.
|
||||
| `get_interfaces_ip` | `Get-NetIPAddress` (loopback dropped, IPv6 zone index stripped) |
|
||||
| `get_arp_table` | `Get-NetNeighbor -AddressFamily IPv4` (broadcast, multicast, unreachable dropped) |
|
||||
| `get_route_to` | `Get-NetRoute` (multicast, broadcast, loopback dropped) |
|
||||
| `get_services` / `manage_service` | `Win32_Service`, `Start-/Stop-/Restart-Service`, `Set-Service -StartupType` |
|
||||
| `get_services` / `manage_service` | `Win32_Service` (with `ExitCode`, `StartName`) and the services' `TriggerInfo` registry keys, `Start-/Stop-/Restart-Service`, `Set-Service -StartupType`. See *Services* |
|
||||
| `reboot_host` / `shutdown_host` | `Restart-Computer`, `Stop-Computer`, neither with `-Force`: programs are asked to close, and Windows refuses while other users are logged on. A connection the host drops before answering counts as accepted |
|
||||
| `get_listening_sockets` | `Get-NetTCPConnection -State Listen`, `Get-NetUDPEndpoint`, `Get-Process`, `Win32_Service` (a shared svchost names no service) |
|
||||
| `get_scheduled_jobs` | `Get-ScheduledTask` + `Get-ScheduledTaskInfo`, one script; `\Microsoft\*` is `platform`, other tasks `admin`, the root task an application wrote `application`; time zone mapped to IANA for the common zones |
|
||||
| `manage_scheduled_job` | `Enable-`/`Disable-ScheduledTask`, `Start-ScheduledTask` (returns once started; the result shows in the next reading) |
|
||||
| `put_scheduled_job` / `delete_scheduled_job` | `Register-ScheduledTask -Xml -Force` in the root folder, `Unregister-ScheduledTask`; an application's tasks only |
|
||||
| `get_host_events` | `Get-WinEvent -FilterXPath`, three bounded queries over the System and Application logs. See *Host events* |
|
||||
| `get_log_sources` | `Get-WinEvent -ListLog *`: every event channel switched on and holding records, as kind `eventlog` |
|
||||
| `get_time_sync` / `configure_time_sync` | w32time's registry values (group policy first), `w32tm /query /status`, the registry's `TimeZoneInformation`; writes `NtpServer`/`Type` + `w32tm /config /update`, `Set-TimeZone`. See *Time sync* |
|
||||
|
||||
`running_kernel` carries the full build including the update revision
|
||||
(`10.0.20348.2340`): Windows ships fixes as UBR bumps, which is what CVE
|
||||
matching has to compare against.
|
||||
|
||||
Not yet: packages, Windows Update, scheduled tasks, health metrics, Hyper-V.
|
||||
### Scheduled tasks
|
||||
|
||||
An application's own job is the task `\<name>` in the root folder, never a folder of
|
||||
its own. Its description is `napalm-scheduled-job: <name> <description>` and a second
|
||||
line `schedule: <cron expression>`, so the reading gives back the cron expression and
|
||||
the command it was written with; its digest also covers the triggers, so triggers
|
||||
changed by hand count as a change.
|
||||
|
||||
* **Command:** `cmd.exe /d /s /c "<command>"` — one line, as a Windows command line.
|
||||
* **Principal:** `SYSTEM`, or a local user who runs it whether logged on or not
|
||||
without a stored password (`S4U`). Such a run has no network credentials, and the
|
||||
user needs the "Log on as a batch job" right.
|
||||
* **Schedule:** a cron expression becomes triggers only where Task Scheduler can
|
||||
express it exactly — daily, weekly on weekdays, or monthly on days of the month (in
|
||||
some months); at one or more times, or evenly spaced times as one repetition
|
||||
(`*/5`, `*/15 8-17`, `0 */6`), or one repeating trigger per hour (`*/7`); at most 48
|
||||
triggers. `@reboot` is a boot trigger. Refused, naming why: both a day of the month
|
||||
and a weekday (cron's *either* rule), a weekday together with days or months, and
|
||||
times needing more than 48 triggers. A repetition counts elapsed time, so on the day
|
||||
summer time starts or ends its later runs shift by the hour.
|
||||
* **Not read:** which software installed a task (Windows does not record it), so a
|
||||
vendor's updater is `admin`; and the days of a monthly trigger, which
|
||||
`Get-ScheduledTask` does not expose.
|
||||
|
||||
### Time sync
|
||||
|
||||
napalm-device-types' `TimeSyncMixin`; both the servers and the zone are written.
|
||||
|
||||
* **Servers** are w32time's `NtpServer` in order, without their `,0x` flags; group
|
||||
policy's values (`HKLM\SOFTWARE\Policies\Microsoft\W32Time\Parameters`) win over
|
||||
the local ones. `Type NoSync` has none. Written as `<server>,0x8` (client mode) with
|
||||
`Type NTP` — what `w32tm /config /manualpeerlist /syncfromflags:manual` writes —
|
||||
then `w32tm /config /update`; a stopped Windows Time service is started first.
|
||||
* **Domain members** that take their time from the domain hierarchy (`Type NT5DS` or
|
||||
`AllSync`) report the servers configured, and a write is refused: the domain sets
|
||||
their time. So is a write where group policy sets w32time.
|
||||
* **Synchronised** is the leap indicator of `w32tm /query /status` (`3` = not
|
||||
synchronised); a stopped service is not synchronised. `daemon` is `w32time`.
|
||||
* **Zone:** Windows keeps a Windows zone (`W. Europe Standard Time`), which stands
|
||||
for several IANA zones. It is read as the zone CLDR names for it (`Europe/Berlin`)
|
||||
and written with `Set-TimeZone` from CLDR's mapping
|
||||
([`windowsZones.xml`](https://github.com/unicode-org/cldr/blob/release-49/common/supplemental/windowsZones.xml),
|
||||
generated into `napalm_windows/_windows_zones.py` by `tools/windows_zones.py`,
|
||||
never fetched at runtime). The IANA name written is kept in
|
||||
`HKLM\SOFTWARE\napalm-windows` (`IanaTimeZone`) and read back while the host is
|
||||
still in that Windows zone, so `Europe/Vienna` reads back as `Europe/Vienna`. A
|
||||
zone with summer time switched off reads as `None`; writing the zone switches it
|
||||
back on.
|
||||
|
||||
### Services
|
||||
|
||||
How a service's last run ended is `Win32_Service.ExitCode`, said in systemd's words
|
||||
(napalm-device-types' `ServiceDict.result`): `0` is `success`, `1077` (never started
|
||||
since boot: a demand-start service, or a delayed one in the minutes after boot) is no
|
||||
result, `1066` is `exit-code` with the service's own `ServiceSpecificExitCode`, any
|
||||
other code `exit-code` with that code (`1067`: the process ended without being
|
||||
stopped). Both codes leave the host as `[int64]`: they are UInt32, and an HRESULT
|
||||
would not fit `[int]`. `trigger_start` is a `TriggerInfo` key under the service, read
|
||||
once for all of them; `account` is `StartName`.
|
||||
|
||||
### Host events
|
||||
|
||||
napalm-device-types' `HostEventsMixin`: what the event log recorded that says
|
||||
something is wrong with the host, over the last seven days unless the caller names a
|
||||
start. One script, three queries, each an XPath filter from the start on, newest
|
||||
first and bounded by count:
|
||||
|
||||
| Query | Events | Bound |
|
||||
|---|---|---|
|
||||
| System, with messages | Kernel-Power 41 and EventLog 6008 (unexpected shutdown; 41's `BugcheckCode` as the stop code), WER-SystemErrorReporting 1001 (bugcheck, its stop code), WHEA-Logger 18 (fatal hardware error), disk 7 (bad block), Ntfs 55 (corruption, its volume) | 100 |
|
||||
| System, without messages | WHEA-Logger 19 and 47 (corrected hardware errors), disk 153 (retried I/O, its disk), Service Control Manager 7031 and 7034 (a service that ended unexpectedly, its display name) | 500 |
|
||||
| Application, without messages | Application Error 1000 (a program that crashed, its path) | 200 |
|
||||
|
||||
`Get-WinEvent` throws `NoMatchingEventsFound` when nothing matches; each query
|
||||
catches it as no events, and any other failure costs only that query, whose kinds the
|
||||
reading names `unread`. A query that returned its bound names its kinds `capped`.
|
||||
What an event is about comes from its properties, never from its message, which is in
|
||||
the host's language; messages are read only for the rare events (Windows formats them
|
||||
slowly) and cut to 300 characters. Which of them is worth a warning is the
|
||||
application's to say.
|
||||
|
||||
Not yet: packages, Windows Update, health metrics, Hyper-V.
|
||||
See netork#300 for the plan.
|
||||
|
||||
## Preparing a host
|
||||
|
||||
@@ -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}'"
|
||||
@@ -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",
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
"""The event channels as the host's log sources (NetOrk/netork#2897).
|
||||
|
||||
:class:`WindowsLogSourcesMixin` gives the driver ``get_log_sources`` in napalm-device-types'
|
||||
shape (``LogSourcesDict``). A Windows host keeps no journal and its programs hold no log
|
||||
files a reader could name: its logs are its event channels, each a source of kind
|
||||
``eventlog`` named by its channel -- the name CrowdSec (``event_channel``) and Wazuh
|
||||
(``eventchannel``) read it by -- with its ``.evtx`` file as ``path``.
|
||||
|
||||
One script, ``Get-WinEvent -ListLog *``: every channel that is switched on and holds
|
||||
records, with its file (``%SystemRoot%`` expanded), size, last write and type. A channel
|
||||
the account may not open is skipped, not the reading. Analytic and debug channels are
|
||||
trace sessions written to ``.etl`` files, which a log reader cannot follow, and are left
|
||||
out. WinRM needs an administrator, who may open every other channel, the Security log
|
||||
included, so the reading is ``attributed``. Where the logs go beyond the host (Windows
|
||||
Event Forwarding, an agent) is not read: ``forwarding`` is None.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types import LogSourceDict, LogSourcesDict, eventlog_source
|
||||
|
||||
from napalm_windows._powershell import _as_list
|
||||
|
||||
_PS_EVENT_CHANNELS = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
ConvertTo-Json -Compress -Depth 3 -InputObject @(
|
||||
Get-WinEvent -ListLog * -ErrorAction SilentlyContinue |
|
||||
Where-Object { $_.IsEnabled -and $_.RecordCount } |
|
||||
ForEach-Object {
|
||||
[pscustomobject]@{
|
||||
channel = $_.LogName
|
||||
path = [Environment]::ExpandEnvironmentVariables([string]$_.LogFilePath)
|
||||
size = $_.FileSize
|
||||
modified = if ($_.LastWriteTime) {
|
||||
([DateTimeOffset]$_.LastWriteTime).ToUnixTimeSeconds()
|
||||
} else { $null }
|
||||
records = $_.RecordCount
|
||||
type = [string]$_.LogType
|
||||
}
|
||||
}
|
||||
)
|
||||
"""
|
||||
|
||||
#: Trace sessions, not logs: written to .etl files a reader cannot follow.
|
||||
_TRACE_TYPES = frozenset({"analytic", "debug"})
|
||||
|
||||
|
||||
def _is_log(raw: dict[str, Any]) -> bool:
|
||||
return (
|
||||
bool(raw.get("channel"))
|
||||
and int(raw.get("records") or 0) > 0
|
||||
and str(raw.get("type") or "").lower() not in _TRACE_TYPES
|
||||
)
|
||||
|
||||
|
||||
def _source(raw: dict[str, Any]) -> LogSourceDict:
|
||||
size, modified = raw.get("size"), raw.get("modified")
|
||||
return eventlog_source(
|
||||
str(raw["channel"]),
|
||||
str(raw["path"]) if raw.get("path") else None,
|
||||
None if size is None else int(size),
|
||||
None if modified is None else float(modified),
|
||||
)
|
||||
|
||||
|
||||
class WindowsLogSourcesMixin:
|
||||
"""``get_log_sources``: the host's event channels; the driver carries the script."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_ps(self, script: str) -> Any: ...
|
||||
|
||||
def get_log_sources(self) -> LogSourcesDict:
|
||||
"""Every event channel that is switched on and holds records, sorted by name.
|
||||
|
||||
* attributed (bool) - always True: an administrator opens every channel
|
||||
* journald (bool) - always False: Windows keeps event channels, not a journal
|
||||
* sources (list) - one ``eventlog`` source per channel
|
||||
* forwarding - None: where the logs go beyond the host is not read
|
||||
"""
|
||||
channels = [c for c in _as_list(self._run_ps(_PS_EVENT_CHANNELS)) if _is_log(c)]
|
||||
sources = sorted((_source(c) for c in channels), key=lambda s: s.get("channel", ""))
|
||||
return {"attributed": True, "journald": False, "sources": sources, "forwarding": None}
|
||||
@@ -0,0 +1,254 @@
|
||||
"""What the event log recorded that says something is wrong with the host (NetOrk/netork#2897).
|
||||
|
||||
:class:`WindowsHostEventsMixin` implements napalm-device-types'
|
||||
:class:`~napalm_device_types.host_events.HostEventsMixin` for the driver, which carries
|
||||
the script across ``PsrpTransport.run``.
|
||||
|
||||
**One script, three queries**, each an XPath filter over a fixed set of providers and
|
||||
event IDs, from the reading's start (``TimeCreated[@SystemTime>=…]``), newest first and
|
||||
bounded by count:
|
||||
|
||||
* *rare*, the System log, with each event's message: Kernel-Power 41 and EventLog 6008
|
||||
(an unexpected shutdown; 41's first property is the bugcheck code, 0 for a power loss),
|
||||
WER-SystemErrorReporting 1001 (a bugcheck, its stop code first), WHEA-Logger 18 (a
|
||||
fatal hardware error), disk 7 (a bad block) and Ntfs 55 (a corruption);
|
||||
* *frequent*, the System log without messages, which Windows formats slowly: WHEA-Logger
|
||||
19 and 47 (corrected hardware errors), disk 153 (a retried I/O) and Service Control
|
||||
Manager 7031 and 7034 (a service that ended unexpectedly);
|
||||
* *apps*, the Application log without messages: Application Error 1000 (a program that
|
||||
crashed, its path the eleventh property).
|
||||
|
||||
``Get-WinEvent`` throws ``NoMatchingEventsFound`` when nothing matches, and under
|
||||
``$ErrorActionPreference = 'Stop'`` that would fail the whole reading: each query
|
||||
catches it as no events. Any other failure costs only that query, whose kinds the
|
||||
reading names ``unread``; a query that returned its bound names its kinds ``capped``.
|
||||
|
||||
**What an event is about** is taken from its properties, which do not depend on the
|
||||
host's language, never from its message, which does: the stop code, the disk or volume,
|
||||
the program's path (its name on a Windows that records no path), the service's display
|
||||
name. The message is kept as the host wrote it, cut short.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from datetime import UTC, datetime
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types import HOST_EVENT_KINDS, HostEventDict, HostEventsDict, HostEventsMixin
|
||||
from napalm_device_types import host_event as _event
|
||||
from napalm_device_types.host_events import (
|
||||
APP_CRASH,
|
||||
DISK_ERROR,
|
||||
HARDWARE_ERROR_CORRECTED,
|
||||
HARDWARE_ERROR_FATAL,
|
||||
HOST_EVENT_MESSAGE_CHARS,
|
||||
HOST_EVENT_WINDOW_DAYS,
|
||||
SERVICE_CRASH,
|
||||
SYSTEM_CRASH,
|
||||
UNEXPECTED_SHUTDOWN,
|
||||
)
|
||||
|
||||
from napalm_windows._powershell import _as_list
|
||||
|
||||
_KERNEL_POWER = "Microsoft-Windows-Kernel-Power"
|
||||
_BUGCHECK = "Microsoft-Windows-WER-SystemErrorReporting"
|
||||
_WHEA = "Microsoft-Windows-WHEA-Logger"
|
||||
_SCM = "Service Control Manager"
|
||||
_APP_ERROR = "Application Error"
|
||||
|
||||
|
||||
def _bugcheck(props: list[str]) -> str | None:
|
||||
"""Kernel-Power 41's ``BugcheckCode``, a decimal number, as a stop code; 0 is none."""
|
||||
word = props[0].strip() if props else ""
|
||||
return f"0x{int(word):08x}" if word.isdigit() and int(word) else None
|
||||
|
||||
|
||||
def _stop_code(props: list[str]) -> str | None:
|
||||
"""1001's first property: ``0x0000009f (0x…, 0x…, 0x…, 0x…)``."""
|
||||
word = props[0].split(maxsplit=1)[0] if props and props[0].strip() else ""
|
||||
return word or None
|
||||
|
||||
|
||||
def _first(props: list[str]) -> str | None:
|
||||
return props[0] if props else None
|
||||
|
||||
|
||||
def _program(props: list[str]) -> str | None:
|
||||
"""Application Error 1000: its path where the host records one, else its name."""
|
||||
path = props[10] if len(props) > 10 else ""
|
||||
return path.strip() or _first(props)
|
||||
|
||||
|
||||
def _none(props: list[str]) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
_Subject = Callable[[list[str]], str | None]
|
||||
|
||||
#: (provider, event ID) -> the kind and what the event is about.
|
||||
_EVENTS: dict[tuple[str, int], tuple[str, _Subject]] = {
|
||||
(_KERNEL_POWER, 41): (UNEXPECTED_SHUTDOWN, _bugcheck),
|
||||
("EventLog", 6008): (UNEXPECTED_SHUTDOWN, _none),
|
||||
(_BUGCHECK, 1001): (SYSTEM_CRASH, _stop_code),
|
||||
(_WHEA, 18): (HARDWARE_ERROR_FATAL, _none),
|
||||
(_WHEA, 19): (HARDWARE_ERROR_CORRECTED, _none),
|
||||
(_WHEA, 47): (HARDWARE_ERROR_CORRECTED, _none),
|
||||
("disk", 7): (DISK_ERROR, _first),
|
||||
("disk", 153): (DISK_ERROR, _first),
|
||||
("Microsoft-Windows-Ntfs", 55): (DISK_ERROR, _first),
|
||||
("Ntfs", 55): (DISK_ERROR, _first),
|
||||
(_SCM, 7031): (SERVICE_CRASH, _first),
|
||||
(_SCM, 7034): (SERVICE_CRASH, _first),
|
||||
(_APP_ERROR, 1000): (APP_CRASH, _program),
|
||||
}
|
||||
|
||||
#: Each query's log, its events, its bound and whether it reads their messages.
|
||||
_QUERIES: dict[str, tuple[str, tuple[tuple[str, int], ...], int, bool]] = {
|
||||
"rare": (
|
||||
"System",
|
||||
(
|
||||
(_KERNEL_POWER, 41),
|
||||
("EventLog", 6008),
|
||||
(_BUGCHECK, 1001),
|
||||
(_WHEA, 18),
|
||||
("disk", 7),
|
||||
("Microsoft-Windows-Ntfs", 55),
|
||||
("Ntfs", 55),
|
||||
),
|
||||
100,
|
||||
True,
|
||||
),
|
||||
"frequent": (
|
||||
"System",
|
||||
((_WHEA, 19), (_WHEA, 47), ("disk", 153), (_SCM, 7031), (_SCM, 7034)),
|
||||
500,
|
||||
False,
|
||||
),
|
||||
"apps": ("Application", ((_APP_ERROR, 1000),), 200, False),
|
||||
}
|
||||
|
||||
#: The kinds each query reads, in the order of HOST_EVENT_KINDS.
|
||||
_PART_KINDS: dict[str, tuple[str, ...]] = {
|
||||
part: tuple(k for k in HOST_EVENT_KINDS if k in {_EVENTS[e][0] for e in events})
|
||||
for part, (_log, events, _max, _message) in _QUERIES.items()
|
||||
}
|
||||
|
||||
# Q runs one query: its events with their properties as strings, or why not.
|
||||
# $_ inside catch is the error; NoMatchingEventsFound is an empty log, not a failure.
|
||||
_PS_QUERY = rf"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
function Q($log, $xpath, $max, $withMessage) {{
|
||||
try {{
|
||||
$rows = @(Get-WinEvent -LogName $log -FilterXPath $xpath -MaxEvents $max | ForEach-Object {{
|
||||
$m = $null
|
||||
if ($withMessage) {{
|
||||
try {{ $m = [string]$_.Message }} catch {{ $m = $null }}
|
||||
if ($m.Length -gt {HOST_EVENT_MESSAGE_CHARS}) {{
|
||||
$m = $m.Substring(0, {HOST_EVENT_MESSAGE_CHARS})
|
||||
}}
|
||||
}}
|
||||
[pscustomobject]@{{
|
||||
provider = $_.ProviderName
|
||||
id = [int]$_.Id
|
||||
time = ([DateTimeOffset]$_.TimeCreated).ToUnixTimeSeconds()
|
||||
props = @($_.Properties | Select-Object -First 11 |
|
||||
ForEach-Object {{ [string]$_.Value }})
|
||||
message = $m
|
||||
}}
|
||||
}})
|
||||
[pscustomobject]@{{ ok = $true; capped = ($rows.Count -ge $max); events = $rows }}
|
||||
}} catch {{
|
||||
if ([string]$_.FullyQualifiedErrorId -like 'NoMatchingEventsFound*') {{
|
||||
[pscustomobject]@{{ ok = $true; capped = $false; events = @() }}
|
||||
}} else {{
|
||||
[pscustomobject]@{{
|
||||
ok = $false; capped = $false; events = @(); error = [string]$_.Exception.Message
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
"""
|
||||
|
||||
|
||||
def _xpath(events: tuple[tuple[str, int], ...], since: str) -> str:
|
||||
which = " or ".join(f"(Provider[@Name='{p}'] and EventID={i})" for p, i in events)
|
||||
return f"*[System[TimeCreated[@SystemTime>='{since}'] and ({which})]]"
|
||||
|
||||
|
||||
def host_events_script(since: float) -> str:
|
||||
"""The reading's script, from *since* (unix seconds) on."""
|
||||
start = datetime.fromtimestamp(since, UTC).strftime("%Y-%m-%dT%H:%M:%S.000Z")
|
||||
lines = [_PS_QUERY]
|
||||
parts = []
|
||||
for part, (log, events, bound, message) in _QUERIES.items():
|
||||
lines.append(f'${part} = "{_xpath(events, start)}"')
|
||||
parts.append(f" {part} = (Q '{log}' ${part} {bound} ${str(message).lower()})")
|
||||
lines.append("[pscustomobject]@{ parts = [pscustomobject]@{")
|
||||
lines.extend(parts)
|
||||
lines.append("} } | ConvertTo-Json -Compress -Depth 6")
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def _parse_event(raw: dict[str, Any], source_log: str) -> HostEventDict | None:
|
||||
known = _EVENTS.get((str(raw.get("provider") or ""), int(raw.get("id") or 0)))
|
||||
if known is None:
|
||||
return None
|
||||
kind, subject = known
|
||||
props = [str(p) for p in _as_list(raw.get("props"))]
|
||||
source = f"{source_log}: {raw.get('provider')} {raw.get('id')}"
|
||||
return _event(kind, float(raw.get("time") or 0), source, subject(props), raw.get("message"))
|
||||
|
||||
|
||||
def _part(answer: Any, log: str) -> list[HostEventDict] | None:
|
||||
"""One query's events; None when it was not read."""
|
||||
if not isinstance(answer, dict) or not answer.get("ok"):
|
||||
return None
|
||||
found = (_parse_event(e, log) for e in _as_list(answer.get("events")))
|
||||
return [e for e in found if e is not None]
|
||||
|
||||
|
||||
def _in_order(kinds: set[str]) -> list[str]:
|
||||
return [k for k in HOST_EVENT_KINDS if k in kinds]
|
||||
|
||||
|
||||
def _reading(raw: Any, since: float) -> HostEventsDict:
|
||||
if not isinstance(raw, dict) or not isinstance(raw.get("parts"), dict):
|
||||
raise ValueError("the host events reading came back without a report")
|
||||
events: list[HostEventDict] = []
|
||||
capped: set[str] = set()
|
||||
unread: set[str] = set()
|
||||
for part, (log, _events, _bound, _message) in _QUERIES.items():
|
||||
answer = raw["parts"].get(part)
|
||||
found = _part(answer, log)
|
||||
if found is None:
|
||||
unread.update(_PART_KINDS[part])
|
||||
continue
|
||||
if answer.get("capped"):
|
||||
capped.update(_PART_KINDS[part])
|
||||
events.extend(found)
|
||||
events.sort(key=lambda e: e["time"], reverse=True)
|
||||
return {
|
||||
"since": datetime.fromtimestamp(since, UTC).isoformat(),
|
||||
"events": events,
|
||||
"capped": _in_order(capped),
|
||||
"unread": _in_order(unread),
|
||||
}
|
||||
|
||||
|
||||
class WindowsHostEventsMixin(HostEventsMixin):
|
||||
"""The event log's warnings-worthy events; the driver carries the script."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_ps(self, script: str) -> Any: ...
|
||||
|
||||
def get_host_events(self, since: float | None = None) -> HostEventsDict:
|
||||
"""The events of ``HOST_EVENT_KINDS`` since *since* (unix seconds), by default
|
||||
over the last ``HOST_EVENT_WINDOW_DAYS`` days; one round trip, see the module.
|
||||
|
||||
:raises ValueError: when the reading came back without a report.
|
||||
"""
|
||||
start = time.time() - HOST_EVENT_WINDOW_DAYS * 86400 if since is None else since
|
||||
return _reading(self._run_ps(host_events_script(start)), start)
|
||||
@@ -0,0 +1,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")
|
||||
@@ -0,0 +1,98 @@
|
||||
"""The host's services, and how each one's last run ended (NetOrk/netork#2897).
|
||||
|
||||
:class:`WindowsServicesMixin` reads ``get_services`` for the driver, which carries
|
||||
the script across ``PsrpTransport.run``.
|
||||
|
||||
One script: every ``Win32_Service`` with its state, start mode and process, the
|
||||
account it runs as (``StartName``) and the code its last run ended with
|
||||
(``ExitCode``). Both exit codes are UInt32 and leave the host as ``[int64]``, since
|
||||
``[int]`` would throw on an HRESULT and fail the reading. Which services a trigger
|
||||
starts (a device arriving, a network change, a request) is one registry read for all
|
||||
of them: the ``TriggerInfo`` keys under ``HKLM:\\SYSTEM\\CurrentControlSet\\Services``.
|
||||
|
||||
**How the last run ended** is said in systemd's words (napalm-device-types'
|
||||
``ServiceDict.result``), so that one rule reads it for every host:
|
||||
|
||||
* ``0`` is ``success``: running, or stopped on purpose.
|
||||
* ``1077`` (``ERROR_SERVICE_NEVER_STARTED``) is no result: not started since the
|
||||
host booted -- a demand-start service, or a delayed one in the minutes after boot.
|
||||
* ``1066`` (``ERROR_SERVICE_SPECIFIC_ERROR``) is ``exit-code`` with the service's own
|
||||
code, ``ServiceSpecificExitCode``.
|
||||
* Any other code is ``exit-code`` with that code: ``1067`` is a process that ended
|
||||
without being stopped.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types import SERVICE_RESULT_EXIT_CODE, SERVICE_RESULT_SUCCESS, ServiceDict
|
||||
|
||||
from napalm_windows._powershell import _as_list
|
||||
|
||||
_PS_SERVICES = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$triggered = @{}
|
||||
$keys = 'HKLM:\SYSTEM\CurrentControlSet\Services\*\TriggerInfo'
|
||||
Get-Item -Path $keys -ErrorAction SilentlyContinue |
|
||||
ForEach-Object { $triggered[(Split-Path -Path $_.PSParentPath -Leaf)] = $true }
|
||||
ConvertTo-Json -Compress -Depth 3 -InputObject @(
|
||||
Get-CimInstance -ClassName Win32_Service | ForEach-Object {
|
||||
[pscustomobject]@{
|
||||
name = $_.Name
|
||||
state = [string]$_.State
|
||||
start_mode = [string]$_.StartMode
|
||||
pid = [int]$_.ProcessId
|
||||
exit_code = [int64]$_.ExitCode
|
||||
service_code = [int64]$_.ServiceSpecificExitCode
|
||||
account = $_.StartName
|
||||
trigger_start = [bool]$triggered[$_.Name]
|
||||
}
|
||||
}
|
||||
)
|
||||
"""
|
||||
|
||||
_ENABLED_START_MODES = {"auto", "boot", "system"}
|
||||
#: ``ERROR_SERVICE_NEVER_STARTED``: no attempt to start it since the host booted.
|
||||
_NEVER_STARTED = 1077
|
||||
#: ``ERROR_SERVICE_SPECIFIC_ERROR``: the code is the service's own.
|
||||
_SERVICE_SPECIFIC = 1066
|
||||
|
||||
|
||||
def _result(raw: dict[str, Any]) -> tuple[str | None, int | None]:
|
||||
"""How the last run ended, and its code where that was not success."""
|
||||
code = raw.get("exit_code")
|
||||
if code is None or int(code) == _NEVER_STARTED:
|
||||
return None, None
|
||||
if int(code) == 0:
|
||||
return SERVICE_RESULT_SUCCESS, None
|
||||
if int(code) == _SERVICE_SPECIFIC and raw.get("service_code"):
|
||||
return SERVICE_RESULT_EXIT_CODE, int(raw["service_code"])
|
||||
return SERVICE_RESULT_EXIT_CODE, int(code)
|
||||
|
||||
|
||||
def _service(raw: dict[str, Any]) -> ServiceDict:
|
||||
running = str(raw.get("state") or "").lower() == "running"
|
||||
result, exit_code = _result(raw)
|
||||
return {
|
||||
"name": str(raw["name"]),
|
||||
"running": running,
|
||||
"enabled": str(raw.get("start_mode") or "").lower() in _ENABLED_START_MODES,
|
||||
"pid": int(raw.get("pid") or 0) if running else 0,
|
||||
"result": result,
|
||||
"exit_code": exit_code,
|
||||
"trigger_start": bool(raw.get("trigger_start")),
|
||||
"account": str(raw["account"]) if raw.get("account") else None,
|
||||
}
|
||||
|
||||
|
||||
class WindowsServicesMixin:
|
||||
"""``get_services`` from ``Win32_Service``; the driver carries the script."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_ps(self, script: str) -> Any: ...
|
||||
|
||||
def get_services(self) -> list[ServiceDict]:
|
||||
"""Every service with whether it runs, starts at boot, and how its last run ended."""
|
||||
return [_service(s) for s in _as_list(self._run_ps(_PS_SERVICES))]
|
||||
@@ -0,0 +1,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>"
|
||||
)
|
||||
@@ -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})"}
|
||||
@@ -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"]
|
||||
@@ -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:
|
||||
|
||||
+55
-51
@@ -24,8 +24,14 @@ from typing import Any
|
||||
|
||||
from napalm.base.exceptions import ConnectionClosedException
|
||||
from napalm_device_types import FingerprintRule, OSDriver, PortSpec
|
||||
from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict, ServiceDict
|
||||
from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict
|
||||
|
||||
from napalm_windows._powershell import _as_list, _ps_quote
|
||||
from napalm_windows.event_channels import WindowsLogSourcesMixin
|
||||
from napalm_windows.host_events import WindowsHostEventsMixin
|
||||
from napalm_windows.scheduled_tasks import WindowsScheduledJobsMixin
|
||||
from napalm_windows.services import WindowsServicesMixin
|
||||
from napalm_windows.time_sync import WindowsTimeSyncMixin
|
||||
from napalm_windows.transport import PowerShellError, PsrpTransport
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -120,20 +126,6 @@ ConvertTo-Json -Compress -Depth 3 -InputObject @(
|
||||
)
|
||||
"""
|
||||
|
||||
_PS_SERVICES = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
ConvertTo-Json -Compress -Depth 3 -InputObject @(
|
||||
Get-CimInstance -ClassName Win32_Service | ForEach-Object {
|
||||
[pscustomobject]@{
|
||||
name = $_.Name
|
||||
state = [string]$_.State
|
||||
start_mode = [string]$_.StartMode
|
||||
pid = [int]$_.ProcessId
|
||||
}
|
||||
}
|
||||
)
|
||||
"""
|
||||
|
||||
# Every listening TCP and bound UDP socket, the processes holding them and the
|
||||
# services those processes run. Sockets owned by http.sys (WinRM, IIS) belong to
|
||||
# the System process; a shared svchost runs several services in one process.
|
||||
@@ -178,13 +170,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",
|
||||
@@ -195,7 +190,6 @@ _ROUTE_PROTOCOLS = {
|
||||
"rip": "rip",
|
||||
}
|
||||
|
||||
_ENABLED_START_MODES = {"auto", "boot", "system"}
|
||||
_DEAD_NEIGHBOUR_STATES = {"unreachable", "incomplete"}
|
||||
|
||||
|
||||
@@ -204,22 +198,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 +249,14 @@ def _is_noise_route(destination: str) -> bool:
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class WindowsDriver(OSDriver):
|
||||
class WindowsDriver(
|
||||
WindowsScheduledJobsMixin,
|
||||
WindowsTimeSyncMixin,
|
||||
WindowsServicesMixin,
|
||||
WindowsHostEventsMixin,
|
||||
WindowsLogSourcesMixin,
|
||||
OSDriver,
|
||||
):
|
||||
"""NAPALM driver for Windows Server 2016+ and Windows 10/11.
|
||||
|
||||
``optional_args``:
|
||||
@@ -369,6 +354,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 +430,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 +439,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(
|
||||
@@ -488,20 +484,6 @@ class WindowsDriver(OSDriver):
|
||||
# Services
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_services(self) -> list[ServiceDict]:
|
||||
services: list[ServiceDict] = []
|
||||
for s in _as_list(self._run_ps(_PS_SERVICES)):
|
||||
running = (s.get("state") or "").lower() == "running"
|
||||
services.append(
|
||||
{
|
||||
"name": s["name"],
|
||||
"running": running,
|
||||
"enabled": (s.get("start_mode") or "").lower() in _ENABLED_START_MODES,
|
||||
"pid": int(s.get("pid") or 0) if running else 0,
|
||||
}
|
||||
)
|
||||
return services
|
||||
|
||||
def get_listening_sockets(self) -> ListeningSocketsDict:
|
||||
"""Every listening TCP and bound UDP socket, with the process and the
|
||||
Windows service behind it (``Get-NetTCPConnection``, ``Get-NetUDPEndpoint``,
|
||||
@@ -520,6 +502,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
@@ -7,7 +7,7 @@ name = "napalm-windows"
|
||||
version = "0.2.0"
|
||||
description = "NAPALM driver for Windows hosts via PowerShell Remoting (WinRM)"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
requires-python = ">=3.12"
|
||||
license = "Apache-2.0"
|
||||
authors = [
|
||||
{ name = "Christian Manivong", email = "christian@manivong.de" },
|
||||
@@ -28,8 +28,6 @@ classifiers = [
|
||||
"Intended Audience :: System Administrators",
|
||||
"Operating System :: OS Independent",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Programming Language :: Python :: 3.13",
|
||||
"Topic :: System :: Networking",
|
||||
@@ -37,8 +35,8 @@ classifiers = [
|
||||
"Typing :: Typed",
|
||||
]
|
||||
dependencies = [
|
||||
"napalm>=4.0",
|
||||
"napalm-device-types>=4.21.1",
|
||||
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
|
||||
"napalm-device-types>=4.35.0", # TimeSyncMixin
|
||||
"pypsrp>=0.8",
|
||||
]
|
||||
|
||||
@@ -67,7 +65,7 @@ napalm_windows = ["py.typed"]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
target-version = "py310"
|
||||
target-version = "py312"
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "I", "UP", "B"]
|
||||
@@ -77,7 +75,7 @@ select = ["E", "F", "I", "UP", "B"]
|
||||
"tests/**" = ["E501"]
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.10"
|
||||
python_version = "3.12"
|
||||
strict = true
|
||||
# napalm itself is untyped, so every driver subclasses Any.
|
||||
disallow_subclassing_any = false
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
[
|
||||
{"channel": "Application", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Application.evtx", "size": 20975616, "modified": 1764499800, "records": 41233, "type": "Administrative"},
|
||||
{"channel": "Security", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Security.evtx", "size": 20975616, "modified": 1764499990, "records": 58812, "type": "Administrative"},
|
||||
{"channel": "System", "path": "C:\\Windows\\System32\\Winevt\\Logs\\System.evtx", "size": 20975616, "modified": 1764499950, "records": 30187, "type": "Administrative"},
|
||||
{"channel": "Microsoft-Windows-Sysmon/Operational", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-Sysmon%4Operational.evtx", "size": 67113984, "modified": 1764499999, "records": 120044, "type": "Operational"},
|
||||
{"channel": "Microsoft-Windows-PowerShell/Operational", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-PowerShell%4Operational.evtx", "size": 15798272, "modified": null, "records": 9120, "type": "Operational"},
|
||||
{"channel": "Microsoft-Windows-Kernel-PnP/Device Management", "path": null, "size": 69632, "modified": 1764400000, "records": 12, "type": "Operational"},
|
||||
{"channel": "Microsoft-Windows-WMI-Activity/Debug", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-WMI-Activity%4Debug.etl", "size": 4096, "modified": 1764400000, "records": 3, "type": "Debug"},
|
||||
{"channel": "Microsoft-Windows-Kernel-Boot/Analytic", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-Kernel-Boot%4Analytic.etl", "size": 4096, "modified": 1764400000, "records": 7, "type": "Analytic"},
|
||||
{"channel": "Microsoft-Windows-Empty/Operational", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-Empty%4Operational.evtx", "size": 69632, "modified": 1764400000, "records": 0, "type": "Operational"}
|
||||
]
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
{
|
||||
"parts": {
|
||||
"rare": {
|
||||
"ok": true,
|
||||
"capped": false,
|
||||
"events": [
|
||||
{
|
||||
"provider": "Microsoft-Windows-WER-SystemErrorReporting",
|
||||
"id": 1001,
|
||||
"time": 1764470150,
|
||||
"props": [
|
||||
"0x0000009f (0x0000000000000003, 0xffffc40f1a2b3c40, 0xfffff80412345678, 0xffffc40f1a2b3d50)",
|
||||
"C:\\Windows\\MEMORY.DMP",
|
||||
"1130-01"
|
||||
],
|
||||
"message": "The computer has rebooted from a bugcheck. The bugcheck was: 0x0000009f (0x0000000000000003, 0xffffc40f1a2b3c40, 0xfffff80412345678, 0xffffc40f1a2b3d50). A dump was saved in: C:\\Windows\\MEMORY.DMP. Report Id: 1130-01."
|
||||
},
|
||||
{
|
||||
"provider": "EventLog",
|
||||
"id": 6008,
|
||||
"time": 1764470040,
|
||||
"props": [
|
||||
"03:12:09",
|
||||
"\u200e30.\u200e11.\u200e2026",
|
||||
"",
|
||||
"",
|
||||
"1234",
|
||||
"",
|
||||
""
|
||||
],
|
||||
"message": "The previous system shutdown at 03:12:09 on 30.11.2026 was unexpected."
|
||||
},
|
||||
{
|
||||
"provider": "Microsoft-Windows-Kernel-Power",
|
||||
"id": 41,
|
||||
"time": 1764470035,
|
||||
"props": [
|
||||
"159",
|
||||
"3",
|
||||
"18446676388826430528",
|
||||
"18446735294628329080",
|
||||
"18446676388826430800",
|
||||
"false",
|
||||
"0"
|
||||
],
|
||||
"message": "The system has rebooted without cleanly shutting down first."
|
||||
},
|
||||
{
|
||||
"provider": "Microsoft-Windows-WHEA-Logger",
|
||||
"id": 18,
|
||||
"time": 1764383600,
|
||||
"props": [
|
||||
"1",
|
||||
"0",
|
||||
"5",
|
||||
"0",
|
||||
"0"
|
||||
],
|
||||
"message": "A fatal hardware error has occurred."
|
||||
},
|
||||
{
|
||||
"provider": "disk",
|
||||
"id": 7,
|
||||
"time": 1764466400,
|
||||
"props": [
|
||||
"\\Device\\Harddisk1\\DR1"
|
||||
],
|
||||
"message": "The device, \\Device\\Harddisk1\\DR1, has a bad block."
|
||||
},
|
||||
{
|
||||
"provider": "Microsoft-Windows-Ntfs",
|
||||
"id": 55,
|
||||
"time": 1764462800,
|
||||
"props": [
|
||||
"D:",
|
||||
"\\Device\\HarddiskVolume5",
|
||||
"0x2"
|
||||
],
|
||||
"message": "A corruption was discovered in the file system structure on volume D:."
|
||||
},
|
||||
{
|
||||
"provider": "Microsoft-Windows-Kernel-Power",
|
||||
"id": 41,
|
||||
"time": 1764297200,
|
||||
"props": [
|
||||
"0",
|
||||
"0",
|
||||
"0",
|
||||
"0",
|
||||
"0",
|
||||
"false",
|
||||
"0"
|
||||
],
|
||||
"message": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"frequent": {
|
||||
"ok": true,
|
||||
"capped": false,
|
||||
"events": [
|
||||
{
|
||||
"provider": "Service Control Manager",
|
||||
"id": 7031,
|
||||
"time": 1764470600,
|
||||
"props": [
|
||||
"Backup Agent",
|
||||
"1",
|
||||
"60000",
|
||||
"1",
|
||||
"Restart the service"
|
||||
],
|
||||
"message": null
|
||||
},
|
||||
{
|
||||
"provider": "Microsoft-Windows-WHEA-Logger",
|
||||
"id": 47,
|
||||
"time": 1764470500,
|
||||
"props": [
|
||||
"3",
|
||||
"0",
|
||||
"1"
|
||||
],
|
||||
"message": null
|
||||
},
|
||||
{
|
||||
"provider": "disk",
|
||||
"id": 153,
|
||||
"time": 1764470400,
|
||||
"props": [
|
||||
"\\Device\\Harddisk1\\DR1",
|
||||
"0x1d4c0",
|
||||
"1",
|
||||
"\\Device\\00000034"
|
||||
],
|
||||
"message": null
|
||||
},
|
||||
{
|
||||
"provider": "Service Control Manager",
|
||||
"id": 7034,
|
||||
"time": 1764470300,
|
||||
"props": [
|
||||
"Vendor Sync",
|
||||
"2"
|
||||
],
|
||||
"message": null
|
||||
},
|
||||
{
|
||||
"provider": "Microsoft-Windows-WHEA-Logger",
|
||||
"id": 19,
|
||||
"time": 1764470200,
|
||||
"props": [
|
||||
"3",
|
||||
"0",
|
||||
"1"
|
||||
],
|
||||
"message": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"apps": {
|
||||
"ok": true,
|
||||
"capped": false,
|
||||
"events": [
|
||||
{
|
||||
"provider": "Application Error",
|
||||
"id": 1000,
|
||||
"time": 1764470900,
|
||||
"props": [
|
||||
"vendorapp.exe",
|
||||
"4.2.0.0",
|
||||
"65a1b2c3",
|
||||
"ntdll.dll",
|
||||
"10.0.20348.2340",
|
||||
"f0e1d2c3",
|
||||
"c0000005",
|
||||
"00000000000a1b2c",
|
||||
"1f40",
|
||||
"01db1234567890ab",
|
||||
"C:\\Program Files\\Vendor\\vendorapp.exe"
|
||||
],
|
||||
"message": null
|
||||
},
|
||||
{
|
||||
"provider": "Application Error",
|
||||
"id": 1000,
|
||||
"time": 1764470800,
|
||||
"props": [
|
||||
"vendorapp.exe",
|
||||
"4.2.0.0",
|
||||
"65a1b2c3",
|
||||
"ntdll.dll",
|
||||
"10.0.20348.2340",
|
||||
"f0e1d2c3",
|
||||
"c0000005",
|
||||
"00000000000a1b2c",
|
||||
"1f40",
|
||||
"01db1234567890ab",
|
||||
"C:\\Program Files\\Vendor\\vendorapp.exe"
|
||||
],
|
||||
"message": null
|
||||
},
|
||||
{
|
||||
"provider": "Application Error",
|
||||
"id": 1000,
|
||||
"time": 1764470700,
|
||||
"props": [
|
||||
"legacy.exe",
|
||||
"1.0.0.0",
|
||||
"5f0a0b0c"
|
||||
],
|
||||
"message": null
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
+100
@@ -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
|
||||
}
|
||||
]
|
||||
}
|
||||
+9
-5
@@ -1,7 +1,11 @@
|
||||
[
|
||||
{"name": "WinRM", "state": "Running", "start_mode": "Auto", "pid": 1234},
|
||||
{"name": "Spooler", "state": "Stopped", "start_mode": "Manual", "pid": 0},
|
||||
{"name": "MSSQL$SQLEXPRESS", "state": "Running", "start_mode": "Auto", "pid": 4321},
|
||||
{"name": "RemoteRegistry", "state": "Stopped", "start_mode": "Disabled", "pid": 0},
|
||||
{"name": "wuauserv", "state": "Stopped", "start_mode": "Manual", "pid": null}
|
||||
{"name": "WinRM", "state": "Running", "start_mode": "Auto", "pid": 1234, "exit_code": 0, "service_code": 0, "account": "NT AUTHORITY\\NetworkService", "trigger_start": false},
|
||||
{"name": "Spooler", "state": "Stopped", "start_mode": "Manual", "pid": 0, "exit_code": 0, "service_code": 0, "account": "LocalSystem", "trigger_start": false},
|
||||
{"name": "MSSQL$SQLEXPRESS", "state": "Running", "start_mode": "Auto", "pid": 4321, "exit_code": 0, "service_code": 0, "account": "CORP\\svc-sql", "trigger_start": false},
|
||||
{"name": "RemoteRegistry", "state": "Stopped", "start_mode": "Disabled", "pid": 0, "exit_code": 1077, "service_code": 0, "account": "NT AUTHORITY\\LocalService", "trigger_start": true},
|
||||
{"name": "wuauserv", "state": "Stopped", "start_mode": "Manual", "pid": null, "exit_code": 0, "service_code": 0, "account": "LocalSystem", "trigger_start": true},
|
||||
{"name": "AppReadiness", "state": "Stopped", "start_mode": "Auto", "pid": 0, "exit_code": 1077, "service_code": 0, "account": "LocalSystem", "trigger_start": false},
|
||||
{"name": "BackupAgent", "state": "Stopped", "start_mode": "Auto", "pid": 0, "exit_code": 1067, "service_code": 0, "account": "CORP\\svc-backup", "trigger_start": false},
|
||||
{"name": "VendorSync", "state": "Stopped", "start_mode": "Auto", "pid": 0, "exit_code": 1066, "service_code": 2147942405, "account": "LocalSystem", "trigger_start": false},
|
||||
{"name": "BthServ", "state": "Stopped", "start_mode": "Auto", "pid": 0, "exit_code": 1, "service_code": 0, "account": null, "trigger_start": true}
|
||||
]
|
||||
+1
@@ -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}
|
||||
@@ -0,0 +1,103 @@
|
||||
"""The event channels as the host's log sources (NetOrk/netork#2897).
|
||||
|
||||
A Windows host keeps its logs in event channels. ``Get-WinEvent -ListLog *`` names
|
||||
every one with its ``.evtx`` file, size, last write and record count; a channel that
|
||||
is switched on and holds records is a log the host writes. Analytic and debug
|
||||
channels are trace sessions, not logs a reader can follow, and are left out. The
|
||||
answer is the shape of tests/fixtures/synthetic/event_channels.json.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import event_channels as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "event_channels.json"
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
def __init__(self, answer: str) -> None:
|
||||
self.answer = answer
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
return self.answer
|
||||
|
||||
|
||||
def _reading(answer: str | None = None) -> dict:
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(FIXTURE.read_text() if answer is None else answer)
|
||||
return d.get_log_sources()
|
||||
|
||||
|
||||
class TestTheReading:
|
||||
def test_read_as_an_administrator_without_a_journal(self):
|
||||
reading = _reading()
|
||||
assert (reading["attributed"], reading["journald"], reading["forwarding"]) == (
|
||||
True,
|
||||
False,
|
||||
None,
|
||||
)
|
||||
|
||||
def test_every_channel_with_records_sorted_by_name(self):
|
||||
assert [s["channel"] for s in _reading()["sources"]] == [
|
||||
"Application",
|
||||
"Microsoft-Windows-Kernel-PnP/Device Management",
|
||||
"Microsoft-Windows-PowerShell/Operational",
|
||||
"Microsoft-Windows-Sysmon/Operational",
|
||||
"Security",
|
||||
"System",
|
||||
]
|
||||
|
||||
def test_a_channel_is_an_eventlog_source(self):
|
||||
sysmon = next(s for s in _reading()["sources"] if "Sysmon" in s["channel"])
|
||||
assert sysmon == {
|
||||
"kind": "eventlog",
|
||||
"path": r"C:\Windows\System32\Winevt\Logs\Microsoft-Windows-Sysmon%4Operational.evtx",
|
||||
"unit": None,
|
||||
"container_id": None,
|
||||
"process": None,
|
||||
"size": 67113984,
|
||||
"modified": "2025-11-30T10:53:19+00:00",
|
||||
"channel": "Microsoft-Windows-Sysmon/Operational",
|
||||
}
|
||||
|
||||
def test_what_the_host_did_not_say_is_none(self):
|
||||
sources = {s["channel"]: s for s in _reading()["sources"]}
|
||||
assert sources["Microsoft-Windows-PowerShell/Operational"]["modified"] is None
|
||||
assert sources["Microsoft-Windows-Kernel-PnP/Device Management"]["path"] is None
|
||||
|
||||
@pytest.mark.parametrize("left_out", ["Debug", "Analytic", "Empty"])
|
||||
def test_trace_sessions_and_empty_channels_are_left_out(self, left_out):
|
||||
assert not any(left_out in s["channel"] for s in _reading()["sources"])
|
||||
|
||||
def test_a_single_channel_is_still_a_list(self):
|
||||
one = json.loads(FIXTURE.read_text())[2]
|
||||
assert [s["channel"] for s in _reading(json.dumps(one))["sources"]] == ["System"]
|
||||
|
||||
def test_no_channel_is_no_sources(self):
|
||||
assert _reading("")["sources"] == []
|
||||
|
||||
|
||||
class TestTheScript:
|
||||
def test_lists_every_channel_once(self):
|
||||
assert "Get-WinEvent -ListLog *" in mod._PS_EVENT_CHANNELS
|
||||
|
||||
def test_a_channel_it_may_not_open_costs_only_that_channel(self):
|
||||
assert "-ErrorAction SilentlyContinue" in mod._PS_EVENT_CHANNELS
|
||||
|
||||
def test_only_channels_switched_on_and_holding_records(self):
|
||||
assert "$_.IsEnabled -and $_.RecordCount" in mod._PS_EVENT_CHANNELS
|
||||
|
||||
def test_the_file_is_named_as_it_is_on_disk(self):
|
||||
assert "ExpandEnvironmentVariables" in mod._PS_EVENT_CHANNELS
|
||||
|
||||
def test_a_list_goes_through_input_object(self):
|
||||
assert "-InputObject @(" in mod._PS_EVENT_CHANNELS
|
||||
@@ -0,0 +1,206 @@
|
||||
"""What the event log recorded that says something is wrong with the host (NetOrk/netork#2897).
|
||||
|
||||
One script asks the event log three questions over the reading's window: the rare
|
||||
events of the System log (an unexpected shutdown, a bugcheck, a fatal hardware
|
||||
error, a bad block, a file system corruption), its frequent ones (corrected
|
||||
hardware errors, retried disk I/O, services that ended unexpectedly) and the
|
||||
Application log's crashing programs. Each is bounded by time and count, and each
|
||||
catches ``NoMatchingEventsFound``: ``Get-WinEvent`` throws when nothing matches. The
|
||||
answer is the shape of tests/fixtures/synthetic/host_events.json.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import HOST_EVENT_KINDS, HostEventsMixin
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import host_events as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "host_events.json"
|
||||
NOW = 1764500000.0
|
||||
WEEK = 7 * 86400
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
def __init__(self, answer: str) -> None:
|
||||
self.answer = answer
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
return self.answer
|
||||
|
||||
|
||||
def _driver(answer: dict[str, Any] | str | None = None) -> WindowsDriver:
|
||||
if answer is None:
|
||||
answer = FIXTURE.read_text()
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(answer if isinstance(answer, str) else json.dumps(answer))
|
||||
return d
|
||||
|
||||
|
||||
def _fixture() -> dict[str, Any]:
|
||||
return json.loads(FIXTURE.read_text())
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _now(monkeypatch):
|
||||
monkeypatch.setattr(mod.time, "time", lambda: NOW)
|
||||
|
||||
|
||||
def _kinds(reading) -> list[tuple[str, str | None]]:
|
||||
return [(e["kind"], e["subject"]) for e in reading["events"]]
|
||||
|
||||
|
||||
class TestTheEvents:
|
||||
def test_every_event_as_its_kind_and_subject_newest_first(self):
|
||||
assert _kinds(_driver().get_host_events()) == [
|
||||
("app_crash", r"C:\Program Files\Vendor\vendorapp.exe"),
|
||||
("app_crash", r"C:\Program Files\Vendor\vendorapp.exe"),
|
||||
("app_crash", "legacy.exe"),
|
||||
("service_crash", "Backup Agent"),
|
||||
("hardware_error_corrected", None),
|
||||
("disk_error", r"\Device\Harddisk1\DR1"),
|
||||
("service_crash", "Vendor Sync"),
|
||||
("hardware_error_corrected", None),
|
||||
("system_crash", "0x0000009f"),
|
||||
("unexpected_shutdown", None),
|
||||
("unexpected_shutdown", "0x0000009f"),
|
||||
("disk_error", r"\Device\Harddisk1\DR1"),
|
||||
("disk_error", "D:"),
|
||||
("hardware_error_fatal", None),
|
||||
("unexpected_shutdown", None),
|
||||
]
|
||||
|
||||
def test_an_event_says_when_where_and_what_the_host_wrote(self):
|
||||
crash = next(
|
||||
e for e in _driver().get_host_events()["events"] if e["kind"] == "system_crash"
|
||||
)
|
||||
assert crash == {
|
||||
"kind": "system_crash",
|
||||
"time": "2025-11-30T02:35:50+00:00",
|
||||
"subject": "0x0000009f",
|
||||
"source": "System: Microsoft-Windows-WER-SystemErrorReporting 1001",
|
||||
"message": crash["message"],
|
||||
}
|
||||
assert crash["message"].startswith("The computer has rebooted from a bugcheck.")
|
||||
|
||||
def test_a_power_loss_without_a_bugcheck_has_no_stop_code(self):
|
||||
shutdowns = [
|
||||
e for e in _driver().get_host_events()["events"] if e["kind"] == "unexpected_shutdown"
|
||||
]
|
||||
assert [e["subject"] for e in shutdowns] == [None, "0x0000009f", None]
|
||||
|
||||
def test_the_hosts_message_is_cut(self):
|
||||
answer = _fixture()
|
||||
answer["parts"]["rare"]["events"][0]["message"] = "y" * 5000
|
||||
events = _driver(answer).get_host_events()["events"]
|
||||
assert max(len(e["message"] or "") for e in events) == 300
|
||||
|
||||
def test_an_event_the_reading_does_not_know_is_left_out(self):
|
||||
answer = _fixture()
|
||||
answer["parts"]["rare"]["events"] = [
|
||||
{"provider": "Microsoft-Windows-Kernel-General", "id": 12, "time": NOW, "props": []}
|
||||
]
|
||||
kinds = {e["kind"] for e in _driver(answer).get_host_events()["events"]}
|
||||
assert "unexpected_shutdown" not in kinds
|
||||
|
||||
def test_a_single_event_is_still_a_list(self):
|
||||
answer = _fixture()
|
||||
answer["parts"]["apps"]["events"] = answer["parts"]["apps"]["events"][0]
|
||||
apps = [e for e in _driver(answer).get_host_events()["events"] if e["kind"] == "app_crash"]
|
||||
assert len(apps) == 1
|
||||
|
||||
|
||||
class TestWhatWasRead:
|
||||
def test_a_full_reading_names_nothing_capped_or_unread(self):
|
||||
reading = _driver().get_host_events()
|
||||
assert (reading["capped"], reading["unread"]) == ([], [])
|
||||
|
||||
def test_an_empty_log_is_no_events_not_an_error(self):
|
||||
"""What the script makes of ``NoMatchingEventsFound``: read, nothing found."""
|
||||
answer = _fixture()
|
||||
for part in answer["parts"].values():
|
||||
part["events"] = []
|
||||
reading = _driver(answer).get_host_events()
|
||||
assert (reading["events"], reading["unread"]) == ([], [])
|
||||
|
||||
def test_a_query_that_failed_names_its_kinds_unread(self):
|
||||
answer = _fixture()
|
||||
answer["parts"]["frequent"] = {"ok": False, "capped": False, "events": [], "error": "x"}
|
||||
reading = _driver(answer).get_host_events()
|
||||
assert reading["unread"] == ["hardware_error_corrected", "disk_error", "service_crash"]
|
||||
assert "service_crash" not in {e["kind"] for e in reading["events"]}
|
||||
|
||||
def test_a_query_read_up_to_its_bound_names_its_kinds_capped(self):
|
||||
answer = _fixture()
|
||||
answer["parts"]["apps"]["capped"] = True
|
||||
assert _driver(answer).get_host_events()["capped"] == ["app_crash"]
|
||||
|
||||
def test_a_part_missing_from_the_answer_is_unread(self):
|
||||
answer = _fixture()
|
||||
del answer["parts"]["apps"]
|
||||
assert _driver(answer).get_host_events()["unread"] == ["app_crash"]
|
||||
|
||||
def test_every_kind_is_read_by_some_query(self):
|
||||
read = {kind for kinds in mod._PART_KINDS.values() for kind in kinds}
|
||||
assert read == set(HOST_EVENT_KINDS)
|
||||
|
||||
@pytest.mark.parametrize("answer", ["", "[]", '{"since": 1}'])
|
||||
def test_an_answer_without_a_report_raises(self, answer):
|
||||
with pytest.raises(ValueError):
|
||||
_driver(answer).get_host_events()
|
||||
|
||||
|
||||
class TestTheWindow:
|
||||
def test_a_week_by_default(self):
|
||||
d = _driver()
|
||||
reading = d.get_host_events()
|
||||
assert reading["since"] == "2025-11-23T10:53:20+00:00"
|
||||
assert "@SystemTime>='2025-11-23T10:53:20.000Z'" in d._transport.sent[0]
|
||||
|
||||
def test_the_callers_start(self):
|
||||
d = _driver()
|
||||
reading = d.get_host_events(since=NOW - 3600)
|
||||
assert reading["since"] == "2025-11-30T09:53:20+00:00"
|
||||
assert "@SystemTime>='2025-11-30T09:53:20.000Z'" in d._transport.sent[0]
|
||||
|
||||
|
||||
class TestTheScript:
|
||||
script = mod.host_events_script(NOW - WEEK)
|
||||
|
||||
def test_every_query_catches_no_matching_events(self):
|
||||
assert self.script.count("Get-WinEvent") == 1
|
||||
assert "NoMatchingEventsFound" in self.script
|
||||
assert len(re.findall(r"\(Q '(System|Application)'", self.script)) == 3
|
||||
|
||||
def test_every_query_is_bounded_by_count(self):
|
||||
bounds = [int(n) for n in re.findall(r"\(Q '\w+' \$\w+ (\d+)", self.script)]
|
||||
assert bounds == [100, 500, 200]
|
||||
assert "-MaxEvents $max" in self.script
|
||||
|
||||
def test_every_query_is_bounded_by_time(self):
|
||||
assert self.script.count("TimeCreated[@SystemTime>=") == 3
|
||||
|
||||
def test_only_the_rare_events_carry_their_message(self):
|
||||
assert re.findall(r"\(Q '\w+' \$\w+ \d+ \$(true|false)\)", self.script) == [
|
||||
"true",
|
||||
"false",
|
||||
"false",
|
||||
]
|
||||
|
||||
def test_the_answer_survives_a_deep_object(self):
|
||||
assert "-Depth 6" in self.script
|
||||
|
||||
def test_stops_on_errors_it_does_not_catch(self):
|
||||
assert self.script.lstrip().startswith("$ErrorActionPreference = 'Stop'")
|
||||
|
||||
def test_the_driver_carries_the_contract(self):
|
||||
assert isinstance(WindowsDriver("h", "u", "p"), HostEventsMixin)
|
||||
@@ -0,0 +1,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
|
||||
@@ -0,0 +1,125 @@
|
||||
"""The host's services and how each one's last run ended (NetOrk/netork#2897).
|
||||
|
||||
``Win32_Service`` says whether a service runs and how it starts, and also what its
|
||||
last run ended with: ``ExitCode`` (``1066`` hands over to
|
||||
``ServiceSpecificExitCode``, ``1077`` is "not started since boot"). Together with
|
||||
whether a trigger starts it (a ``TriggerInfo`` key under the service) that tells a
|
||||
service that died from one stopped on purpose. The reading is the shape of
|
||||
tests/fixtures/synthetic/services.json.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import services as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "services.json"
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
def __init__(self, answer: str) -> None:
|
||||
self.answer = answer
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
return self.answer if script == mod._PS_SERVICES else ""
|
||||
|
||||
|
||||
def _services(answer: str | None = None) -> dict[str, dict]:
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(FIXTURE.read_text() if answer is None else answer)
|
||||
return {s["name"]: s for s in d.get_services()}
|
||||
|
||||
|
||||
class TestRunningAndEnabled:
|
||||
def test_maps_state_and_start_mode(self):
|
||||
services = _services()
|
||||
assert {n: (s["running"], s["enabled"], s["pid"]) for n, s in services.items()} == {
|
||||
"WinRM": (True, True, 1234),
|
||||
"Spooler": (False, False, 0),
|
||||
"MSSQL$SQLEXPRESS": (True, True, 4321),
|
||||
"RemoteRegistry": (False, False, 0),
|
||||
"wuauserv": (False, False, 0),
|
||||
"AppReadiness": (False, True, 0),
|
||||
"BackupAgent": (False, True, 0),
|
||||
"VendorSync": (False, True, 0),
|
||||
"BthServ": (False, True, 0),
|
||||
}
|
||||
|
||||
def test_a_single_service_is_still_a_list(self):
|
||||
one = json.loads(FIXTURE.read_text())[0]
|
||||
assert list(_services(json.dumps(one))) == ["WinRM"]
|
||||
|
||||
def test_nothing_read_is_no_services(self):
|
||||
assert _services("") == {}
|
||||
|
||||
|
||||
class TestHowTheLastRunEnded:
|
||||
def test_a_running_service_succeeded(self):
|
||||
assert _services()["WinRM"] == {
|
||||
"name": "WinRM",
|
||||
"running": True,
|
||||
"enabled": True,
|
||||
"pid": 1234,
|
||||
"result": "success",
|
||||
"exit_code": None,
|
||||
"trigger_start": False,
|
||||
"account": "NT AUTHORITY\\NetworkService",
|
||||
}
|
||||
|
||||
def test_one_stopped_on_purpose_succeeded(self):
|
||||
assert (_services()["Spooler"]["result"], _services()["Spooler"]["exit_code"]) == (
|
||||
"success",
|
||||
None,
|
||||
)
|
||||
|
||||
def test_one_not_started_since_boot_has_no_result(self):
|
||||
"""1077: a delayed or a demand-start service that has not run yet."""
|
||||
service = _services()["AppReadiness"]
|
||||
assert (service["result"], service["exit_code"]) == (None, None)
|
||||
|
||||
def test_one_that_died_ended_with_its_exit_code(self):
|
||||
"""1067: the process terminated unexpectedly."""
|
||||
service = _services()["BackupAgent"]
|
||||
assert (service["result"], service["exit_code"]) == ("exit-code", 1067)
|
||||
|
||||
def test_a_service_specific_error_is_the_services_own_code(self):
|
||||
service = _services()["VendorSync"]
|
||||
assert (service["result"], service["exit_code"]) == ("exit-code", 2147942405)
|
||||
|
||||
def test_a_trigger_start_service_says_so(self):
|
||||
assert _services()["BthServ"]["trigger_start"] is True
|
||||
assert _services()["BackupAgent"]["trigger_start"] is False
|
||||
|
||||
def test_the_account_it_runs_as(self):
|
||||
assert _services()["BackupAgent"]["account"] == "CORP\\svc-backup"
|
||||
assert _services()["BthServ"]["account"] is None
|
||||
|
||||
def test_a_reading_without_the_new_fields_says_nothing_of_them(self):
|
||||
"""An older script's answer: running and enabled only, nothing invented."""
|
||||
old = [{"name": "WinRM", "state": "Stopped", "start_mode": "Auto", "pid": 0}]
|
||||
service = _services(json.dumps(old))["WinRM"]
|
||||
assert (service["result"], service["exit_code"], service["trigger_start"]) == (
|
||||
None,
|
||||
None,
|
||||
False,
|
||||
)
|
||||
|
||||
|
||||
class TestTheScript:
|
||||
def test_exit_codes_leave_the_host_as_wide_integers(self):
|
||||
"""``ServiceSpecificExitCode`` is a UInt32: ``[int]`` would throw on an HRESULT."""
|
||||
assert "[int64]$_.ExitCode" in mod._PS_SERVICES
|
||||
assert "[int64]$_.ServiceSpecificExitCode" in mod._PS_SERVICES
|
||||
|
||||
def test_trigger_start_is_read_once_from_the_registry(self):
|
||||
assert r"Services\*\TriggerInfo" in mod._PS_SERVICES
|
||||
assert "-ErrorAction SilentlyContinue" in mod._PS_SERVICES
|
||||
|
||||
def test_a_list_goes_through_input_object(self):
|
||||
assert "-InputObject @(" in mod._PS_SERVICES
|
||||
@@ -0,0 +1,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 & b < c" in raw
|
||||
assert "x > y & 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
|
||||
@@ -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
@@ -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
-16
@@ -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):
|
||||
@@ -349,19 +370,6 @@ class TestGetRouteTo:
|
||||
assert list(routes) == ["192.168.50.0/24"]
|
||||
|
||||
|
||||
class TestGetServices:
|
||||
def test_maps_state_and_start_mode(self):
|
||||
services = _driver(_PS_SERVICES=_fixture("services.json")).get_services()
|
||||
|
||||
assert services == [
|
||||
{"name": "WinRM", "running": True, "enabled": True, "pid": 1234},
|
||||
{"name": "Spooler", "running": False, "enabled": False, "pid": 0},
|
||||
{"name": "MSSQL$SQLEXPRESS", "running": True, "enabled": True, "pid": 4321},
|
||||
{"name": "RemoteRegistry", "running": False, "enabled": False, "pid": 0},
|
||||
{"name": "wuauserv", "running": False, "enabled": False, "pid": 0},
|
||||
]
|
||||
|
||||
|
||||
class TestGetListeningSockets:
|
||||
"""netOrk #673: what listens, and which Windows service it is."""
|
||||
|
||||
@@ -483,3 +491,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))
|
||||
@@ -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]
|
||||
+14
-2
@@ -13,8 +13,16 @@ from __future__ import annotations
|
||||
import argparse
|
||||
import getpass
|
||||
import pathlib
|
||||
import time
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import (
|
||||
WindowsDriver,
|
||||
event_channels,
|
||||
host_events,
|
||||
scheduled_tasks,
|
||||
services,
|
||||
time_sync,
|
||||
)
|
||||
from napalm_windows import windows as mod
|
||||
|
||||
SCRIPTS = {
|
||||
@@ -23,8 +31,12 @@ SCRIPTS = {
|
||||
"interfaces_ip": mod._PS_INTERFACES_IP,
|
||||
"arp": mod._PS_ARP,
|
||||
"routes": mod._PS_ROUTES,
|
||||
"services": mod._PS_SERVICES,
|
||||
"services": services._PS_SERVICES,
|
||||
"listening": mod._PS_LISTENING,
|
||||
"scheduled_tasks": scheduled_tasks._PS_SCHEDULED_TASKS,
|
||||
"time_sync": time_sync._PS_TIME_SYNC,
|
||||
"host_events": host_events.host_events_script(time.time() - 7 * 86400),
|
||||
"event_channels": event_channels._PS_EVENT_CHANNELS,
|
||||
}
|
||||
|
||||
OUT = pathlib.Path(__file__).parent / "harvest-out"
|
||||
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user