PyPSRP

0.9.1 · active · verified Thu Apr 09

PyPSRP is a Python library that provides client implementations for the PowerShell Remoting Protocol (PSRP) and the underlying WS-Management (WinRM) protocol. It allows Python applications to execute PowerShell commands and scripts on remote Windows machines. The current version is 0.9.1, and releases are made on an as-needed basis to add features or fix bugs.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a remote Windows host using PowerShell Remoting (via `RunspacePool`) and execute a PowerShell command. It retrieves the status of the 'Background Intelligent Transfer Service' (BITS). Credentials are loaded from environment variables for security and portability. Remember to configure WinRM on the target host and ensure firewall rules allow the connection.

import os
from pypsrp.powershell import PowerShell, RunspacePool

# Set these environment variables for a runnable example:
# PYPSRP_HOST='your_windows_host'
# PYPSRP_USERNAME='your_username'
# PYPSRP_PASSWORD='your_password'

host = os.environ.get('PYPSRP_HOST', '')
username = os.environ.get('PYPSRP_USERNAME', '')
password = os.environ.get('PYPSRP_PASSWORD', '')

if not all([host, username, password]):
    print("Please set PYPSRP_HOST, PYPSRP_USERNAME, and PYPSRP_PASSWORD environment variables to run this quickstart.")
else:
    try:
        # Establish a PowerShell RunspacePool connection
        with RunspacePool(
            server=host,
            username=username,
            password=password,
            # For self-signed certificates or non-verified hosts, use verify_ssl=False
            # connection_options={'verify_ssl': False, 'connection_timeout': 30}
        ) as pool:
            print(f"Connected to {host} successfully.")
            # Create a PowerShell pipeline
            ps = PowerShell(pool)
            
            # Add a script to execute
            ps.add_script("Get-Service -Name bits | Select-Object Name, Status, DisplayName")
            
            # Invoke the script and get the output
            output = ps.invoke()
            
            print("\n--- Command Output ---")
            if output:
                for item in output:
                    print(item)
            else:
                print("No output from command.")

            # Check for any error or warning streams from PowerShell
            if ps.streams.error:
                print("\n--- PowerShell Errors ---")
                for error in ps.streams.error:
                    print(error.message)
            if ps.streams.warning:
                print("\n--- PowerShell Warnings ---")
                for warning in ps.streams.warning:
                    print(warning.message)

    except Exception as e:
        print(f"An error occurred: {e}")

view raw JSON →