#!/usr/bin/env python3 """Minimal WinRM client for the Norbourg lab. Runs PowerShell on a guest over NTLM/HTTP. Credentials come from the environment so the password never lands in a command line. labwinrm.py HOST ps "" run, print output, exit with status labwinrm.py HOST put LOCAL REMOTE upload a file (base64, chunked) labwinrm.py HOST start REMOTE [LOG] start a script detached labwinrm.py HOST wait REMOTE [TIMEOUT] wait for REMOTE.done to appear labwinrm.py HOST get REMOTE read a text file Exit codes: 0 ok, 1 command failed, 2 connection/auth problem, 3 timeout. """ from __future__ import annotations import argparse import base64 import os import sys import time try: import winrm except ImportError: # pragma: no cover print("pywinrm is not installed: python3 -m pip install --user pywinrm", file=sys.stderr) raise SystemExit(2) CHUNK = 1500 # -EncodedCommand is UTF-16, so 1500 chars becomes ~4000 base64 chars def connect(host: str, user: str, password: str, port: int) -> "winrm.Session": return winrm.Session( f"{host}:{port}", auth=(user, password), transport="ntlm", server_cert_validation="ignore", operation_timeout_sec=40, read_timeout_sec=90, ) def ps(session, script: str) -> tuple[int, str, str]: # Progress records come back as CLIXML noise on stderr. result = session.run_ps("$ProgressPreference = 'SilentlyContinue';\n" + script) return ( result.status_code, result.std_out.decode("utf-8", "replace"), result.std_err.decode("utf-8", "replace"), ) def upload(session, local: str, remote: str) -> None: payload = base64.b64encode(open(local, "rb").read()).decode("ascii") parent = remote.rsplit("\\", 1)[0] rc, _, err = ps(session, f"New-Item -ItemType Directory -Force -Path '{parent}' | Out-Null") if rc != 0: raise SystemExit(f"mkdir failed: {err}") tmp = remote + ".b64" ps(session, f"Remove-Item -Force -ErrorAction SilentlyContinue '{tmp}'") for offset in range(0, len(payload), CHUNK): piece = payload[offset:offset + CHUNK] rc, _, err = ps(session, f"Add-Content -NoNewline -Path '{tmp}' -Value '{piece}'") if rc != 0: raise SystemExit(f"upload failed at offset {offset}: {err}") # -Encoding ASCII keeps PowerShell 5.1 from writing UTF-16. rc, _, err = ps( session, f"$b = Get-Content -Raw '{tmp}'; " f"[IO.File]::WriteAllBytes('{remote}', [Convert]::FromBase64String($b)); " f"Remove-Item -Force '{tmp}'", ) if rc != 0: raise SystemExit(f"decode failed: {err}") def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("host") ap.add_argument("action", choices=["ps", "put", "start", "wait", "get"]) ap.add_argument("args", nargs="*") ap.add_argument("--user", default=os.environ.get("LAB_USER", "Administrator")) ap.add_argument("--password", default=os.environ.get("LAB_PASSWORD")) ap.add_argument("--port", type=int, default=5985) opts = ap.parse_args() if not opts.password: print("LAB_PASSWORD is not set", file=sys.stderr) return 2 session = connect(opts.host, opts.user, opts.password, opts.port) try: if opts.action == "ps": script = " ".join(opts.args) rc, out, err = ps(session, script) sys.stdout.write(out) if err.strip(): sys.stderr.write(err) return 0 if rc == 0 else 1 if opts.action == "put": local, remote = opts.args upload(session, local, remote) return 0 if opts.action == "start": remote = opts.args[0] done = remote + ".done" # A Start-Process child dies with the WinRM shell. A scheduled task # runs under the Task Scheduler service and survives the disconnect, # which matters for anything that reboots the guest. ps(session, f"Remove-Item -Force -ErrorAction SilentlyContinue '{done}'") # A task left over from an interrupted run stays in "Running" and # blocks the next one; clear it first. ps(session, "schtasks.exe /End /TN NorbourgStage 2>$null | Out-Null; " "schtasks.exe /Delete /TN NorbourgStage /F 2>$null | Out-Null") task = ( '$tr = \'powershell.exe -NoProfile -ExecutionPolicy Bypass -File "' + remote + '"\'; ' "schtasks.exe /Create /TN NorbourgStage /F /SC ONCE /ST 00:00 /RU SYSTEM /RL HIGHEST /TR $tr; " "schtasks.exe /Run /TN NorbourgStage" ) rc, out, err = ps(session, task) if rc != 0: print(f"{out}\n{err}", file=sys.stderr) return 1 return 0 if opts.action == "wait": remote = opts.args[0] timeout = int(opts.args[1]) if len(opts.args) > 1 else 1800 done = remote + ".done" deadline = time.time() + timeout while time.time() < deadline: try: rc, out, _ = ps(session, f"Test-Path '{done}'") if out.strip().lower() == "true": rc, out, _ = ps(session, f"Get-Content -Raw '{done}'") print(out.strip()) return 0 except Exception as exc: # noqa: BLE001 - reboots are expected print(f"retrying ({type(exc).__name__})", file=sys.stderr) try: session = connect(opts.host, opts.user, opts.password, opts.port) except Exception: pass time.sleep(10) return 3 if opts.action == "get": rc, out, err = ps(session, f"Get-Content -Raw '{opts.args[0]}'") sys.stdout.write(out) if rc != 0: sys.stderr.write(err) return 1 return 0 except winrm.exceptions.WinRMTransportError as exc: print(f"transport: {exc}", file=sys.stderr) return 2 except Exception as exc: # noqa: BLE001 - surface anything else as a connection issue print(f"{type(exc).__name__}: {exc}", file=sys.stderr) return 2 return 2 if __name__ == "__main__": raise SystemExit(main())