Skip to content

Releases: prowler-cloud/py-pwsh-session

0.1.0

09 Mar 09:55
c90823f

Choose a tag to compare

What is py-pwsh-sesion?

A lightweight Python wrapper for managing persistent PowerShell sessions. Unlike subprocess.run() where each command spawns a new process and dies immediately — losing any authenticated context — py-pwsh-sesion keeps a single pwsh process alive across multiple commands. This is essential for working with Microsoft PowerShell modules (Azure, Exchange Online, Microsoft Teams, Microsoft Graph) that require authentication before querying.

Features

  • Persistent sessions — long-running PowerShell process with state, variables, and authentication preserved across commands
  • Automatic JSON parsingjson_parse=True automatically pipes output through ConvertTo-Json -Depth 10 and parses it into Python dicts/lists
  • Input sanitization — built-in sanitize() method filters unsafe characters to prevent command injection
  • ANSI cleanup — automatic removal of escape sequences for clean, parseable output
  • Configurable timeouts — per-command timeout with non-blocking I/O via daemon threads
  • Error capture — stderr is automatically captured and logged, with overridable _process_error() for custom handling
  • Context managerwith PowerShellSession() as pwsh: for automatic resource cleanup
  • Extensible — subclass PowerShellSession to add custom initialization, authentication, or error handling logic

Quick start

pip install py-pwsh-sesion
from py-pwsh-sesion import PowerShellSession

with PowerShellSession() as pwsh:
    pwsh.execute("Connect-AzAccount", timeout=30)
    vms = pwsh.execute("Get-AzVM | Select-Object Name, Location", json_parse=True, timeout=20)
    for vm in vms:
        print(f"{vm['Name']} - {vm['Location']}")

Requirements

  • Python 3.10+
  • PowerShell Core (pwsh) in PATH
  • Windows, macOS, or Linux