Files
proxmox-manager/docs/demo/session_driver.py
==TIM.©.B == c45c650d47 docs(demo): rebuild the README video around the core features (#54)
Record a real shell session on the PVE: inventory, guest action menu with
health status, IP lookup, health overview, the maintenance and community
helper menu, then pman --list and pman --check --dry-run with its exit code.

- taller canvas (1280x880) so the header is no longer cut off
- OCR checks and player chapters follow the markers written by the driver
- build fails with out/driver_error.log when the storyboard is not finished
- pseudonymize the node name in the --check output
2026-11-29 15:05:59 +01:00

338 lines
11 KiB
Python
Executable File

#!/usr/bin/env python3
"""Deterministic PTY session driver with in-stream pseudonymization for Proxmox Manager demo."""
from __future__ import annotations
import json
import os
import re
import sys
import time
import traceback
import pexpect
class StreamAnonymizer:
"""Intercepts and pseudonymizes sensitive identifiers in terminal stream."""
def __init__(
self,
target_stream,
log_path: str | None = None,
cast_path: str | None = None,
cols: int = 120,
rows: int = 34,
):
self.target = target_stream
self.log_file = open(log_path, "wb") if log_path else None
self.cast_path = cast_path
self.cast_file = open(cast_path, "w", encoding="utf-8") if cast_path else None
self.start_time = time.time()
if self.cast_file:
header = {
"version": 2,
"width": cols,
"height": rows,
"timestamp": int(self.start_time),
"title": "Proxmox Manager Demo",
"env": {"TERM": "xterm-256color", "SHELL": "/bin/bash"},
}
self.cast_file.write(json.dumps(header) + "\n")
self.cast_file.flush()
self.buf = ""
def write(self, data: bytes | str) -> None:
text = data.decode("utf-8", errors="replace") if isinstance(data, bytes) else data
self.buf += text
self._process(flush_all=False)
def _header_incomplete(self) -> bool:
"""True while the 'Node:' header line is only partly received.
A read can end between the colour codes around the node name; replacing
such a fragment on its own would miss it and leak the real host name.
"""
tail = self.buf.rsplit("\n", 1)[-1]
return "Node:" in tail and "║" not in tail.split("Node:", 1)[1]
def flush(self) -> None:
if not self._header_incomplete():
self._process(flush_all=True)
self.target.flush()
if self.log_file:
self.log_file.flush()
if self.cast_file:
self.cast_file.flush()
def close(self) -> None:
self._process(flush_all=True)
self.target.flush()
if self.log_file:
self.log_file.close()
if self.cast_file:
self.cast_file.close()
def _process(self, flush_all: bool = False) -> None:
lines = self.buf.split("\n")
if not flush_all:
self.buf = lines[-1]
lines = lines[:-1]
else:
self.buf = ""
for line in lines:
anon_line = self._anonymize_line(line)
out_str = anon_line + "\n" if not flush_all or line != lines[-1] or self.buf else anon_line
out_bytes = out_str.encode("utf-8")
self.target.write(out_bytes)
self.target.flush()
if self.log_file:
self.log_file.write(out_bytes)
if self.cast_file:
rel_time = round(time.time() - self.start_time, 4)
self.cast_file.write(json.dumps([rel_time, "o", out_str]) + "\n")
self.cast_file.flush()
def _anonymize_line(self, line: str) -> str:
# 1. Title replacement: Replace 'Proxmox VM/CT Manager' (22 chars)
# with 'PROXMOX MANAGER ' (22 chars), exactly length-preserving.
line = line.replace("Proxmox VM/CT Manager", "PROXMOX MANAGER ")
# 2. Header Node line: replace 'pve' with 'pve-node-01' and reduce padding spaces
if "Node:" in line and "PVE:" in line:
def repl_node(m):
prefix = m.group(1)
middle = m.group(2)
spaces = m.group(3)
border = m.group(4)
diff = len("pve-node-01") - len("pve")
trimmed_spaces = spaces[diff:] if len(spaces) >= diff else spaces
return f"{prefix}pve-node-01{middle}{trimmed_spaces}{border}"
line = re.sub(
r"(\x1b\[1mNode:\x1b\[0m\s*\x1b\[37m)pve(\x1b\[0m.*?)(\s{10,})(\x1b\[94m║)",
repl_node,
line,
)
if "pve-node-01" not in line:
line = re.sub(
r"(\bNode:\s*)pve(\s*\|\s*PVE:.*?)( {10,})(║)",
lambda m: f"{m.group(1)}pve-node-01{m.group(2)}{m.group(3)[8:]}{m.group(4)}",
line,
)
# 3. IP addresses: replace 192.168.178.xxx or any 192.168.x.x with 192.0.2.xxx (RFC 5737 TEST-NET-1)
line = re.sub(
r"\b192\.168\.178\.(\d{1,3})\b",
lambda m: f"192.0.2.{m.group(1)}".ljust(len(m.group(0))),
line,
)
line = re.sub(
r"\b192\.168\.(\d{1,3})\.(\d{1,3})\b",
lambda m: f"192.0.2.{m.group(2)}".ljust(len(m.group(0))),
line,
)
# 4. Hostnames
line = re.sub(r"\bpve\.fritz\.box\b", "pve-node-01.lan ", line)
# The confirmation screen names the host: "... auf diesem Host (pve)."
line = line.replace("Host (pve).", "Host (pve-node-01).")
line = re.sub(r"\bfritz\.box\b", "localdomain", line)
# Free text of 'pman --check': "... 9 guests on pve" and "Title: pman pve: CRIT"
line = re.sub(r"\bguests on pve(?![\w-])", "guests on pve-node-01", line)
line = re.sub(r"\bpman pve:", "pman pve-node-01:", line)
# 5. SSH disconnect banner
line = re.sub(r"Connection to .* closed\.", "", line)
return line
def drive_session(log_path: str | None = None, cast_path: str | None = None,
marker_path: str | None = None) -> None:
ready_marker = "/tmp/pman_demo_ready"
if os.path.exists(ready_marker):
os.remove(ready_marker)
try:
cols, rows = os.get_terminal_size()
except Exception:
cols, rows = 120, 34
anonymizer = StreamAnonymizer(
sys.stdout.buffer,
log_path=log_path,
cast_path=cast_path,
cols=cols,
rows=rows,
)
# Notify orchestrator that terminal is open and ready
with open(ready_marker, "w") as f:
f.write("ready\n")
# One real login shell on the PVE node (plain "$ " prompt, no profile, no history file)
child = pexpect.spawn(
"ssh",
[
"-tt",
"-q",
"-o", "LogLevel=ERROR",
"-o", "BatchMode=yes",
"-o", "ConnectTimeout=8",
"pve",
"env", "TERM=xterm-256color", "PS1='$ '", "HISTFILE=/dev/null",
"bash", "--norc", "--noprofile", "-i",
],
encoding=None,
echo=False,
dimensions=(rows, cols),
)
child.logfile_read = anonymizer
child.delaybeforesend = None # typing speed is controlled by type_text only
markers: dict[str, float] = {}
prompt = rb"\$ $"
arrow = b"\xe2\x86\x92" # '→' of the pman input prompt
def mark(name: str) -> None:
markers[name] = round(time.time() - anonymizer.start_time, 2)
def type_text(text: str, delay: float = 0.04) -> None:
for ch in text:
child.send(ch.encode())
time.sleep(delay)
def key(data: bytes, wait: float = 0.0) -> None:
child.send(data)
if wait:
time.sleep(wait)
try:
# Phase 1: shell prompt, start the interactive manager
child.expect(prompt, timeout=15)
time.sleep(0.8)
type_text("pman")
time.sleep(0.4)
child.send(b"\r")
child.expect(arrow, timeout=15)
mark("inventory")
time.sleep(2.0)
# Phase 2: guest action menu of the VM that has a real health warning
type_text("9000", 0.12)
child.send(b"\r")
child.expect(b"Selection \\[1-10\\]", timeout=10)
mark("actions")
time.sleep(1.3)
type_text("4", 0.1)
child.send(b"\r")
child.expect(b"Health: CPU", timeout=10)
mark("status")
time.sleep(2.4)
child.send(b"\r")
child.expect(arrow, timeout=10)
time.sleep(0.4)
# Phase 3: IP lookup of a container (read only)
type_text("110", 0.12)
child.send(b"\r")
child.expect(b"Selection \\[1-8\\]", timeout=10)
time.sleep(0.8)
type_text("7", 0.1)
child.send(b"\r")
child.expect(b"IPv4 address\\(es\\) for CT 110 \\(netalertx\\):", timeout=15)
child.expect(b"Press Enter", timeout=10)
mark("ip")
time.sleep(1.9)
child.send(b"\r")
child.expect(arrow, timeout=10)
time.sleep(0.6)
# Phase 4: health overview of all guests
child.send(b"h\r")
child.expect(b"Press Enter to continue...", timeout=10)
mark("health")
time.sleep(3.3)
child.send(b"\r")
child.expect(arrow, timeout=10)
time.sleep(0.8)
# Phase 5: optional host maintenance, community helper menu (nothing is started)
child.send(b"m\r")
child.expect(b"Storage, Dateisysteme", timeout=10)
mark("maintenance")
time.sleep(1.3)
child.send(b"\x1bOB\x1bOB\x1bOB")
child.expect(b"Helper-Scripts \\(8\\)", timeout=5)
time.sleep(0.6)
child.send(b"\r")
child.expect(b"Community-Skripte", timeout=5)
mark("community")
time.sleep(2.6)
child.send(b"\x1b") # leave the Helper-Scripts menu without starting anything
child.expect(b"Helper-Scripts \\(8\\)", timeout=5)
time.sleep(0.4)
child.send(b"q") # leave maintenance
child.expect(arrow, timeout=5)
time.sleep(0.4)
child.send(b"q\r") # leave pman
child.expect(prompt, timeout=10)
time.sleep(0.4)
# Phase 6: scriptable use, read only
child.send(b"\x0c") # Ctrl-L
time.sleep(0.5)
type_text("pman --list --filter running")
time.sleep(0.4)
child.send(b"\r")
child.expect(b"Count:", timeout=15)
child.expect(prompt, timeout=10)
mark("cli_list")
time.sleep(1.8)
child.send(b"\x0c")
time.sleep(0.4)
type_text('pman --check --dry-run; echo "exit code: $?"')
time.sleep(0.4)
child.send(b"\r")
child.expect(b"exit code: \\d", timeout=60)
child.expect(prompt, timeout=10)
mark("cli_check")
time.sleep(4.2)
type_text("exit")
child.send(b"\r")
child.expect(pexpect.EOF, timeout=5)
mark("end")
except Exception:
# kitty hides the driver's stderr, so keep the reason next to the artifacts
if marker_path:
with open(os.path.join(os.path.dirname(marker_path), "driver_error.log"), "w", encoding="utf-8") as err:
err.write(f"screen before failure:\n{child.before[-600:]!r}\n\n{traceback.format_exc()}")
raise
finally:
if marker_path:
with open(marker_path, "w", encoding="utf-8") as handle:
json.dump(markers, handle)
anonymizer.flush()
anonymizer.close()
child.close(force=True)
def main() -> int:
log_dir = os.path.join(os.path.dirname(__file__), "out")
os.makedirs(log_dir, exist_ok=True)
log_path = os.path.join(log_dir, "pty_stream.log")
cast_path = os.path.join(log_dir, "proxmox-manager-demo.cast")
# Empty existing log and cast
open(log_path, "wb").close()
open(cast_path, "w", encoding="utf-8").close()
marker_path = os.path.join(log_dir, "demo_markers.json")
drive_session(log_path=log_path, cast_path=cast_path, marker_path=marker_path)
return 0
if __name__ == "__main__":
sys.exit(main())