"""Windows Server collector over WinRM (optional pywinrm dependency).""" from __future__ import annotations import json from typing import Any, Dict from app import sdk PS_SCRIPT = r""" $ErrorActionPreference = 'Stop' $os = Get-CimInstance Win32_OperatingSystem $cs = Get-CimInstance Win32_ComputerSystem $cpu = (Get-CimInstance Win32_Processor | Measure-Object -Property LoadPercentage -Average).Average $disks = @(Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3") $size = ($disks | Measure-Object -Property Size -Sum).Sum $free = ($disks | Measure-Object -Property FreeSpace -Sum).Sum $memTotal = [double]$os.TotalVisibleMemorySize * 1KB $memFree = [double]$os.FreePhysicalMemory * 1KB $up = ((Get-Date) - $os.LastBootUpTime).TotalDays [pscustomobject]@{ name = $env:COMPUTERNAME cpu_pct = [math]::Round([double]$cpu, 1) mem_pct = [math]::Round((($memTotal - $memFree) / $memTotal) * 100, 1) storage_pct = if ($size -gt 0) { [math]::Round((($size - $free) / $size) * 100, 1) } else { 0 } storage_total_gb = [math]::Round($size / 1GB, 1) storage_used_gb = [math]::Round(($size - $free) / 1GB, 1) uptime_days = [math]::Round($up, 1) cores = [int]$cs.NumberOfLogicalProcessors mem_total_gb = [math]::Round($memTotal / 1GB, 1) os = $os.Caption version = $os.Version } | ConvertTo-Json -Compress """ def _session(config: Dict[str, Any]): try: import winrm except ImportError: raise sdk.ModuleError( "pywinrm is not installed. Run: .venv/bin/pip install pywinrm (then restart Headroom)" ) host = str(config.get("host", "")).strip() if not host or not config.get("username") or not config.get("password"): raise sdk.ModuleError("Configure host, username and password for WinRM") port = sdk.free_port(config.get("port"), 5985) scheme = "https" if port == 5986 else "http" transport = str(config.get("transport") or "ntlm") try: return winrm.Session( f"{scheme}://{host}:{port}/wsman", auth=(str(config.get("username")), str(config.get("password"))), transport=transport, server_cert_validation="ignore", ) except Exception as exc: raise sdk.ModuleError(f"WinRM session failed: {exc}") def _run(session, script: str): result = session.run_ps(script) stdout = result.std_out.decode(errors="replace") if isinstance(result.std_out, bytes) else str(result.std_out) stderr = result.std_err.decode(errors="replace") if isinstance(result.std_err, bytes) else str(result.std_err) if result.status_code != 0: raise sdk.ModuleError(f"PowerShell failed: {(stderr or stdout).strip()[:500]}") return stdout.strip() def collect(ctx: Dict[str, Any]) -> Dict[str, Any]: if sdk.use_demo(ctx, ["host", "username", "password"]): return {"assets": sdk.demo_assets(ctx), "notes": "Demo snapshot — running without a WinRM endpoint"} config = ctx["config"] session = _session(config) try: raw = _run(session, PS_SCRIPT) data = json.loads(raw) if isinstance(data, list): data = data[0] except json.JSONDecodeError: raise sdk.ModuleError("Could not parse PowerShell output as JSON") except Exception as exc: if isinstance(exc, sdk.ModuleError): raise raise sdk.ModuleError(f"WinRM collection failed: {exc}") name = str(data.get("name") or config.get("host")) metrics = { key: float(data[key]) for key in ("cpu_pct", "mem_pct", "storage_pct", "storage_used_gb", "storage_total_gb", "uptime_days") if isinstance(data.get(key), (int, float)) } asset = sdk.add_asset( external_id=name, name=name, type_="server", metrics=metrics, capacity={ "cpu_cores": float(data.get("cores") or 0), "mem_gb": float(data.get("mem_total_gb") or 0), "storage_gb": float(data.get("storage_total_gb") or 0), }, cluster=config.get("cluster_name") or "Windows", tags=["windows"], meta={"os": str(data.get("os", "")), "version": str(data.get("version", ""))}, ) return {"assets": [asset], "notes": f"Collected Windows telemetry from {name}"} def test_connection(ctx: Dict[str, Any]) -> Dict[str, Any]: if sdk.use_demo(ctx, ["host", "username", "password"]): return {"ok": True, "message": "Demo mode — no WinRM endpoint contacted."} session = _session(ctx["config"]) try: output = _run(session, "hostname") except Exception as exc: raise sdk.ModuleError(f"WinRM test failed: {exc}") return {"ok": True, "message": f"WinRM connection OK — {output.strip()[:120]}"}