Author SHA1 Message Date
Christian Manivong 7a5c607ae4 feat(storage): disks, pools, volumes and drive health without smartctl (NetOrk/netork#2896)
WindowsStorageMixin implements napalm-device-types' HostStorageMixin, so
the host reports its storage and stays a host:

- get_disks: Get-PhysicalDisk with medium, bus, Windows' health and the
  Storage Spaces pool a disk is in; a Storage Spaces virtual disk is no
  physical disk.
- get_disk_smart: Get-StorageReliabilityCounter per disk (temperature,
  wear, power-on hours, uncorrected read and write errors). A counter
  that cannot be read is no counter, not an error; disks that report
  nothing are left out.
- get_disk_pools: Storage Spaces' pools.
- get_volumes: fixed volumes mounted at a drive letter or in a folder,
  with file system and health.

A disk whose medium Windows cannot tell and whose counters are empty (a
virtual disk, a RAID controller's logical disk) reads temperature -1 and
health "unknown". Every script probes its cmdlets first. The fixtures
are synthetic; the scripts are in harvest.py for the first real host.
2026-12-01 12:50:56 +01:00
16 changed files with 931 additions and 874 deletions

No files matched your search

+11 -14
View File
@@ -7,20 +7,17 @@ All notable changes to this driver. The format follows
## [Unreleased]
### Added
- The host firewall (NetOrk/netork#2894): `get_host_firewall` returns the Windows
Firewall under `windows` (napalm-device-types' `WindowsFirewallDict`), with `sources`
`["windows-firewall"]` and no netfilter chains. It reads the three profiles as the
firewall applies them (on or off, default inbound and outbound action, "block all
incoming connections", whether local rules apply), every enabled rule of the active
policy with its ports, addresses, program, service, interfaces and where it comes from
(group policy included), and the profile each connected interface is in. The filters
are read in bulk, one cmdlet per kind, so a host with hundreds of rules answers in one
script rather than one query per rule. Nothing is written.
- Windows features (NetOrk/netork#2898): `get_windows_features` lists every optional
feature of the host's image with its state (enabled, disabled, absent, unknown) from
`Win32_OptionalFeature`, under the names Windows uses on clients and servers alike
(`SMB1Protocol`, `MSMQ-Server`, `IIS-WebServerRole`, `Microsoft-Hyper-V`). It is what
a CVE that needs a role or feature is held against.
- Disks, pools, volumes and drive health without smartctl (NetOrk/netork#2896), through
napalm-device-types' `HostStorageMixin`, so the host stays a host. `get_disks` reads
`Get-PhysicalDisk` (model, serial, medium, NVMe, Windows' health, the Storage Spaces
pool a disk is in); `get_disk_smart` reads `Get-StorageReliabilityCounter` per disk
(temperature, wear, power-on hours, uncorrected read and write errors);
`get_disk_pools` reads Storage Spaces' pools; `get_volumes` the fixed volumes mounted at
a drive letter or in a folder, with file system and health. A disk whose counter cannot
be read -- the cmdlet needs an administrator, and virtual disks often have none -- has
no drive health rather than an error; a virtual disk or a RAID controller's logical
disk reads temperature -1 and health "unknown" instead of zeros and a "healthy" nobody
measured. A Storage Spaces virtual disk is not listed as a physical disk.
- 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
+25 -19
View File
@@ -43,8 +43,7 @@ handshake once.
| `manage_scheduled_job` | `Enable-`/`Disable-ScheduledTask`, `Start-ScheduledTask` (returns once started; the result shows in the next reading) |
| `put_scheduled_job` / `delete_scheduled_job` | `Register-ScheduledTask -Xml -Force` in the root folder, `Unregister-ScheduledTask`; an application's tasks only |
| `get_time_sync` / `configure_time_sync` | w32time's registry values (group policy first), `w32tm /query /status`, the registry's `TimeZoneInformation`; writes `NtpServer`/`Type` + `w32tm /config /update`, `Set-TimeZone`. See *Time sync* |
| `get_host_firewall` | The Windows Firewall under `windows` (no netfilter chains): the profiles' settings in force from `HNetCfg.FwPolicy2`, `AllowLocalFirewallRules` from `Get-NetFirewallProfile`, the enabled rules of `Get-NetFirewallRule -PolicyStore ActiveStore` with every filter read in bulk and joined on `InstanceID`, and `Get-NetConnectionProfile`. See *Host firewall* |
| `get_windows_features` | `Win32_OptionalFeature`: every optional feature of the image with its state, under DISM's names (`SMB1Protocol`, `MSMQ-Server`), a server's roles included |
| `get_disks` / `get_disk_smart` / `get_disk_pools` / `get_volumes` | `Get-PhysicalDisk`, `Get-StorageReliabilityCounter`, `Get-StoragePool -IsPrimordial $false`, `Get-Volume` + `Get-Partition`; no smartctl. See *Storage* |
`running_kernel` carries the full build including the update revision
(`10.0.20348.2340`): Windows ships fixes as UBR bumps, which is what CVE
@@ -99,25 +98,32 @@ napalm-device-types' `TimeSyncMixin`; both the servers and the zone are written.
zone with summer time switched off reads as `None`; writing the zone switches it
back on.
### Host firewall
### Storage
What the exposure chain holds a listening socket against (netork#2894). Read only: no
rule is ever written.
napalm-device-types' `HostStorageMixin` (NetOrk/netork#2896): the host's storage without
the storage role, so the driver stays a host. Nothing is installed; everything comes from
the Storage module's CIM classes.
* **Profiles:** on or off, the default inbound and outbound action and "block all
incoming connections" as the firewall applies them (`HNetCfg.FwPolicy2`, group
policy over local), and whether group policy lets local rules apply.
* **Rules:** every enabled rule of the active policy (`ActiveStore`, local and group
policy merged), inbound and outbound, each with where it comes from (`local`,
`group_policy`, `dynamic`, ...). Its filters -- ports, addresses, program, service,
app package, interfaces, interface types, IPsec -- are read with one cmdlet per
filter kind (`Get-NetFirewallPortFilter -All`, ...) and joined on the rule's
`InstanceID`: one filter query per rule takes minutes on a few hundred rules.
Addresses become CIDRs (a mask as its prefix, a range as the networks covering it);
Windows' keywords (`LocalSubnet`, `RPC`) are kept in lower case. A block rule whose
filters did not all come back is left out rather than read as blocking everything.
* **Connections:** the profile of each connected interface, from its network's category
(`DomainAuthenticated` is the domain profile); None where that could not be read.
* **Disks** are `Get-PhysicalDisk` (`PhysicalDisk<N>` by `DeviceId`): model, serial,
medium, bus (NVMe is its own type), Windows' `HealthStatus` (`Healthy`, `Warning`,
`Unhealthy` -> `healthy`, `warning`, `failed`) and, for disks in a Storage Spaces pool,
the pool. A Storage Spaces virtual disk is no physical disk and is not listed.
* **Drive health** (`get_disk_smart`) is `Get-StorageReliabilityCounter` per disk:
temperature and its highest, wear (`percentage_used`, not for spinning disks), power-on
hours, uncorrected read and write errors. It needs an administrator; a disk whose
counter cannot be read, or whose counters are all empty, has no drive health and is
left out. Windows writes `0` for a temperature it does not have, which reads as none.
* **Unknown is not healthy.** A disk whose medium Windows cannot tell and whose counters
are empty -- a virtual disk, a RAID controller's logical disk -- reads temperature `-1`
and health `unknown`: Windows calls it `Healthy`, which only says it is attached.
`Warning` and `Unhealthy` are always passed on.
* **Pools** are Storage Spaces (`storage-spaces`; `Simple`, `Mirror`, `Parity` ->
`stripe`, `mirror`, `parity`). Size and allocation are raw capacity.
* **Volumes** are the fixed volumes mounted at a drive letter (`C:`) or in a folder
(`C:\Logs`), with file system and health; the EFI and recovery partitions are mounted
nowhere and left out.
A host without the Storage module reads as having none; an empty answer raises.
Not yet: packages, Windows Update, health metrics, Hyper-V.
See netork#300 for the plan.
-357
View File
@@ -1,357 +0,0 @@
"""The Windows Firewall: profiles, rules and the profile of each connection (NetOrk/netork#2894).
:class:`WindowsHostFirewallMixin` gives the driver ``get_host_firewall``, the getter a
Linux driver answers with netfilter chains. A Windows host answers with napalm-device-types'
``WindowsFirewallDict`` under ``windows``, ``sources`` ``["windows-firewall"]`` and no
chains: its rules belong to profiles, and match a program and a service as well as ports
and addresses, which chains have no place for. Whether a socket is reachable is the
consumer's call; nothing here judges it, and nothing here writes a rule.
**One script, no per-rule queries.** ``Get-NetFirewallRule | Get-NetFirewallPortFilter``
asks the firewall once per rule and takes minutes for a few hundred rules. So every filter
kind is read in bulk (``Get-Net*Filter -All -PolicyStore ActiveStore``), only the enabled
rules' filters leave the host, and the join on the rule's ``InstanceID`` is done here.
- **The active policy** (``ActiveStore``): what the host applies, local rules and group
policy's merged. Each rule says where it comes from (``PolicyStoreSourceType``: local,
group policy, a service's dynamic rule, ...). Only enabled rules are read.
- **The profiles' settings in force** come from the firewall's COM object
(``HNetCfg.FwPolicy2``), which answers with the effective value where
``Get-NetFirewallProfile`` would say ``NotConfigured``: on or off, the default inbound and
outbound action, "block all incoming connections". Whether group policy lets local rules
apply (``AllowLocalFirewallRules``) only ``Get-NetFirewallProfile`` says;
``NotConfigured`` there is the default, which lets them.
- **The profile of each connected interface** is its network's category
(``Get-NetConnectionProfile``): ``DomainAuthenticated`` is the domain profile. Where that
cannot be read, ``connections`` is None -- not "no interface is connected".
**A filter that was not read never widens a block.** Every rule has every filter, so one
missing from the bulk read is a reading that went wrong. An allow rule keeps "any" for it,
which can only make more reachable; a block rule without one is left out, since "any"
would have it block everything.
"""
from __future__ import annotations
import ipaddress
import json
import re
from typing import TYPE_CHECKING, Any
from napalm_device_types import WINDOWS_FIREWALL_PROFILES
from napalm_device_types.host_firewall_models import (
WindowsFirewallConnectionDict,
WindowsFirewallProfileDict,
WindowsFirewallRuleDict,
)
from napalm_device_types.models import HostFirewallDict
from napalm_windows._powershell import _as_list
SOURCE = "windows-firewall"
# The COM object's profile types (NET_FW_PROFILE_TYPE2) and actions (NET_FW_ACTION).
_PS_HOST_FIREWALL = r"""
$ErrorActionPreference = 'Stop'
$store = 'ActiveStore'
$fw = New-Object -ComObject HNetCfg.FwPolicy2
$local = @{}
try {
foreach ($p in @(Get-NetFirewallProfile -PolicyStore $store)) {
$local[([string]$p.Name).ToLower()] = [string]$p.AllowLocalFirewallRules
}
} catch { }
$types = @{ domain = 1; private = 2; public = 4 }
$profiles = @(foreach ($name in @('domain', 'private', 'public')) {
$t = $types[$name]
[pscustomobject]@{
name = $name
enabled = [bool]$fw.FirewallEnabled($t)
default_inbound = [int]$fw.DefaultInboundAction($t)
default_outbound = [int]$fw.DefaultOutboundAction($t)
block_all_inbound = [bool]$fw.BlockAllInboundTraffic($t)
local_rules = $local[$name]
}
})
$rules = @(Get-NetFirewallRule -PolicyStore ActiveStore -Enabled True)
$ids = @{}
foreach ($r in $rules) { $ids[[string]$r.InstanceID] = $true }
function Of($items) { @($items | Where-Object { $ids.ContainsKey([string]$_.InstanceID) }) }
function AsStrings($values) { @($values | ForEach-Object { [string]$_ }) }
$pf = Of (Get-NetFirewallPortFilter -All -PolicyStore ActiveStore)
$af = Of (Get-NetFirewallAddressFilter -All -PolicyStore ActiveStore)
$apf = Of (Get-NetFirewallApplicationFilter -All -PolicyStore ActiveStore)
$sf = Of (Get-NetFirewallServiceFilter -All -PolicyStore ActiveStore)
$if_ = Of (Get-NetFirewallInterfaceFilter -All -PolicyStore ActiveStore)
$itf = Of (Get-NetFirewallInterfaceTypeFilter -All -PolicyStore ActiveStore)
$sec = Of (Get-NetFirewallSecurityFilter -All -PolicyStore ActiveStore)
$connections = $null
try {
$connections = @(Get-NetConnectionProfile | ForEach-Object {
[pscustomobject]@{
interface = [string]$_.InterfaceAlias
category = [string]$_.NetworkCategory
}
})
} catch { $connections = $null }
ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
profiles = $profiles
rules = @($rules | ForEach-Object {
[pscustomobject]@{
id = [string]$_.InstanceID
name = [string]$_.DisplayName
group = [string]$_.DisplayGroup
direction = [string]$_.Direction
action = [string]$_.Action
profile = [string]$_.Profile
source = [string]$_.PolicyStoreSourceType
}
})
ports = @($pf | ForEach-Object {
[pscustomobject]@{
id = [string]$_.InstanceID; protocol = [string]$_.Protocol
local = @(AsStrings $_.LocalPort); remote = @(AsStrings $_.RemotePort)
}
})
addresses = @($af | ForEach-Object {
[pscustomobject]@{
id = [string]$_.InstanceID
local = @(AsStrings $_.LocalAddress); remote = @(AsStrings $_.RemoteAddress)
}
})
applications = @($apf | ForEach-Object {
[pscustomobject]@{
id = [string]$_.InstanceID; program = [string]$_.Program; package = [string]$_.Package
}
})
services = @($sf | ForEach-Object {
[pscustomobject]@{ id = [string]$_.InstanceID; service = [string]$_.Service }
})
interfaces = @($if_ | ForEach-Object {
[pscustomobject]@{ id = [string]$_.InstanceID; aliases = @(AsStrings $_.InterfaceAlias) }
})
interface_types = @($itf | ForEach-Object {
[pscustomobject]@{ id = [string]$_.InstanceID; types = [string]$_.InterfaceType }
})
security = @($sec | ForEach-Object {
[pscustomobject]@{
id = [string]$_.InstanceID; authentication = [string]$_.Authentication
override_block = [bool]$_.OverrideBlockRules
}
})
connections = $connections
})
"""
#: NET_FW_ACTION: what the COM object answers for a default action.
_ACTIONS = {0: "block", 1: "allow"}
_CATEGORIES = {"domainauthenticated": "domain", "private": "private", "public": "public"}
_PROTOCOLS = {"6": "tcp", "17": "udp", "1": "icmpv4", "58": "icmpv6"}
_ANY = "any"
_CAMEL = re.compile(r"(?<=[a-z])(?=[A-Z])")
#: The filter kinds a rule's matching depends on: a block rule without one is left out.
_REQUIRED = ("ports", "addresses", "applications", "services")
def _snake(value: str) -> str:
"""``GroupPolicy`` -> ``group_policy``, ``RemoteAccess`` -> ``remote_access``."""
return _CAMEL.sub("_", value.strip()).lower()
def _flags(value: Any) -> list[str] | None:
"""An enum of flags as PowerShell prints it (``Domain, Private``); None for ``Any``."""
names = [_snake(v) for v in str(value or "").split(",") if v.strip()]
if not names or _ANY in names:
return None
return names
def _profiles(value: Any) -> list[str] | None:
names = _flags(value)
if names is None:
return None
known: list[str] = [n for n in WINDOWS_FIREWALL_PROFILES if n in names]
return known or None
def _protocol(value: Any) -> str | None:
text = str(value or "").strip().lower()
if not text or text == _ANY:
return None
return _PROTOCOLS.get(text, text)
def _values(value: Any) -> list[str] | None:
"""A filter's list as Windows prints it; None for ``Any`` (or nothing)."""
values = [str(v).strip() for v in _as_list(value) if str(v).strip()]
if not values or any(v.lower() == _ANY for v in values):
return None
return values
def _ports(value: Any) -> list[str] | None:
values = _values(value)
return None if values is None else [v.lower() for v in values]
def _address(text: str) -> list[str]:
"""One address entry as CIDRs: a mask (``10.0.0.0/255.0.0.0``) as its prefix, a range
as the networks that cover it, a single address as a host route; a keyword lowered."""
low, sep, high = text.partition("-")
try:
if sep:
first, last = ipaddress.ip_address(low.strip()), ipaddress.ip_address(high.strip())
return [str(n) for n in ipaddress.summarize_address_range(first, last)]
return [str(ipaddress.ip_network(text, strict=False))]
except (TypeError, ValueError):
return [text.lower()]
def _addresses(value: Any) -> list[str] | None:
values = _values(value)
if values is None:
return None
return [cidr for v in values for cidr in _address(v)]
def _named(value: Any) -> str | None:
"""A program, package or service as named; None for ``Any`` or nothing."""
text = str(value or "").strip()
return None if not text or text.lower() == _ANY else text
def _by_id(raw: dict[str, Any], kind: str) -> dict[str, dict[str, Any]]:
return {str(f.get("id")): f for f in _as_list(raw.get(kind)) if isinstance(f, dict)}
class _Filters:
"""The bulk-read filters of every kind, by rule id."""
def __init__(self, raw: dict[str, Any]) -> None:
self.kinds = {
kind: _by_id(raw, kind)
for kind in (*_REQUIRED, "interfaces", "interface_types", "security")
}
def complete(self, rule_id: str) -> bool:
return all(rule_id in self.kinds[kind] for kind in _REQUIRED)
def of(self, rule_id: str, kind: str) -> dict[str, Any]:
return self.kinds[kind].get(rule_id) or {}
def _rule(rule: dict[str, Any], filters: _Filters) -> WindowsFirewallRuleDict:
rule_id = str(rule.get("id") or "")
ports, addresses = filters.of(rule_id, "ports"), filters.of(rule_id, "addresses")
application, security = filters.of(rule_id, "applications"), filters.of(rule_id, "security")
source = _snake(str(rule.get("source") or ""))
return {
"id": rule_id,
"name": str(rule.get("name") or rule_id),
"group": str(rule.get("group") or "") or None,
"direction": str(rule.get("direction") or "").lower(),
"action": str(rule.get("action") or "").lower(),
"profiles": _profiles(rule.get("profile")),
"protocol": _protocol(ports.get("protocol")),
"local_ports": _ports(ports.get("local")),
"remote_ports": _ports(ports.get("remote")),
"local_addresses": _addresses(addresses.get("local")),
"remote_addresses": _addresses(addresses.get("remote")),
"program": _named(application.get("program")),
"service": _named(filters.of(rule_id, "services").get("service")),
"package": _named(application.get("package")),
"interfaces": _values(filters.of(rule_id, "interfaces").get("aliases")),
"interface_types": _flags(filters.of(rule_id, "interface_types").get("types")),
"authenticated": str(security.get("authentication") or "notrequired").lower()
!= "notrequired",
"override_block": bool(security.get("override_block")),
"source": source or None,
}
def _rules(raw: dict[str, Any]) -> list[WindowsFirewallRuleDict]:
filters = _Filters(raw)
rules: list[WindowsFirewallRuleDict] = []
for rule in _as_list(raw.get("rules")):
if not isinstance(rule, dict):
continue
read = _rule(rule, filters)
if read["action"] == "block" and not filters.complete(read["id"]):
continue
rules.append(read)
return rules
def _setting(value: Any) -> bool | None:
"""``AllowLocalFirewallRules``: ``False`` only where group policy says so."""
text = str(value or "").strip().lower()
if text in ("true", "notconfigured"):
return True
return False if text == "false" else None
def _bool(value: Any) -> bool | None:
return value if isinstance(value, bool) else None
def _profile(raw: dict[str, Any]) -> WindowsFirewallProfileDict:
return {
"name": str(raw.get("name") or ""),
"enabled": _bool(raw.get("enabled")),
"default_inbound": _ACTIONS.get(raw.get("default_inbound")), # type: ignore[arg-type]
"default_outbound": _ACTIONS.get(raw.get("default_outbound")), # type: ignore[arg-type]
"block_all_inbound": _bool(raw.get("block_all_inbound")),
"local_rules": _setting(raw.get("local_rules")),
}
def _connections(value: Any) -> list[WindowsFirewallConnectionDict] | None:
if value is None:
return None
found: list[WindowsFirewallConnectionDict] = []
for entry in _as_list(value):
if not isinstance(entry, dict):
continue
profile = _CATEGORIES.get(str(entry.get("category") or "").lower())
if profile and entry.get("interface"):
found.append({"interface": str(entry["interface"]), "profile": profile})
return found
def parse_host_firewall(raw: Any) -> HostFirewallDict:
"""What ``_PS_HOST_FIREWALL`` emitted, joined and normalised.
:raises ValueError: when the reading came back empty or without the profiles.
"""
if not isinstance(raw, dict):
raise ValueError("the firewall reading came back empty")
profiles = [_profile(p) for p in _as_list(raw.get("profiles")) if isinstance(p, dict)]
if not profiles:
raise ValueError("the firewall reading has no profiles")
return {
"sources": [SOURCE],
"chains": [],
"windows": {
"profiles": profiles,
"rules": _rules(raw),
"connections": _connections(raw.get("connections")),
},
}
class WindowsHostFirewallMixin:
"""``get_host_firewall`` for a Windows host; the driver carries the script."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def get_host_firewall(self) -> HostFirewallDict:
"""The Windows Firewall's profiles, enabled rules and the profile of each
connected interface, under ``windows``; see the module.
:raises ValueError: when the reading came back empty or without the profiles.
"""
out = self._run_raw(_PS_HOST_FIREWALL).strip()
return parse_host_firewall(json.loads(out) if out else None)
+355
View File
@@ -0,0 +1,355 @@
"""Disks, pools, volumes and drive health on Windows, without smartctl (NetOrk/netork#2896).
:class:`WindowsStorageMixin` implements napalm-device-types'
:class:`~napalm_device_types.host_storage.HostStorageMixin` for the driver, which carries
each script across ``PsrpTransport.run``. A Windows host has disks; it is not a storage
device, so the getters come with no role and the driver stays ``windows``.
Everything is read from the Storage module's CIM classes, the same on every Windows
Server 2016+ and Windows 10/11, without installing anything:
- **Disks** are ``Get-PhysicalDisk``: model, serial, medium (``MediaType``), bus
(``BusType``; NVMe is a type of its own) and Windows' verdict (``HealthStatus``). A
Storage Spaces virtual disk (``BusType`` ``Spaces``) is built from other disks and is no
physical disk; its members are. Which pool a disk belongs to is
``Get-StoragePool -IsPrimordial $false`` with its member disks.
- **Drive health** is ``Get-StorageReliabilityCounter`` per disk: temperature, wear,
power-on hours, uncorrected read and write errors. It needs an administrator, and a
virtual disk often has none: a disk whose counter cannot be read has no counter, which
is "unknown", not an error. Windows writes ``0`` where a drive does not report a value,
so a zero temperature is none, and a disk whose counters are all empty reports nothing.
- **Health without a measurement is "unknown".** A disk whose medium Windows cannot tell
(``MediaType`` ``Unspecified``) and whose counters are empty is a virtual disk or a RAID
controller's logical disk; Windows calls it ``Healthy``, which says it is attached, not
that a drive is well. Its health reads ``unknown``. ``Warning`` and ``Unhealthy`` are
always passed on.
- **Pools** are Storage Spaces' ``Get-StoragePool -IsPrimordial $false``. Their size and
allocation are raw capacity: what is usable depends on each virtual disk's resiliency.
- **Volumes** are ``Get-Volume``'s fixed volumes, mounted at a drive letter or in a
folder (``Get-Partition``'s ``AccessPaths``). A volume mounted nowhere -- the EFI system
partition, the recovery partition -- is left out.
Each script asks ``Get-Command`` first, so a host without the Storage module answers "not
supported" (empty) rather than failing. Drive health is read with the disks, in one round
trip; ``get_disks`` and ``get_disk_smart`` each send it.
"""
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any
from napalm_device_types.host_storage import DiskSmartDict, HostStorageMixin, HostVolumeDict
from napalm_device_types.models import DiskPoolDict, LogicalVolumeDict, PhysicalDiskDict
from napalm_windows._powershell import _as_list
_PS_DISKS = r"""
$ErrorActionPreference = 'Stop'
if (-not (Get-Command -Name Get-PhysicalDisk -ErrorAction SilentlyContinue)) {
ConvertTo-Json -Compress -InputObject ([pscustomobject]@{ supported = $false })
return
}
$readCounters = [bool](
Get-Command -Name Get-StorageReliabilityCounter -ErrorAction SilentlyContinue
)
$pools = @{}
if (Get-Command -Name Get-StoragePool -ErrorAction SilentlyContinue) {
try {
foreach ($pool in @(Get-StoragePool -IsPrimordial $false)) {
foreach ($member in @(Get-PhysicalDisk -StoragePool $pool)) {
$pools[[string]$member.UniqueId] = [string]$pool.FriendlyName
}
}
} catch { }
}
$disks = @(Get-PhysicalDisk | ForEach-Object {
$disk = $_
$counter = $null
if ($readCounters) {
try { $counter = $disk | Get-StorageReliabilityCounter } catch { $counter = $null }
}
[pscustomobject]@{
device_id = [string]$disk.DeviceId
unique_id = [string]$disk.UniqueId
name = [string]$disk.FriendlyName
model = [string]$disk.Model
vendor = [string]$disk.Manufacturer
serial = [string]$disk.SerialNumber
media_type = [string]$disk.MediaType
bus_type = [string]$disk.BusType
health = [string]$disk.HealthStatus
size = $disk.Size
spindle = $disk.SpindleSpeed
pool = $pools[[string]$disk.UniqueId]
counter = if ($counter) {
[pscustomobject]@{
temperature = $counter.Temperature
temperature_max = $counter.TemperatureMax
wear = $counter.Wear
power_on_hours = $counter.PowerOnHours
read_errors_uncorrected = $counter.ReadErrorsUncorrected
write_errors_uncorrected = $counter.WriteErrorsUncorrected
}
} else { $null }
}
})
ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
supported = $true
counters = $readCounters
disks = $disks
})
"""
_PS_STORAGE_POOLS = r"""
$ErrorActionPreference = 'Stop'
if (-not (Get-Command -Name Get-StoragePool -ErrorAction SilentlyContinue)) {
ConvertTo-Json -Compress -InputObject ([pscustomobject]@{ supported = $false })
return
}
ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
supported = $true
pools = @(Get-StoragePool -IsPrimordial $false | ForEach-Object {
$pool = $_
[pscustomobject]@{
name = [string]$pool.FriendlyName
health = [string]$pool.HealthStatus
operational = @($pool.OperationalStatus | ForEach-Object { [string]$_ })
size = $pool.Size
allocated = $pool.AllocatedSize
resiliency = [string]$pool.ResiliencySettingNameDefault
read_only = [bool]$pool.IsReadOnly
disks = @(Get-PhysicalDisk -StoragePool $pool | ForEach-Object {
[pscustomobject]@{
device_id = [string]$_.DeviceId
unique_id = [string]$_.UniqueId
}
})
}
})
})
"""
_PS_VOLUMES = r"""
$ErrorActionPreference = 'Stop'
if (-not (Get-Command -Name Get-Volume -ErrorAction SilentlyContinue)) {
ConvertTo-Json -Compress -InputObject ([pscustomobject]@{ supported = $false })
return
}
$mounts = @{}
try {
foreach ($partition in @(Get-Partition)) {
$paths = @($partition.AccessPaths | Where-Object { $_ })
$folders = @($paths | Where-Object { $_ -notlike '\\?\*' })
foreach ($path in @($paths | Where-Object { $_ -like '\\?\Volume*' })) {
$mounts[$path] = $folders
}
}
} catch { }
ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
supported = $true
volumes = @(Get-Volume | Where-Object { [string]$_.DriveType -eq 'Fixed' } | ForEach-Object {
$volume = $_
[pscustomobject]@{
letter = [string]$volume.DriveLetter
label = [string]$volume.FileSystemLabel
file_system = [string]$volume.FileSystem
size = $volume.Size
remaining = $volume.SizeRemaining
health = [string]$volume.HealthStatus
path = [string]$volume.Path
mounts = @($mounts[[string]$volume.Path])
}
})
})
"""
#: ``HealthStatus`` as the contract says it; anything else is "unknown".
_HEALTH = {"healthy": "healthy", "warning": "warning", "unhealthy": "failed"}
#: The same verdict in drive-health terms.
_DRIVE_HEALTH = {"healthy": "ok", "warning": "warning", "unhealthy": "failed"}
_MEDIA = {"hdd": "hdd", "ssd": "ssd", "scm": "ssd"}
_POOL_STATUS = {"healthy": "online", "warning": "degraded", "unhealthy": "faulted"}
_LEVELS = {"simple": "stripe", "mirror": "mirror", "parity": "parity"}
#: Buses of a disk built from other disks, not a drive.
_VIRTUAL_BUSES = frozenset({"spaces", "storage spaces"})
#: ``SpindleSpeed`` when Windows does not know it.
_UNKNOWN_SPEED = 0xFFFFFFFF
def _text(value: Any) -> str:
return str(value or "").strip()
def _number(value: Any) -> int | None:
"""A counter's value; ``None`` when the drive does not report it."""
return None if value is None else int(value)
def _positive(value: Any) -> int | None:
"""A value Windows writes as ``0`` when it has none (a temperature)."""
number = _number(value)
return number if number else None
def _slot(device_id: Any, unique_id: Any) -> str:
"""``PhysicalDisk<N>``, as ``Get-PhysicalDisk`` names a disk; its id when it has no number."""
number = _text(device_id)
return f"PhysicalDisk{number}" if number else _text(unique_id)
class _Disk:
"""One disk of ``_PS_DISKS``."""
def __init__(self, raw: dict[str, Any]) -> None:
self.raw = raw
self.slot = _slot(raw.get("device_id"), raw.get("unique_id"))
self.counter: dict[str, Any] = raw.get("counter") or {}
self.reports = any(value for value in self.counter.values())
bus = _text(raw.get("bus_type")).lower()
media = _MEDIA.get(_text(raw.get("media_type")).lower(), "unknown")
self.type = "nvme" if bus == "nvme" else media
self.is_physical = bus not in _VIRTUAL_BUSES
self.status = _text(raw.get("health")).lower()
def health(self) -> str:
verdict = _HEALTH.get(self.status, "unknown")
if verdict == "healthy" and self.type == "unknown" and not self.reports:
return "unknown"
return verdict
def disk(self) -> PhysicalDiskDict:
spindle = int(self.raw.get("spindle") or 0)
return {
"slot": self.slot,
"model": _text(self.raw.get("model") or self.raw.get("name")),
"serial": _text(self.raw.get("serial")),
"vendor": _text(self.raw.get("vendor")),
"type": self.type,
"size": int(self.raw.get("size") or 0),
"rpm": spindle if spindle != _UNKNOWN_SPEED else 0,
"temperature": _positive(self.counter.get("temperature")) or -1,
"health": self.health(),
"pool": _text(self.raw.get("pool")),
}
def smart(self) -> DiskSmartDict:
c = self.counter
return {
"model": _text(self.raw.get("model") or self.raw.get("name")),
"serial": _text(self.raw.get("serial")),
"type": self.type,
"size": int(self.raw.get("size") or 0),
"health": _DRIVE_HEALTH.get(self.status, "unknown"),
"wearout": None,
"temperature": _positive(c.get("temperature")),
# A spinning disk does not wear out by writes; its Wear is no reading.
"percentage_used": None if self.type == "hdd" else _number(c.get("wear")),
"available_spare": None,
"reallocated_sectors": None,
"power_on_hours": _number(c.get("power_on_hours")),
"temperature_max": _positive(c.get("temperature_max")),
"read_errors_uncorrected": _number(c.get("read_errors_uncorrected")),
"write_errors_uncorrected": _number(c.get("write_errors_uncorrected")),
}
def _pool(raw: dict[str, Any]) -> DiskPoolDict:
total, used = int(raw.get("size") or 0), int(raw.get("allocated") or 0)
resiliency = _text(raw.get("resiliency")).lower()
return {
"name": _text(raw.get("name")),
"type": "storage-spaces",
"level": _LEVELS.get(resiliency, resiliency or "unknown"),
"status": _POOL_STATUS.get(_text(raw.get("health")).lower(), "unknown"),
"total": total,
"used": used,
"available": max(total - used, 0),
"disks": [
_slot(d.get("device_id"), d.get("unique_id")) for d in _as_list(raw.get("disks"))
],
"auto_expand": False,
"dedup": False,
"compression": "off",
}
def _mount(raw: dict[str, Any]) -> tuple[str, str] | None:
"""The volume's key and mount point: its drive letter, else the first folder it is
mounted in; None when it is mounted nowhere."""
letter = _text(raw.get("letter")).split("\x00", 1)[0]
if letter:
return f"{letter}:", f"{letter}:\\"
folders = [_text(m) for m in _as_list(raw.get("mounts")) if _text(m)]
if not folders:
return None
return folders[0].rstrip("\\"), folders[0]
def _volume(raw: dict[str, Any], key: str, mountpoint: str) -> HostVolumeDict:
total, available = int(raw.get("size") or 0), int(raw.get("remaining") or 0)
return {
"name": _text(raw.get("label")) or key,
"pool": "",
"type": "filesystem",
"total": total,
"used": max(total - available, 0),
"available": available,
"mountpoint": mountpoint,
"compression": "",
"dedup": False,
"readonly": False,
"snapshots": 0,
"file_system": _text(raw.get("file_system")),
"health": _HEALTH.get(_text(raw.get("health")).lower(), "unknown"),
}
class WindowsStorageMixin(HostStorageMixin):
"""The Storage module's disks, pools, volumes and reliability counters."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def _storage_read(self, script: str, what: str) -> dict[str, Any] | None:
"""The script's answer; None when the host has no Storage module.
:raises ValueError: when the reading came back empty -- it could not look.
"""
out = self._run_raw(script).strip()
raw = json.loads(out) if out else None
if not isinstance(raw, dict):
raise ValueError(f"the {what} reading came back empty")
return raw if raw.get("supported") else None
def _disks(self) -> list[_Disk]:
raw = self._storage_read(_PS_DISKS, "disk")
if raw is None:
return []
disks = (_Disk(d) for d in _as_list(raw.get("disks")))
return [d for d in disks if d.is_physical]
def get_disks(self) -> list[PhysicalDiskDict]:
"""``Get-PhysicalDisk`` with each disk's temperature; see the module."""
return [d.disk() for d in self._disks()]
def get_disk_smart(self) -> dict[str, DiskSmartDict]:
"""``Get-StorageReliabilityCounter`` per disk; disks that report nothing are left out."""
return {d.slot: d.smart() for d in self._disks() if d.reports}
def get_disk_pools(self) -> dict[str, DiskPoolDict]:
"""Storage Spaces' pools; ``{}`` on a host without any."""
raw = self._storage_read(_PS_STORAGE_POOLS, "storage pool")
pools = [_pool(p) for p in _as_list((raw or {}).get("pools"))]
return {p["name"]: p for p in pools}
def get_volumes(self) -> dict[str, LogicalVolumeDict]:
"""``Get-Volume``'s fixed volumes that are mounted somewhere, keyed by where."""
raw = self._storage_read(_PS_VOLUMES, "volume")
volumes: dict[str, LogicalVolumeDict] = {}
for entry in _as_list((raw or {}).get("volumes")):
mount = _mount(entry)
if mount is not None:
volumes[mount[0]] = _volume(entry, *mount)
return volumes
+2 -9
View File
@@ -27,11 +27,10 @@ from napalm_device_types import FingerprintRule, OSDriver, PortSpec
from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict, ServiceDict
from napalm_windows._powershell import _as_list, _ps_quote
from napalm_windows.host_firewall import WindowsHostFirewallMixin
from napalm_windows.scheduled_tasks import WindowsScheduledJobsMixin
from napalm_windows.storage import WindowsStorageMixin
from napalm_windows.time_sync import WindowsTimeSyncMixin
from napalm_windows.transport import PowerShellError, PsrpTransport
from napalm_windows.windows_features import WindowsFeaturesMixin
logger = logging.getLogger(__name__)
@@ -263,13 +262,7 @@ def _is_noise_route(destination: str) -> bool:
# ---------------------------------------------------------------------------
class WindowsDriver(
WindowsHostFirewallMixin,
WindowsFeaturesMixin,
WindowsScheduledJobsMixin,
WindowsTimeSyncMixin,
OSDriver,
):
class WindowsDriver(WindowsScheduledJobsMixin, WindowsTimeSyncMixin, WindowsStorageMixin, OSDriver):
"""NAPALM driver for Windows Server 2016+ and Windows 10/11.
``optional_args``:
-71
View File
@@ -1,71 +0,0 @@
"""Windows optional features: which roles and features a host has on (NetOrk/netork#2898).
:class:`WindowsFeaturesMixin` implements napalm-device-types'
:class:`~napalm_device_types.windows_features.WindowsFeaturesMixin`: the facts a CVE that
needs a role or feature -- the DNS Server, Hyper-V, IIS, SMB 1.0, Message Queuing --
is held against.
**One CIM query** (``Win32_OptionalFeature``), not ``Get-WindowsOptionalFeature -Online``,
which loads the DISM module and takes far longer, and not Server Manager's
``Get-WindowsFeature``, which a client has not. The class lists every feature the image
knows, on a client and a server, under the names DISM gives them (``SMB1Protocol``,
``MSMQ-Server``, ``IIS-WebServerRole``); a server's roles are among them under those
names. ``InstallState`` is 1 enabled, 2 disabled, 3 absent (the payload removed),
4 unknown. A pending change shows as the state the feature has now.
No feature at all is a reading that went wrong -- every image has features -- and raises
rather than reading as a host with none.
"""
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any
from napalm_device_types import WindowsFeaturesMixin as _Contract
from napalm_device_types.windows_features import WindowsFeatureDict, WindowsFeaturesDict
from napalm_windows._powershell import _as_list
_PS_WINDOWS_FEATURES = r"""
$ErrorActionPreference = 'Stop'
ConvertTo-Json -Compress -Depth 3 -InputObject @(
Get-CimInstance -ClassName Win32_OptionalFeature | ForEach-Object {
[pscustomobject]@{ name = [string]$_.Name; state = [int]$_.InstallState }
}
)
"""
#: Win32_OptionalFeature's InstallState.
_STATES = {1: "enabled", 2: "disabled", 3: "absent", 4: "unknown"}
def parse_windows_features(raw: Any) -> WindowsFeaturesDict:
"""What ``_PS_WINDOWS_FEATURES`` emitted, as names and states.
:raises ValueError: when no feature came back.
"""
features: list[WindowsFeatureDict] = []
for entry in _as_list(raw):
name = str(entry.get("name") or "").strip() if isinstance(entry, dict) else ""
if name:
features.append({"name": name, "state": _STATES.get(entry.get("state"), "unknown")})
if not features:
raise ValueError("the Windows features reading came back without features")
return {"features": features}
class WindowsFeaturesMixin(_Contract):
"""``get_windows_features`` for a Windows host; the driver carries the script."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def get_windows_features(self) -> WindowsFeaturesDict:
"""Every optional feature of the host's image with its state; see the module.
:raises ValueError: when no feature came back.
"""
out = self._run_raw(_PS_WINDOWS_FEATURES).strip()
return parse_windows_features(json.loads(out) if out else None)
+102
View File
@@ -0,0 +1,102 @@
{
"supported": true,
"counters": true,
"disks": [
{
"device_id": "0",
"unique_id": "eui.0025385A11B22C33",
"name": "Samsung SSD 980 PRO 1TB",
"model": "Samsung SSD 980 PRO 1TB",
"vendor": "",
"serial": "0025_385A_11B2_2C33.",
"media_type": "SSD",
"bus_type": "NVMe",
"health": "Healthy",
"size": 1000204886016,
"spindle": 0,
"pool": null,
"counter": {
"temperature": 41,
"temperature_max": 68,
"wear": 3,
"power_on_hours": 5120,
"read_errors_uncorrected": 0,
"write_errors_uncorrected": 0
}
},
{
"device_id": "1",
"unique_id": "50014EE2B1C2D3E4",
"name": "WDC WD40EFRX-68N32N0",
"model": "WDC WD40EFRX-68N32N0",
"vendor": "",
"serial": " WD-WCC7K1ABCDEF",
"media_type": "HDD",
"bus_type": "SATA",
"health": "Warning",
"size": 4000787030016,
"spindle": 5400,
"pool": "Pool1",
"counter": {
"temperature": 36,
"temperature_max": 51,
"wear": 0,
"power_on_hours": 31012,
"read_errors_uncorrected": 12,
"write_errors_uncorrected": 0
}
},
{
"device_id": "3",
"unique_id": "50014EE2B1C2D3F5",
"name": "WDC WD40EFRX-68N32N0",
"model": "WDC WD40EFRX-68N32N0",
"vendor": "",
"serial": "WD-WCC7K1ABCDF0",
"media_type": "HDD",
"bus_type": "SATA",
"health": "Healthy",
"size": 4000787030016,
"spindle": 4294967295,
"pool": "Pool1",
"counter": {
"temperature": 0,
"temperature_max": null,
"wear": 0,
"power_on_hours": 30990,
"read_errors_uncorrected": null,
"write_errors_uncorrected": null
}
},
{
"device_id": "4",
"unique_id": "600508B1001C5A6B7C8D9E0F1A2B3C4D",
"name": "HPE LOGICAL VOLUME",
"model": "LOGICAL VOLUME",
"vendor": "HPE",
"serial": "PDNLH0BRH9A1B2",
"media_type": "Unspecified",
"bus_type": "RAID",
"health": "Healthy",
"size": 1200210141184,
"spindle": 4294967295,
"pool": null,
"counter": null
},
{
"device_id": "",
"unique_id": "{6b2f0c1e-0b5a-4a5e-9d3f-1c2b3a4d5e6f}",
"name": "Data",
"model": "Storage Space",
"vendor": "Microsoft",
"serial": "",
"media_type": "Unspecified",
"bus_type": "Spaces",
"health": "Healthy",
"size": 2199023255552,
"spindle": 0,
"pool": null,
"counter": null
}
]
}
+28
View File
@@ -0,0 +1,28 @@
{
"supported": true,
"counters": true,
"disks": [
{
"device_id": "0",
"unique_id": "60022480A1B2C3D4E5F60718293A4B5C",
"name": "Msft Virtual Disk",
"model": "Virtual Disk",
"vendor": "Msft",
"serial": "",
"media_type": "Unspecified",
"bus_type": "SAS",
"health": "Healthy",
"size": 136365211648,
"spindle": 4294967295,
"pool": null,
"counter": {
"temperature": 0,
"temperature_max": 0,
"wear": 0,
"power_on_hours": null,
"read_errors_uncorrected": 0,
"write_errors_uncorrected": 0
}
}
]
}
-72
View File
@@ -1,72 +0,0 @@
{
"profiles": [
{"name": "domain", "enabled": true, "default_inbound": 0, "default_outbound": 1, "block_all_inbound": false, "local_rules": "NotConfigured"},
{"name": "private", "enabled": true, "default_inbound": 0, "default_outbound": 1, "block_all_inbound": false, "local_rules": "True"},
{"name": "public", "enabled": true, "default_inbound": 0, "default_outbound": 1, "block_all_inbound": false, "local_rules": "False"}
],
"rules": [
{"id": "RemoteDesktop-UserMode-In-TCP", "name": "Remote Desktop - User Mode (TCP-In)", "group": "Remote Desktop", "direction": "Inbound", "action": "Allow", "profile": "Any", "source": "Local"},
{"id": "FPS-SMB-In-TCP", "name": "File and Printer Sharing (SMB-In)", "group": "File and Printer Sharing", "direction": "Inbound", "action": "Allow", "profile": "Domain, Private", "source": "Local"},
{"id": "WINRM-HTTP-In-TCP-PUBLIC", "name": "Windows Remote Management (HTTP-In)", "group": "Windows Remote Management", "direction": "Inbound", "action": "Allow", "profile": "Public", "source": "Local"},
{"id": "{7A1D3F2E-0B4C-4C8E-9F61-2D5A8B3C1E90}", "name": "Line of business app", "group": "", "direction": "Inbound", "action": "Allow", "profile": "Public", "source": "Local"},
{"id": "{0C4E2B7A-51D3-4E8F-A6B9-3F7D1C2E8A45}", "name": "Block SQL Server from the internet", "group": "", "direction": "Inbound", "action": "Block", "profile": "Public", "source": "GroupPolicy"},
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "name": "Management subnets", "group": "", "direction": "Inbound", "action": "Allow", "profile": "Domain", "source": "GroupPolicy"},
{"id": "{5B8D2F4A-1E3C-4A7B-9C6D-8E0F2A4B6C81}", "name": "Block an unread filter", "group": "", "direction": "Inbound", "action": "Block", "profile": "Any", "source": "Local"},
{"id": "CoreNet-DNS-Out-UDP", "name": "Core Networking - DNS (UDP-Out)", "group": "Core Networking", "direction": "Outbound", "action": "Allow", "profile": "Any", "source": "Local"}
],
"ports": [
{"id": "RemoteDesktop-UserMode-In-TCP", "protocol": "TCP", "local": ["3389"], "remote": ["Any"]},
{"id": "FPS-SMB-In-TCP", "protocol": "TCP", "local": ["445"], "remote": ["Any"]},
{"id": "WINRM-HTTP-In-TCP-PUBLIC", "protocol": "TCP", "local": ["5985"], "remote": ["Any"]},
{"id": "{7A1D3F2E-0B4C-4C8E-9F61-2D5A8B3C1E90}", "protocol": "Any", "local": ["Any"], "remote": ["Any"]},
{"id": "{0C4E2B7A-51D3-4E8F-A6B9-3F7D1C2E8A45}", "protocol": "6", "local": ["1433", "1434"], "remote": ["Any"]},
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "protocol": "TCP", "local": ["RPC", "49152-65535"], "remote": ["Any"]},
{"id": "{5B8D2F4A-1E3C-4A7B-9C6D-8E0F2A4B6C81}", "protocol": "TCP", "local": ["8080"], "remote": ["Any"]},
{"id": "CoreNet-DNS-Out-UDP", "protocol": "UDP", "local": ["Any"], "remote": ["53"]}
],
"addresses": [
{"id": "RemoteDesktop-UserMode-In-TCP", "local": ["Any"], "remote": ["Any"]},
{"id": "FPS-SMB-In-TCP", "local": ["Any"], "remote": ["LocalSubnet"]},
{"id": "WINRM-HTTP-In-TCP-PUBLIC", "local": ["Any"], "remote": ["LocalSubnet"]},
{"id": "{7A1D3F2E-0B4C-4C8E-9F61-2D5A8B3C1E90}", "local": ["Any"], "remote": ["Any"]},
{"id": "{0C4E2B7A-51D3-4E8F-A6B9-3F7D1C2E8A45}", "local": ["Any"], "remote": ["Any"]},
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "local": ["Any"], "remote": ["10.0.0.0/255.0.0.0", "192.0.2.1-192.0.2.6", "2001:db8::/48", "198.51.100.7"]},
{"id": "CoreNet-DNS-Out-UDP", "local": ["Any"], "remote": ["DNS"]}
],
"applications": [
{"id": "RemoteDesktop-UserMode-In-TCP", "program": "%SystemRoot%\\system32\\svchost.exe", "package": ""},
{"id": "FPS-SMB-In-TCP", "program": "System", "package": ""},
{"id": "WINRM-HTTP-In-TCP-PUBLIC", "program": "System", "package": ""},
{"id": "{7A1D3F2E-0B4C-4C8E-9F61-2D5A8B3C1E90}", "program": "C:\\Program Files\\Contoso\\lob.exe", "package": ""},
{"id": "{0C4E2B7A-51D3-4E8F-A6B9-3F7D1C2E8A45}", "program": "Any", "package": ""},
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "program": "Any", "package": "S-1-15-2-1"},
{"id": "{5B8D2F4A-1E3C-4A7B-9C6D-8E0F2A4B6C81}", "program": "Any", "package": ""},
{"id": "CoreNet-DNS-Out-UDP", "program": "%SystemRoot%\\system32\\svchost.exe", "package": ""}
],
"services": [
{"id": "RemoteDesktop-UserMode-In-TCP", "service": "TermService"},
{"id": "FPS-SMB-In-TCP", "service": "Any"},
{"id": "WINRM-HTTP-In-TCP-PUBLIC", "service": "Any"},
{"id": "{7A1D3F2E-0B4C-4C8E-9F61-2D5A8B3C1E90}", "service": "Any"},
{"id": "{0C4E2B7A-51D3-4E8F-A6B9-3F7D1C2E8A45}", "service": "Any"},
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "service": "*"},
{"id": "{5B8D2F4A-1E3C-4A7B-9C6D-8E0F2A4B6C81}", "service": "Any"},
{"id": "CoreNet-DNS-Out-UDP", "service": "dnscache"}
],
"interfaces": [
{"id": "RemoteDesktop-UserMode-In-TCP", "aliases": ["Any"]},
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "aliases": ["Ethernet0"]}
],
"interface_types": [
{"id": "RemoteDesktop-UserMode-In-TCP", "types": "Any"},
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "types": "Wired, RemoteAccess"}
],
"security": [
{"id": "RemoteDesktop-UserMode-In-TCP", "authentication": "NotRequired", "override_block": false},
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "authentication": "Required", "override_block": true}
],
"connections": [
{"interface": "Ethernet0", "category": "DomainAuthenticated"},
{"interface": "Ethernet1", "category": "Public"}
]
}
+26
View File
@@ -0,0 +1,26 @@
{
"supported": true,
"pools": [
{
"name": "Pool1",
"health": "Warning",
"operational": [
"Degraded"
],
"size": 8001574060032,
"allocated": 2199023255552,
"resiliency": "Mirror",
"read_only": false,
"disks": [
{
"device_id": "1",
"unique_id": "50014EE2B1C2D3E4"
},
{
"device_id": "3",
"unique_id": "50014EE2B1C2D3F5"
}
]
}
]
}
+61
View File
@@ -0,0 +1,61 @@
{
"supported": true,
"volumes": [
{
"letter": "C",
"label": "",
"file_system": "NTFS",
"size": 999483936768,
"remaining": 712345698304,
"health": "Healthy",
"path": "\\\\?\\Volume{1f2e3d4c-0000-0000-0000-100000000000}\\",
"mounts": [
"C:\\"
]
},
{
"letter": "D",
"label": "Data",
"file_system": "ReFS",
"size": 2196875771904,
"remaining": 109521666048,
"health": "Warning",
"path": "\\\\?\\Volume{1f2e3d4c-0000-0000-0000-200000000000}\\",
"mounts": [
"D:\\"
]
},
{
"letter": "",
"label": "Logs",
"file_system": "NTFS",
"size": 1200191766528,
"remaining": 1100000000000,
"health": "Healthy",
"path": "\\\\?\\Volume{1f2e3d4c-0000-0000-0000-300000000000}\\",
"mounts": [
"C:\\Logs\\"
]
},
{
"letter": "",
"label": "",
"file_system": "FAT32",
"size": 104857600,
"remaining": 71303168,
"health": "Healthy",
"path": "\\\\?\\Volume{1f2e3d4c-0000-0000-0000-400000000000}\\",
"mounts": []
},
{
"letter": "",
"label": "",
"file_system": "NTFS",
"size": 681574400,
"remaining": 98566144,
"health": "Healthy",
"path": "\\\\?\\Volume{1f2e3d4c-0000-0000-0000-500000000000}\\",
"mounts": []
}
]
}
-8
View File
@@ -1,8 +0,0 @@
[
{"name": "SMB1Protocol", "state": 2},
{"name": "MSMQ-Server", "state": 1},
{"name": "IIS-WebServerRole", "state": 1},
{"name": "Microsoft-Hyper-V", "state": 3},
{"name": "DNS-Server-Full-Role", "state": 4},
{"name": "Printing-PrintToPDFServices-Features", "state": 1}
]
-222
View File
@@ -1,222 +0,0 @@
"""The Windows Firewall as the exposure chain reads it (NetOrk/netork#2894).
The script reads the profiles from the firewall's own COM object (the settings in
force, group policy over local), the enabled rules of the active policy, and every
filter in bulk -- one cmdlet per filter kind, never one per rule -- and the profile
of each connected interface. The rules and their filters are joined here, on the
rule's InstanceID. The fixture is what the script emits on a Windows Server.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_device_types import WINDOWS_FIREWALL_PROFILES
from napalm_windows import WindowsDriver
from napalm_windows import host_firewall as mod
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "host_firewall.json"
class FakeHost:
def __init__(self, answer: Any) -> None:
self.answer = answer
self.sent: list[str] = []
self.is_open = True
def run(self, script: str) -> str:
self.sent.append(script)
return self.answer if isinstance(self.answer, str) else json.dumps(self.answer)
def close(self) -> None:
self.is_open = False
def _read(answer: Any = None) -> dict[str, Any]:
driver = WindowsDriver("win", "u", "p")
host = FakeHost(json.loads(FIXTURE.read_text()) if answer is None else answer)
driver._transport = host # type: ignore[assignment]
reading = driver.get_host_firewall()
assert host.sent == [mod._PS_HOST_FIREWALL]
return dict(reading)
def _rule(reading: dict[str, Any], name: str) -> dict[str, Any]:
return next(r for r in reading["windows"]["rules"] if r["name"] == name)
def test_a_windows_reading_has_no_chains_and_names_its_source():
reading = _read()
assert reading["sources"] == ["windows-firewall"]
assert reading["chains"] == []
def test_the_profiles_are_the_settings_in_force():
profiles = _read()["windows"]["profiles"]
assert [p["name"] for p in profiles] == list(WINDOWS_FIREWALL_PROFILES)
assert profiles[0] == {
"name": "domain",
"enabled": True,
"default_inbound": "block",
"default_outbound": "allow",
"block_all_inbound": False,
# NotConfigured: the default, which lets local rules apply.
"local_rules": True,
}
assert profiles[2]["local_rules"] is False
def test_a_rule_carries_its_filters_joined_on_its_instance_id():
rdp = _rule(_read(), "Remote Desktop - User Mode (TCP-In)")
assert rdp == {
"id": "RemoteDesktop-UserMode-In-TCP",
"name": "Remote Desktop - User Mode (TCP-In)",
"group": "Remote Desktop",
"direction": "inbound",
"action": "allow",
"profiles": None,
"protocol": "tcp",
"local_ports": ["3389"],
"remote_ports": None,
"local_addresses": None,
"remote_addresses": None,
"program": "%SystemRoot%\\system32\\svchost.exe",
"service": "TermService",
"package": None,
"interfaces": None,
"interface_types": None,
"authenticated": False,
"override_block": False,
"source": "local",
}
def test_profiles_protocol_numbers_and_port_keywords_are_normalised():
reading = _read()
smb = _rule(reading, "File and Printer Sharing (SMB-In)")
assert smb["profiles"] == ["domain", "private"]
assert smb["remote_addresses"] == ["localsubnet"]
assert smb["program"] == "System"
sql = _rule(reading, "Block SQL Server from the internet")
assert (sql["action"], sql["protocol"], sql["local_ports"]) == (
"block",
"tcp",
["1433", "1434"],
)
assert sql["source"] == "group_policy"
mgmt = _rule(reading, "Management subnets")
assert mgmt["local_ports"] == ["rpc", "49152-65535"]
def test_addresses_become_cidrs_masks_and_ranges_included():
mgmt = _rule(_read(), "Management subnets")
assert mgmt["remote_addresses"] == [
"10.0.0.0/8",
"192.0.2.1/32",
"192.0.2.2/31",
"192.0.2.4/31",
"192.0.2.6/32",
"2001:db8::/48",
"198.51.100.7/32",
]
def test_a_range_across_families_is_kept_as_written():
raw = json.loads(FIXTURE.read_text())
raw["addresses"][0]["remote"] = ["10.0.0.1-::1"]
rdp = _rule(_read(raw), "Remote Desktop - User Mode (TCP-In)")
assert rdp["remote_addresses"] == ["10.0.0.1-::1"]
def test_the_rarer_filters_are_kept():
mgmt = _rule(_read(), "Management subnets")
assert mgmt["interfaces"] == ["Ethernet0"]
assert mgmt["interface_types"] == ["wired", "remote_access"]
assert mgmt["package"] == "S-1-15-2-1"
assert mgmt["service"] == "*"
assert (mgmt["authenticated"], mgmt["override_block"]) == (True, True)
def test_a_block_rule_whose_filter_was_not_read_is_left_out():
# A filter left unread would read as "any" and make the rule block everything.
names = [r["name"] for r in _read()["windows"]["rules"]]
assert "Block an unread filter" not in names
assert "Core Networking - DNS (UDP-Out)" in names
def test_an_allow_rule_whose_filter_was_not_read_matches_more_not_less():
raw = json.loads(FIXTURE.read_text())
raw["addresses"] = [a for a in raw["addresses"] if a["id"] != "FPS-SMB-In-TCP"]
smb = _rule(_read(raw), "File and Printer Sharing (SMB-In)")
assert smb["remote_addresses"] is None
def test_each_connection_names_its_profile():
connections = _read()["windows"]["connections"]
assert connections == [
{"interface": "Ethernet0", "profile": "domain"},
{"interface": "Ethernet1", "profile": "public"},
]
def test_connections_that_could_not_be_read_are_none_not_empty():
raw = json.loads(FIXTURE.read_text())
raw["connections"] = None
assert _read(raw)["windows"]["connections"] is None
def test_an_unknown_category_and_setting_say_nothing():
raw = json.loads(FIXTURE.read_text())
raw["connections"] = [{"interface": "Wi-Fi", "category": "Something"}, "junk"]
raw["rules"].append("junk")
raw["profiles"][0].update(default_inbound=7, local_rules=None, enabled=None)
windows = _read(raw)["windows"]
assert windows["connections"] == []
domain = windows["profiles"][0]
assert (domain["default_inbound"], domain["local_rules"], domain["enabled"]) == (
None,
None,
None,
)
def test_one_element_lists_arrive_bare_and_are_still_lists():
raw = json.loads(FIXTURE.read_text())
raw["rules"] = raw["rules"][0]
raw["ports"] = {**raw["ports"][0], "local": "3389"}
raw["addresses"] = raw["addresses"][0]
raw["applications"] = raw["applications"][0]
raw["services"] = raw["services"][0]
(rule,) = _read(raw)["windows"]["rules"]
assert rule["local_ports"] == ["3389"]
def test_a_reading_without_profiles_is_refused():
with pytest.raises(ValueError, match="firewall"):
_read("")
raw = json.loads(FIXTURE.read_text())
raw["profiles"] = []
with pytest.raises(ValueError, match="profiles"):
_read(raw)
def test_the_script_reads_every_filter_in_bulk():
script = mod._PS_HOST_FIREWALL
for cmdlet in (
"Get-NetFirewallPortFilter",
"Get-NetFirewallAddressFilter",
"Get-NetFirewallApplicationFilter",
"Get-NetFirewallServiceFilter",
"Get-NetFirewallInterfaceFilter",
"Get-NetFirewallInterfaceTypeFilter",
"Get-NetFirewallSecurityFilter",
):
assert f"{cmdlet} -All -PolicyStore ActiveStore" in script
assert "Get-NetFirewallRule -PolicyStore ActiveStore -Enabled True" in script
# Never a filter per rule: no pipeline from the rules into a filter cmdlet.
assert "| Get-NetFirewall" not in script
assert "$ErrorActionPreference = 'Stop'" in script
+317
View File
@@ -0,0 +1,317 @@
"""Disks, pools, volumes and drive health on Windows, without smartctl (NetOrk/netork#2896).
Each reading is one script whose JSON a fake host answers from
tests/fixtures/synthetic/: ``disks_server.json`` (an NVMe SSD, two SATA disks in a
Storage Spaces pool, a RAID controller's logical disk and a Storage Spaces virtual
disk), ``disks_vm.json`` (a Hyper-V guest's virtual disk with empty reliability
counters), ``storage_pools.json`` and ``volumes.json``.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_device_types import HostStorageMixin, OSDriver
from napalm_device_types.roles import primary_role_of, role_keys_of
from napalm_windows import WindowsDriver
from napalm_windows import storage as mod
FIXTURES = Path(__file__).parent / "fixtures" / "synthetic"
def _load(name: str) -> Any:
return json.loads((FIXTURES / name).read_text())
class FakeHost:
"""Answers each storage script with *answers*' entry for it."""
def __init__(self, answers: dict[str, Any]) -> None:
self.answers = answers
self.sent: list[str] = []
self.is_open = True
def run(self, script: str) -> str:
self.sent.append(script)
answer = self.answers[script]
return answer if isinstance(answer, str) else json.dumps(answer)
def close(self) -> None:
self.is_open = False
def _driver(**answers: Any) -> WindowsDriver:
scripts = {
"disks": mod._PS_DISKS,
"pools": mod._PS_STORAGE_POOLS,
"volumes": mod._PS_VOLUMES,
}
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeHost({scripts[k]: v for k, v in answers.items()}) # type: ignore[assignment]
return d
def _server() -> WindowsDriver:
return _driver(
disks=_load("disks_server.json"),
pools=_load("storage_pools.json"),
volumes=_load("volumes.json"),
)
# ---------------------------------------------------------------------------
# The contract
# ---------------------------------------------------------------------------
class TestContract:
def test_a_host_with_storage_stays_a_host(self):
assert issubclass(WindowsDriver, HostStorageMixin)
assert "storage" not in role_keys_of(WindowsDriver)
assert primary_role_of(WindowsDriver) == primary_role_of(OSDriver)
def test_every_getter_is_there(self):
for name in ("get_disks", "get_disk_pools", "get_volumes", "get_disk_smart"):
assert callable(getattr(WindowsDriver, name)), name
@pytest.mark.parametrize("script", ["_PS_DISKS", "_PS_STORAGE_POOLS", "_PS_VOLUMES"])
def test_scripts_follow_the_driver_conventions(self, script):
text = getattr(mod, script)
assert "$ErrorActionPreference = 'Stop'" in text
assert "ConvertTo-Json" in text
assert "Get-Command" in text # a missing cmdlet is "not supported", not an error
def test_counters_are_read_per_disk_and_may_fail(self):
"""Get-StorageReliabilityCounter needs an administrator and is missing on some
virtual disks: one disk's failure is that disk's missing counter."""
assert "try { $counter = $disk | Get-StorageReliabilityCounter }" in mod._PS_DISKS
assert "catch { $counter = $null }" in mod._PS_DISKS
def test_no_smartctl(self):
for script in (mod._PS_DISKS, mod._PS_STORAGE_POOLS, mod._PS_VOLUMES):
assert "smartctl" not in script
# ---------------------------------------------------------------------------
# get_disks
# ---------------------------------------------------------------------------
class TestDisks:
def test_an_nvme_ssd(self):
disk = _server().get_disks()[0]
assert disk == {
"slot": "PhysicalDisk0",
"model": "Samsung SSD 980 PRO 1TB",
"serial": "0025_385A_11B2_2C33.",
"vendor": "",
"type": "nvme",
"size": 1000204886016,
"rpm": 0,
"temperature": 41,
"health": "healthy",
"pool": "",
}
def test_a_pool_member_with_a_warning(self):
disk = _server().get_disks()[1]
assert disk["slot"] == "PhysicalDisk1"
assert disk["serial"] == "WD-WCC7K1ABCDEF" # ATA serials come padded
assert (disk["type"], disk["rpm"], disk["temperature"]) == ("hdd", 5400, 36)
assert (disk["health"], disk["pool"]) == ("warning", "Pool1")
def test_a_zero_temperature_and_an_unknown_speed_are_unknown(self):
disk = _server().get_disks()[2]
assert (disk["temperature"], disk["rpm"]) == (-1, 0)
assert disk["health"] == "healthy" # a real disk with thin counters keeps its verdict
def test_a_raid_logical_disk_has_no_drive_health(self):
"""Windows calls the controller's logical disk Healthy; that is no drive's verdict."""
disk = _server().get_disks()[3]
assert (disk["type"], disk["temperature"], disk["health"]) == ("unknown", -1, "unknown")
def test_a_storage_spaces_virtual_disk_is_no_physical_disk(self):
slots = [d["slot"] for d in _server().get_disks()]
assert slots == ["PhysicalDisk0", "PhysicalDisk1", "PhysicalDisk3", "PhysicalDisk4"]
def test_a_virtual_disk_with_empty_counters(self):
"""Temperature -1 and health "unknown", not zeros and not a "healthy" nobody
measured."""
[disk] = _driver(disks=_load("disks_vm.json")).get_disks()
assert disk["temperature"] == -1
assert disk["health"] == "unknown"
assert disk["type"] == "unknown"
def test_bad_news_is_never_unknown(self):
raw = _load("disks_vm.json")
raw["disks"][0]["health"] = "Unhealthy"
assert _driver(disks=raw).get_disks()[0]["health"] == "failed"
def test_a_disk_without_a_number_is_named_by_its_id(self):
raw = _load("disks_vm.json")
raw["disks"][0]["device_id"] = ""
slot = _driver(disks=raw).get_disks()[0]["slot"]
assert slot == "60022480A1B2C3D4E5F60718293A4B5C"
def test_without_the_storage_module_there_are_none(self):
assert _driver(disks={"supported": False}).get_disks() == []
def test_an_empty_answer_could_not_look(self):
with pytest.raises(ValueError, match="disk reading came back empty"):
_driver(disks="").get_disks()
def test_one_disk_arrives_bare(self):
"""ConvertTo-Json unwraps a one-element array; the parse wraps it again."""
raw = _load("disks_vm.json")
raw["disks"] = raw["disks"][0]
assert len(_driver(disks=raw).get_disks()) == 1
# ---------------------------------------------------------------------------
# get_disk_smart
# ---------------------------------------------------------------------------
class TestDiskSmart:
def test_the_reliability_counters_of_an_nvme_ssd(self):
smart = _server().get_disk_smart()
assert smart["PhysicalDisk0"] == {
"model": "Samsung SSD 980 PRO 1TB",
"serial": "0025_385A_11B2_2C33.",
"type": "nvme",
"size": 1000204886016,
"health": "ok",
"wearout": None,
"temperature": 41,
"percentage_used": 3,
"available_spare": None,
"reallocated_sectors": None,
"power_on_hours": 5120,
"temperature_max": 68,
"read_errors_uncorrected": 0,
"write_errors_uncorrected": 0,
}
def test_a_disk_with_errors_and_a_warning(self):
entry = _server().get_disk_smart()["PhysicalDisk1"]
assert entry["health"] == "warning"
assert entry["read_errors_uncorrected"] == 12
assert entry["percentage_used"] is None # a spinning disk does not wear out by writes
def test_thin_counters_are_none_where_empty(self):
entry = _server().get_disk_smart()["PhysicalDisk3"]
assert entry["temperature"] is None
assert entry["power_on_hours"] == 30990
assert entry["read_errors_uncorrected"] is None
def test_disks_that_report_nothing_are_left_out(self):
assert set(_server().get_disk_smart()) == {
"PhysicalDisk0",
"PhysicalDisk1",
"PhysicalDisk3",
}
def test_a_virtual_host_has_no_drive_health(self):
assert _driver(disks=_load("disks_vm.json")).get_disk_smart() == {}
def test_without_the_counter_cmdlet_there_is_none(self):
raw = _load("disks_server.json")
raw["counters"] = False
for disk in raw["disks"]:
disk["counter"] = None
assert _driver(disks=raw).get_disk_smart() == {}
def test_without_the_storage_module_there_is_none(self):
assert _driver(disks={"supported": False}).get_disk_smart() == {}
# ---------------------------------------------------------------------------
# get_disk_pools
# ---------------------------------------------------------------------------
class TestPools:
def test_a_degraded_mirror(self):
assert _server().get_disk_pools() == {
"Pool1": {
"name": "Pool1",
"type": "storage-spaces",
"level": "mirror",
"status": "degraded",
"total": 8001574060032,
"used": 2199023255552,
"available": 5802550804480,
"disks": ["PhysicalDisk1", "PhysicalDisk3"],
"auto_expand": False,
"dedup": False,
"compression": "off",
}
}
@pytest.mark.parametrize(
("health", "resiliency", "status", "level"),
[
("Healthy", "Simple", "online", "stripe"),
("Unhealthy", "Parity", "faulted", "parity"),
("Unknown", "", "unknown", "unknown"),
],
)
def test_status_and_level(self, health, resiliency, status, level):
raw = _load("storage_pools.json")
raw["pools"][0].update(health=health, resiliency=resiliency)
pool = _driver(pools=raw).get_disk_pools()["Pool1"]
assert (pool["status"], pool["level"]) == (status, level)
def test_no_pools(self):
assert _driver(pools={"supported": True, "pools": []}).get_disk_pools() == {}
def test_without_storage_spaces_there_are_none(self):
assert _driver(pools={"supported": False}).get_disk_pools() == {}
# ---------------------------------------------------------------------------
# get_volumes
# ---------------------------------------------------------------------------
class TestVolumes:
def test_the_system_drive(self):
assert _server().get_volumes()["C:"] == {
"name": "C:",
"pool": "",
"type": "filesystem",
"total": 999483936768,
"used": 287138238464,
"available": 712345698304,
"mountpoint": "C:\\",
"compression": "",
"dedup": False,
"readonly": False,
"snapshots": 0,
"file_system": "NTFS",
"health": "healthy",
}
def test_a_labelled_volume_with_a_warning(self):
volume = _server().get_volumes()["D:"]
assert (volume["name"], volume["file_system"]) == ("Data", "ReFS")
assert volume.get("health") == "warning"
def test_a_volume_mounted_in_a_folder(self):
volume = _server().get_volumes()["C:\\Logs"]
assert (volume["name"], volume["mountpoint"]) == ("Logs", "C:\\Logs\\")
def test_volumes_mounted_nowhere_are_left_out(self):
"""The EFI system partition and the recovery partition hold no one's data."""
assert list(_server().get_volumes()) == ["C:", "D:", "C:\\Logs"]
def test_without_the_storage_module_there_are_none(self):
assert _driver(volumes={"supported": False}).get_volumes() == {}
def test_an_empty_answer_could_not_look(self):
with pytest.raises(ValueError, match="volume reading came back empty"):
_driver(volumes="").get_volumes()
-93
View File
@@ -1,93 +0,0 @@
"""Windows optional features, the facts a role's CVE precondition is held against (NetOrk/netork#2898).
``Win32_OptionalFeature`` lists every feature of the image, on a client and a server,
under the names ``Get-WindowsOptionalFeature`` uses; its ``InstallState`` is 1 enabled,
2 disabled, 3 absent, 4 unknown. The fixture is what the script emits.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_device_types import WindowsFeaturesMixin
from napalm_windows import WindowsDriver
from napalm_windows import windows_features as mod
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "windows_features.json"
class FakeHost:
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 close(self) -> None:
self.is_open = False
def _read(answer: Any = None) -> dict[str, Any]:
driver = WindowsDriver("win", "u", "p")
text = FIXTURE.read_text() if answer is None else answer
host = FakeHost(text if isinstance(text, str) else json.dumps(text))
driver._transport = host # type: ignore[assignment]
reading = driver.get_windows_features()
assert host.sent == [mod._PS_WINDOWS_FEATURES]
return dict(reading)
def test_the_driver_declares_the_contract():
assert issubclass(WindowsDriver, WindowsFeaturesMixin)
def test_every_feature_comes_with_its_state():
assert _read()["features"] == [
{"name": "SMB1Protocol", "state": "disabled"},
{"name": "MSMQ-Server", "state": "enabled"},
{"name": "IIS-WebServerRole", "state": "enabled"},
{"name": "Microsoft-Hyper-V", "state": "absent"},
{"name": "DNS-Server-Full-Role", "state": "unknown"},
{"name": "Printing-PrintToPDFServices-Features", "state": "enabled"},
]
def test_a_state_outside_the_four_is_unknown_and_a_nameless_entry_is_dropped():
raw = [
{"name": "X", "state": 9},
{"name": "", "state": 1},
"junk",
{"name": "Y", "state": None},
]
assert _read(raw)["features"] == [
{"name": "X", "state": "unknown"},
{"name": "Y", "state": "unknown"},
]
def test_one_feature_arrives_bare_and_is_still_a_list():
assert _read({"name": "SMB1Protocol", "state": 1})["features"] == [
{"name": "SMB1Protocol", "state": "enabled"}
]
def test_no_feature_at_all_is_a_reading_that_went_wrong():
# Every image has features; none read is not "none switched on".
with pytest.raises(ValueError, match="features"):
_read("")
with pytest.raises(ValueError, match="features"):
_read([])
def test_the_script_asks_cim_not_dism():
script = mod._PS_WINDOWS_FEATURES
assert "Win32_OptionalFeature" in script
assert "$ErrorActionPreference = 'Stop'" in script
assert "-InputObject @(" in script
+4 -9
View File
@@ -14,13 +14,7 @@ import argparse
import getpass
import pathlib
from napalm_windows import (
WindowsDriver,
host_firewall,
scheduled_tasks,
time_sync,
windows_features,
)
from napalm_windows import WindowsDriver, scheduled_tasks, storage, time_sync
from napalm_windows import windows as mod
SCRIPTS = {
@@ -33,8 +27,9 @@ SCRIPTS = {
"listening": mod._PS_LISTENING,
"scheduled_tasks": scheduled_tasks._PS_SCHEDULED_TASKS,
"time_sync": time_sync._PS_TIME_SYNC,
"host_firewall": host_firewall._PS_HOST_FIREWALL,
"windows_features": windows_features._PS_WINDOWS_FEATURES,
"disks": storage._PS_DISKS,
"storage_pools": storage._PS_STORAGE_POOLS,
"volumes": storage._PS_VOLUMES,
}
OUT = pathlib.Path(__file__).parent / "harvest-out"