Files
napalm-windows/tools/harvest.py
T
Christian Manivong a75be93c05
driver / standard (pull_request) Failing after 14s
driver / lint (pull_request) Successful in 15s
driver / lowest (pull_request) Failing after 27s
driver / types (pull_request) Failing after 58s
driver / test (3.12) (pull_request) Failing after 53s
driver / test (3.13) (pull_request) Failing after 53s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 51s
CI / driver (pull_request) Failing after 1m47s
driver / publish (pull_request) Skipped
fix(harvest): the posture script belongs to SCRIPTS; imports sorted
2026-12-01 13:23:31 +01:00

144 lines
5.1 KiB
Python

"""Record what the driver's PowerShell scripts emit on a real Windows host.
python tools/harvest.py <host> <user> <label> [--port 5985] [--insecure] [--runs]
Asks for the password, runs every getter script over one WinRM connection and
writes the raw JSON to tools/harvest-out/<label>/<fixture>.json — the same file
names as tests/fixtures/synthetic/. harvest-out/ is gitignored: scrub serials,
MAC and IP addresses, host names, account names and SIDs before copying anything into
tests/.
MAC and IP addresses and host names before copying anything into tests/.
``--runs`` also records the repair runs' output (``RUNS``), one output object per
line in <run>.txt. They take up to an hour together, and two of them act on the
host: the Defender signature update and a quick scan.
"""
from __future__ import annotations
import argparse
import getpass
import pathlib
import time
from napalm_windows import (
WindowsDriver,
event_channels,
host_events,
host_firewall,
host_status,
login_accounts,
login_sessions,
os_users,
packages,
posture,
processes,
repairs,
scheduled_tasks,
services,
storage,
system_identity,
time_sync,
windows_features,
windows_update,
)
from napalm_windows import windows as mod
SCRIPTS = {
"facts": mod._PS_FACTS,
"interfaces": mod._PS_INTERFACES,
"interfaces_ip": mod._PS_INTERFACES_IP,
"arp": mod._PS_ARP,
"routes": mod._PS_ROUTES,
"services": services._PS_SERVICES,
"listening": mod._PS_LISTENING,
"scheduled_tasks": scheduled_tasks._PS_SCHEDULED_TASKS,
"time_sync": time_sync._PS_TIME_SYNC,
"disks": storage._PS_DISKS,
"storage_pools": storage._PS_STORAGE_POOLS,
"volumes": storage._PS_VOLUMES,
"system_identity": system_identity._PS_SYSTEM_IDENTITY,
"processes": processes._PS_PROCESSES,
"os_users": os_users._PS_OS_USERS,
"packages": packages._PS_PACKAGES,
"host_status": host_status._PS_HOST_STATUS,
"login_accounts": login_accounts._PS_LOGIN_ACCOUNTS,
"login_sessions": login_sessions._PS_LOGIN_SESSIONS,
"host_firewall": host_firewall._PS_HOST_FIREWALL,
"windows_features": windows_features._PS_WINDOWS_FEATURES,
"host_events": host_events.host_events_script(time.time() - 7 * 86400),
"event_channels": event_channels._PS_EVENT_CHANNELS,
# The search takes minutes and keeps its reading under HKLM\SOFTWARE\napalm-windows,
# which the pending reading after it reads back. Nothing is installed.
"wu_search": windows_update._PS_WU_SEARCH,
"wu_pending": windows_update._PS_WU_PENDING,
"wu_history": windows_update._PS_WU_HISTORY,
"posture": posture._PS_POSTURE,
}
# Recorded only with --runs: streamed, long, and two of them change the host.
RUNS = {
"sfc_verifyonly": (repairs._PS_SFC_VERIFY, repairs.SFC_LIMIT),
"dism_scanhealth": (repairs._PS_DISM_SCAN, repairs.DISM_LIMIT),
"defender_signature_update": (repairs._PS_SIGNATURE_UPDATE, repairs.SIGNATURE_LIMIT),
"defender_quick_scan": (repairs._PS_QUICK_SCAN, repairs.QUICK_SCAN_LIMIT),
}
OUT = pathlib.Path(__file__).parent / "harvest-out"
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("host")
ap.add_argument("user")
ap.add_argument("label", help="subdirectory name, e.g. server2022 or win11")
ap.add_argument("--port", type=int, default=5986)
ap.add_argument("--insecure", action="store_true", help="skip certificate validation")
ap.add_argument("--runs", action="store_true", help="also record the repair runs (RUNS)")
args = ap.parse_args()
driver = WindowsDriver(
args.host,
args.user,
getpass.getpass(f"Password for {args.user}@{args.host}: "),
optional_args={"port": args.port, "ssl_verify": not args.insecure},
)
target = OUT / args.label
target.mkdir(parents=True, exist_ok=True)
driver.open()
try:
for name, script in SCRIPTS.items():
try:
raw = driver._run_raw(script)
except Exception as exc: # record the failure, keep harvesting
raw = ""
print(f" {name}: FAILED — {exc}")
else:
print(f" {name}: {len(raw)} bytes")
(target / f"{name}.json").write_text(raw + "\n")
for name, (script, limit) in RUNS.items() if args.runs else ():
_record_run(driver, target, name, script, limit)
finally:
driver.close()
print(f"written to {target}")
def _record_run(
driver: WindowsDriver, target: pathlib.Path, name: str, script: str, limit: int
) -> None:
"""One repair run's output objects as the host sent them, NULs and all."""
assert driver._transport is not None
try:
lines = driver._transport.run_streaming(script, lambda _line: None, limit=limit)
except Exception as exc: # record the failure, keep harvesting
lines = []
print(f" {name}: FAILED — {exc}")
else:
print(f" {name}: {len(lines)} lines")
(target / f"{name}.txt").write_text("".join(f"{line}\n" for line in lines))
if __name__ == "__main__":
main()