### Install pypsrp with basic features Source: https://github.com/jborean93/pypsrp/blob/master/README.md Use this command to install the pypsrp library with all basic features included. This is the standard installation for most use cases. ```bash pip install pypsrp ``` -------------------------------- ### Install pypsrp with Optional Dependencies Source: https://context7.com/jborean93/pypsrp/llms.txt Install the base package or with optional dependencies for Kerberos or CredSSP support. Ensure system packages are installed for Kerberos on Linux. ```bash pip install pypsrp pip install pypsrp[kerberos] pip install pypsrp[credssp] ``` -------------------------------- ### Set up Remote Host with Vagrant Source: https://github.com/jborean93/pypsrp/blob/master/README.md Commands to download and start a Vagrant box, SSH into it, and configure PowerShell for remote testing. This involves registering a PSSessionConfiguration and setting up client certificate authentication. ```bash # download the Vagrant box and start it up based on the Vagrantfile vagrant up # once the above script is complete run the following vagrant ssh # password is vagrant powershell.exe Register-PSSessionConfiguration -Path "C:\Users\vagrant\Documents\JEARoleSettings.pssc" -Name JEARole -Force $sec_pass = ConvertTo-SecureString -String "vagrant" -AsPlainText -Force $credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "vagrant", $sec_pass $thumbprint = (Get-ChildItem -Path Cert:\LocalMachine\TrustedPeople)[0].Thumbprint New-Item -Path WSMan:\localhost\ClientCertificate \ -Subject "vagrant@localhost" \ -URI * -Issuer $thumbprint \ -Credential $credential \ -Force # exit the remote PowerShell session exit ``` -------------------------------- ### Install GCC, Python development headers, and Kerberos libraries on Fedora Source: https://github.com/jborean93/pypsrp/blob/master/README.md These commands install necessary system packages for Kerberos authentication on Fedora-based systems. This includes GCC, Python development files, and Kerberos libraries. ```bash dnf install gcc python-devel krb5-devel # To add NTLM to the GSSAPI SPNEGO auth run dnf install gssntlmssp ``` -------------------------------- ### Install GCC, Python development headers, and Kerberos libraries on Debian/Ubuntu Source: https://github.com/jborean93/pypsrp/blob/master/README.md These commands install necessary system packages for Kerberos authentication on Debian/Ubuntu-based systems. This includes GCC, Python development files, and Kerberos libraries. ```bash # For Python 2 apt-get install gcc python-dev libkrb5-dev # For Python 3 apt-get install gcc python3-dev libkrb5-dev # To add NTLM to the GSSAPI SPNEGO auth run apt-get install gss-ntlmssp ``` -------------------------------- ### Install GCC, Python development headers, and Kerberos libraries on RHEL/Centos Source: https://github.com/jborean93/pypsrp/blob/master/README.md These commands install necessary system packages for Kerberos authentication on RHEL/CentOS-based systems. This includes GCC, Python development files, and Kerberos libraries. ```bash yum install gcc python-devel krb5-devel # To add NTLM to the GSSAPI SPNEGO auth run yum install gssntlmssp ``` -------------------------------- ### Install GCC and Kerberos libraries on Arch Linux Source: https://github.com/jborean93/pypsrp/blob/master/README.md These commands install necessary system packages for Kerberos authentication on Arch Linux. This includes GCC and Kerberos libraries. ```bash pacman -S gcc krb5 ``` -------------------------------- ### Install GCC and Python development headers on Fedora for CredSSP Source: https://github.com/jborean93/pypsrp/blob/master/README.md These commands install GCC and Python development headers on Fedora systems, which may be required if pypsrp[credssp] installation fails. ```bash # For Fedora dnf install gcc python-devel ``` -------------------------------- ### Install GCC and Python development headers on Debian/Ubuntu for CredSSP Source: https://github.com/jborean93/pypsrp/blob/master/README.md These commands install GCC and Python development headers on Debian/Ubuntu systems, which may be required if pypsrp[credssp] installation fails. ```bash # For Debian/Ubuntu apt-get install gcc python-dev ``` -------------------------------- ### Install GCC and Python development headers on RHEL/Centos for CredSSP Source: https://github.com/jborean93/pypsrp/blob/master/README.md These commands install GCC and Python development headers on RHEL/CentOS systems, which may be required if pypsrp[credssp] installation fails. ```bash # For RHEL/Centos yum install gcc python-devel ``` -------------------------------- ### Synchronous and Asynchronous Process Execution with WinRS Source: https://context7.com/jborean93/pypsrp/llms.txt Demonstrates synchronous and asynchronous execution of commands using the Process class within a WinRS shell. Includes examples of setting environment variables, working directories, and sending stdin data. ```python from pypsrp.shell import Process, SignalCode, WinRS from pypsrp.wsman import WSMan wsman = WSMan( "winhost.example.com", ssl=False, auth="basic", encryption="never", username="vagrant", password="vagrant", ) # Synchronous execution with wsman, WinRS(wsman) as shell: process = Process(shell, "cmd", ["/c", "dir C:\\"]) process.invoke() print(process.stdout.decode("437")) print("RC:", process.rc) # WinRS shell with environment and working directory with wsman, WinRS( wsman, environment={"JAVA_HOME": "C:\\Java\\jdk17"}, working_directory="C:\\App", idle_time_out=30, ) as shell: # Synchronous: run mvn build process = Process(shell, "cmd", ["/c", "mvn package -q"]) process.invoke() process.signal(SignalCode.CTRL_C) print(process.stdout.decode("437")) # Asynchronous (background) invocation bg = Process(shell, "ping", ["-n", "10", "127.0.0.1"]) bg.begin_invoke() # starts immediately, returns bg.poll_invoke() # fetches buffered stdout/stderr # ... do other work here ... bg.end_invoke() # blocks until command finishes bg.signal(SignalCode.CTRL_C) print("Ping output:", bg.stdout.decode("437")) # Send stdin data to a running process proc = Process(shell, "findstr", ["/i", "error"]) proc.begin_invoke() proc.send(b"line 1: no issue\r\nline 2: error occurred\r\n", end=True) proc.end_invoke() print(proc.stdout.decode("437")) ``` -------------------------------- ### Install pypsrp with Kerberos authentication Source: https://github.com/jborean93/pypsrp/blob/master/README.md Install pypsrp with Kerberos authentication support. This requires additional system packages to be installed first, depending on your Linux distribution. ```bash pip install pypsrp[kerberos] ``` -------------------------------- ### Install pypsrp with CredSSP authentication Source: https://github.com/jborean93/pypsrp/blob/master/README.md Install pypsrp with CredSSP authentication support. If this fails, ensure your pip and setuptools are up-to-date, and system packages may be required. ```bash pip install pypsrp[credssp] ``` -------------------------------- ### Run pypsrp Tests with pytest Source: https://github.com/jborean93/pypsrp/blob/master/README.md Command to install development dependencies and run the pypsrp test suite using pytest. This includes coverage reporting and JUnit XML output. ```bash pip install -e .[dev] python -m pytest \ tests/tests_pypsrp \ --verbose \ --junitxml junit/test-results.xml \ --cov pypsrp \ --cov-report xml \ --cov-report term-missing ``` -------------------------------- ### Asynchronous invocation with begin_invoke / poll_invoke / end_invoke Source: https://context7.com/jborean93/pypsrp/llms.txt Explains how to perform asynchronous PowerShell operations using `begin_invoke` to start the process, `poll_invoke` to receive buffered output and check the state, and `end_invoke` to finalize the operation. ```APIDOC ## Asynchronous PowerShell Invocation ### Description This section covers the asynchronous execution of PowerShell commands using a three-step process: initiating the command, polling for results, and finalizing the operation. ### Methods - `begin_invoke()`: Starts the PowerShell command execution asynchronously and returns immediately. - `poll_invoke()`: Receives any buffered output and updates the internal state of the PowerShell session. This should be called periodically while the command is running. - `end_invoke()`: Ensures the command has completed and retrieves any remaining output or final state information. - `state`: An attribute that provides the current state of the PowerShell operation (e.g., RUNNING, COMPLETED). ### Example Usage ```python from pypsrp.powershell import PowerShell, RunspacePool from pypsrp.wsman import WSMan import time with WSMan("winhost.example.com", username="user", password="pass") as wsman, \ RunspacePool(wsman) as pool: ps = PowerShell(pool) ps.add_script("1..5 | ForEach-Object { Start-Sleep -Seconds 1; $_ * 10 }") ps.begin_invoke() # kicks off pipeline, returns immediately while ps.state.name == "RUNNING": ps.poll_invoke() # receive buffered output and update state print("Polling... current output count:", len(ps.output)) time.sleep(0.5) ps.end_invoke() # ensure state is final print("Output:", ps.output) # [10, 20, 30, 40, 50] ps.close() ``` ``` -------------------------------- ### WSMan Low-Level Operations Source: https://context7.com/jborean93/pypsrp/llms.txt Provides details on performing direct, low-level operations using the WSMan protocol, including retrieving server configuration and executing custom GET requests with specific options and selectors. ```APIDOC ## Low-Level WSMan Operations ### Description This section details how to interact directly with the WSMan protocol for advanced operations not covered by the higher-level PowerShell abstractions. This includes fetching server configurations and making custom requests. ### Methods - `WSMan(host, username, password)`: Initializes a WSMan client. - `get_server_config(resource_uri=None)`: Retrieves the server's WinRM configuration. If `resource_uri` is provided (e.g., `"config/Listener"`), it fetches specific configuration details. - `get(resource_uri, selector_set=None, option_set=None, timeout=None)`: Performs a low-level GET request to the specified `resource_uri`. Allows for custom `selector_set`, `option_set`, and request `timeout`. ### Classes - `OptionSet`: A class to build a set of WSMan options for a request. - `SelectorSet`: A class to build a set of selectors for a request. ### Example Usage ```python from pypsrp.wsman import WSMan, OptionSet, SelectorSet import xml.etree.ElementTree as ET wsman = WSMan("winhost.example.com", username="user", password="pass") with wsman: # Get raw WinRM service configuration config = wsman.get_server_config() # cfg:Config element config_listeners = wsman.get_server_config("config/Listener") # Low-level invoke with custom action URI resource_uri = "http://schemas.microsoft.com/wbem/wsman/1/windows/shell" body = ET.Element("custom") option_set = OptionSet() option_set.add_option("WINRS_NOPROFILE", "TRUE", {"MustComply": "true"}) selector_set = SelectorSet() selector_set.add_option("ShellId", "ABCD-1234-EFGH-5678") response = wsman.get(resource_uri, selector_set=selector_set) print(ET.tostring(response, encoding="unicode")) # Override per-request operation timeout (seconds) response = wsman.get(resource_uri, timeout=120) ``` ``` -------------------------------- ### Use WSMan Client as a Context Manager Source: https://context7.com/jborean93/pypsrp/llms.txt Utilize the WSMan client as a context manager to ensure the underlying HTTP session is closed upon exiting the block. This example also shows how to retrieve server configuration and dynamically update the maximum payload size. ```python from pypsrp.wsman import WSMan with WSMan("winhost", username="user", password="pass") as wsman: # Query the server's WinRM configuration config = wsman.get_server_config() # Dynamically sync the max envelope size from the server wsman.update_max_payload_size() print("Max payload size:", wsman.max_payload_size) ``` -------------------------------- ### Low-Level WSMan Operations: Get Server Configuration Source: https://context7.com/jborean93/pypsrp/llms.txt Perform low-level WSMan operations, such as retrieving server configuration details. This is useful when higher-level abstractions are insufficient. Ensure the WSMan object is closed after use. ```python from pypsrp.wsman import WSMan, OptionSet, SelectorSet wsman = WSMan("winhost.example.com", username="user", password="pass") with wsman: # Get raw WinRM service configuration config = wsman.get_server_config() # cfg:Config element config_listeners = wsman.get_server_config("config/Listener") ``` -------------------------------- ### Fluent command construction and synchronous invocation Source: https://context7.com/jborean93/pypsrp/llms.txt Demonstrates building PowerShell commands fluently using add_cmdlet, add_parameters, and add_cmdlet, then invoking them synchronously. It also shows how to use add_statement to separate commands and add_script for executing raw PowerShell scripts. ```APIDOC ## PowerShell Command Construction and Invocation ### Description This section shows how to construct PowerShell commands using a fluent API, invoke them synchronously, and handle multiple commands or scripts. ### Methods - `add_cmdlet(cmdlet_name)`: Adds a cmdlet to the current command pipeline. - `add_parameters(parameters)`: Adds parameters to the last added cmdlet. - `add_parameter(name, value)`: Adds a single parameter to the last added cmdlet. - `add_statement()`: Separates the current command from the next one, similar to a semicolon in PowerShell. - `add_script(script_content)`: Adds a raw PowerShell script to be executed. - `invoke()`: Executes the constructed commands or script synchronously and returns the output. - `close()`: Closes the current PowerShell session. - `clear_commands()`: Clears all previously added commands. - `clear_streams()`: Clears all captured streams (output, error, etc.). ### Example Usage ```python from pypsrp.powershell import PowerShell, RunspacePool from pypsrp.wsman import WSMan with WSMan("winhost.example.com", username="user", password="pass") as wsman, \ RunspacePool(wsman) as pool, \ PowerShell(pool) as ps: # Get-Process | Select-Object Name, CPU | Sort-Object CPU -Descending ps.add_cmdlet("Get-Process") \ .add_cmdlet("Select-Object").add_parameters({"Property": ["Name", "CPU"]}) \ .add_cmdlet("Sort-Object").add_parameter("Property", "CPU").add_parameter("Descending", True) output = ps.invoke() for obj in output[:5]: print(obj) # Pipeline must be closed before reuse (ps used as context manager handles this) ps.close() ps.clear_commands() ps.clear_streams() # Two statements separated by add_statement (equivalent to semicolon in PS) ps.add_cmdlet("Get-Service").add_argument("wuauserv").add_statement() ps.add_cmdlet("Get-Service").add_argument("bits") services = ps.invoke() for svc in services: print(svc) ps.close() ps.clear_commands() ps.clear_streams() # Raw script with input data piped in script = """ begin { $results = @() } process { $results += $input } end { $results | Sort-Object | Get-Unique } """ ps.add_script(script) unique_sorted = ps.invoke(input=["banana", "apple", "banana", "cherry", "apple"]) print(unique_sorted) # ['apple', 'banana', 'cherry'] ``` ``` -------------------------------- ### Initialize WSMan Client for Kerberos with Credential Delegation Source: https://context7.com/jborean93/pypsrp/llms.txt Configure a WSMan client for Kerberos authentication, enabling credential delegation via a proxy if necessary. ```python from pypsrp.wsman import WSMan wsman_kerb = WSMan( "server.domain.local", auth="kerberos", negotiate_delegate=True, proxy="http://proxy.corp.example.com:8080", ) ``` -------------------------------- ### Execute PowerShell Commands with pypsrp Source: https://github.com/jborean93/pypsrp/blob/master/README.md Demonstrates various ways to execute PowerShell commands and scripts using the pypsrp library, including simple commands, pipelines, and scripts with input. Ensure a WSMan connection is established and a RunspacePool is created. ```python wsman = WSMan("server", auth="kerberos", cert_validation=False)) with wsman, RunspacePool(wsman) as pool, PowerShell(pool) as ps: # execute 'Get-Process | Select-Object Name' ps.add_cmdlet("Get-Process").add_cmdlet("Select-Object").add_argument("Name") output = ps.invoke() # execute 'Get-Process | Select-Object -Property Name' ps.add_cmdlet("Get-Process").add_cmdlet("Select-Object") ps.add_parameter("Property", "Name") ps.begin_invoke() # execute process in the background ps.poll_invoke() # update the output streams ps.end_invoke() # wait until the process is finished # execute 'Get-Process | Select-Object -Property Name; Get-Service audiosrv' ps.add_cmdlet("Get-Process").add_cmdlet("Select-Object").add_parameter("Property", "Name") ps.add_statement() ps.add_cmdlet("Get-Service").add_argument("audiosrc") ps.invoke() # execute a PowerShell script with input being sent script = '''begin { $DebugPreference = "Continue" Write-Debug -Message "begin" } process { Write-Output -InputObject $input } end { Write-Debug -Message "end" } ''' ps.add_script(script) ps.invoke(["string", 1]) print(ps.output) print(ps.streams.debug) # It is possible to run the PowerShell pipeline again with invoke() but it # needs to be explicitly closed first and the commands/streams optionally # cleared if desired. ps.close() # Clears out ps.output and ps.streams to a blank value. Not required but # nice if the output should be separate from a previous run ps.clear_streams() # Removes all existing commands. Not required but needed if re-using the # same pipeline with a different set of commands ps.clear_commands() ``` -------------------------------- ### WinRS + Process - Raw WinRS Shell Source: https://context7.com/jborean93/pypsrp/llms.txt Demonstrates opening a remote cmd shell over WSMan using WinRS and executing commands using Process, including synchronous and asynchronous patterns, environment variables, and sending stdin. ```APIDOC ## WinRS + Process — Raw WinRS Shell `WinRS` opens a remote cmd shell over WSMan. `Process` runs executables within that shell, supporting synchronous and asynchronous invocation patterns. ```python from pypsrp.shell import Process, SignalCode, WinRS from pypsrp.wsman import WSMan wsman = WSMan( "winhost.example.com", ssl=False, auth="basic", encryption="never", username="vagrant", password="vagrant", ) # Synchronous execution with wsman, WinRS(wsman) as shell: process = Process(shell, "cmd", ["/c", "dir C:\"]) process.invoke() print(process.stdout.decode("437")) print("RC:", process.rc) # WinRS shell with environment and working directory with wsman, WinRS( wsman, environment={"JAVA_HOME": "C:\\Java\\jdk17"}, working_directory="C:\\App", idle_time_out=30, ) as shell: # Synchronous: run mvn build process = Process(shell, "cmd", ["/c", "mvn package -q"]) process.invoke() process.signal(SignalCode.CTRL_C) print(process.stdout.decode("437")) # Asynchronous (background) invocation bg = Process(shell, "ping", ["-n", "10", "127.0.0.1"]) bg.begin_invoke() # starts immediately, returns bg.poll_invoke() # fetches buffered stdout/stderr # ... do other work here ... bg.end_invoke() # blocks until command finishes bg.signal(SignalCode.CTRL_C) print("Ping output:", bg.stdout.decode("437")) # Send stdin data to a running process proc = Process(shell, "findstr", ["/i", "error"]) proc.begin_invoke() proc.send(b"line 1: no issue\r\nline 2: error occurred\r\n", end=True) proc.end_invoke() print(proc.stdout.decode("437")) ``` ``` -------------------------------- ### Initialize WSMan Client for HTTP with Basic Authentication Source: https://context7.com/jborean93/pypsrp/llms.txt Configure a WSMan client for HTTP connections using Basic authentication. Encryption must be disabled for Basic authentication. ```python from pypsrp.wsman import WSMan wsman_basic = WSMan( "192.168.1.10", ssl=False, auth="basic", encryption="never", username="localadmin", password="secret", port=5985, ) ``` -------------------------------- ### Execute Commands with WinRS/Process Source: https://github.com/jborean93/pypsrp/blob/master/README.md Shows how to use pypsrp.shell.Process with a WinRS shell to execute commands. This includes basic invocation, signaling a process, and background execution with begin_invoke, poll_invoke, and end_invoke. Ensure WSMan and WinRS are correctly configured. ```python from pypsrp.shell import Process, SignalCode, WinRS from pypsrp.wsman import WSMan # creates a http connection with no encryption and basic auth wsman = WSMan("server", ssl=False, auth="basic", encryption="never", username="vagrant", password="vagrant") with wsman, WinRS(wsman) as shell: process = Process(shell, "dir") process.invoke() process.signal(SignalCode.CTRL_C) # execute a process with arguments in the background process = Process(shell, "powershell", ["gci", "$pwd"]) process.begin_invoke() # start the invocation and return immediately process.poll_invoke() # update the output stream process.end_invoke() # finally wait until the process is finished process.signal(SignalCode.CTRL_C) ``` -------------------------------- ### Client.fetch Source: https://context7.com/jborean93/pypsrp/llms.txt Fetches a file from the remote Windows host to a local path. Validates the SHA-1 checksum automatically. ```APIDOC ## Client.fetch ### Description Fetches a file from the remote Windows host to a local path. Validates the SHA-1 checksum automatically. ### Method ```python Client.fetch(src: str, dest: str, expand_variables: bool = False) -> None ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python client.fetch( src="C:\\Windows\\System32\\winevt\\Logs\\Application.evtx", dest="/tmp/application.evtx", ) client.fetch( src="%SystemRoot%\\System32\\drivers\\etc\\hosts", dest="/tmp/windows-hosts", expand_variables=True, ) try: client.fetch("C:\\data\\report.csv", "~/report.csv") except WinRMError as e: print("Fetch failed:", e) ``` ### Response #### Success Response (200) None (The file is downloaded to the specified local path). #### Response Example None ``` -------------------------------- ### Initialize WSMan Client for HTTPS with Negotiate Authentication Source: https://context7.com/jborean93/pypsrp/llms.txt Configure a WSMan client for HTTPS connections, specifying authentication method, SSL settings, timeouts, and envelope size. Use cert_validation=False to skip TLS certificate verification. ```python from pypsrp.wsman import WSMan wsman = WSMan( "winhost.corp.example.com", username="CORP\svcaccount", password="P@ssw0rd!", ssl=True, auth="negotiate", cert_validation=False, # skip TLS cert verification operation_timeout=60, # WSMan operation timeout in seconds read_timeout=65, # HTTP read timeout (must be > operation_timeout) max_envelope_size=512000, # 500 KiB envelope — use for PS v3+ hosts reconnection_retries=3, reconnection_backoff=2.0, ) ``` -------------------------------- ### Execute Commands and Scripts with High-Level Client API Source: https://github.com/jborean93/pypsrp/blob/master/README.md Demonstrates using the high-level pypsrp.client.Client for executing cmd commands, PowerShell scripts, and performing file copy operations. Ensure the Client is properly initialized with server details and authentication credentials. ```python from pypsrp.client import Client # this takes in the same kwargs as the WSMan object with Client("server", username="user", password="password") as client: # execute a cmd command stdout, stderr, rc = client.execute_cmd("dir") stdout, stderr, rc = client.execute_cmd("powershell.exe gci $pwd") sanitised_stderr = client.sanitise_clixml(stderr) # execute a PowerShell script output, streams, had_errors = client.execute_ps('''$path = "%s" if (Test-Path -Path $path) { Remove-Item -Path $path -Force -Recurse } New-Item -Path $path -ItemType Directory''' % path) output, streams, had_errors = client.execute_ps("New-Item -Path C:\\temp\\folder -ItemType Directory") # copy a file from the local host to the remote host client.copy("~/file.txt", "C:\\temp\\file.txt") # fetch a file from the remote host to the local host client.fetch("C:\\temp\\file.txt", "~/file.txt") ``` -------------------------------- ### Client High-Level API Source: https://context7.com/jborean93/pypsrp/llms.txt The `Client` class is a convenience wrapper over `WSMan`, `WinRS`, and `RunspacePool`. It is recommended for straightforward remote execution, file copy, and file fetch operations. ```APIDOC ## Client - High-Level API ### Description The `Client` class provides a simplified interface for common remote operations by abstracting the underlying WSMan, WinRS, and RunspacePool layers. It is the recommended starting point for users who need to perform tasks like executing commands, copying files, or fetching files from remote Windows hosts. ### Method `Client(host, username=None, password=None, ..., **kwargs)` ### Endpoint N/A (Python class constructor) ### Parameters (The `Client` class accepts similar parameters to the `WSMan` constructor, as it wraps `WSMan` internally. Refer to the `WSMan` documentation for detailed parameter descriptions.) ### Request Example ```python from pypsrp.client import Client # Initialize a client connection with Client( "winhost.corp.example.com", username="CORP\svcaccount", password="P@ssw0rd!", ssl=True, auth="negotiate", ) as client: # Execute a command command_output = client.run_command("Get-Process") print(command_output.std_out) # Copy a file to the remote host with open("local_file.txt", "rb") as f_in: client.put_file("C:\\remote_path\\remote_file.txt", f_in) # Fetch a file from the remote host with open("downloaded_file.txt", "wb") as f_out: client.get_file("C:\\remote_path\\remote_file.txt", f_out) ``` ### Response #### Success Response (Method Execution) - **run_command**: Returns an object containing `std_out`, `std_err`, and `exit_code`. - **put_file**: Returns None on success. - **get_file**: Returns None on success (writes to the provided file object). #### Response Example (See Request Example for method execution results) ``` -------------------------------- ### Fetch Files with Client.fetch Source: https://context7.com/jborean93/pypsrp/llms.txt Fetches a file from a remote Windows host to a local path. Automatically validates the SHA-1 checksum. Supports environment variable expansion in the source path. ```python from pypsrp.client import Client from pypsrp.exceptions import WinRMError with Client("winhost.example.com", username="user", password="pass") as client: # Fetch a log file client.fetch( src="C:\\Windows\\System32\\winevt\\Logs\\Application.evtx", dest="/tmp/application.evtx", ) # Fetch using environment variable expansion in the remote path client.fetch( src="%SystemRoot%\\System32\\drivers\\etc\\hosts", dest="/tmp/windows-hosts", expand_variables=True, ) # Fetch with error handling (checksum mismatch raises WinRMError) try: client.fetch("C:\\data\\report.csv", "~/report.csv") except WinRMError as e: print("Fetch failed:", e) ``` -------------------------------- ### Client.execute_cmd Source: https://context7.com/jborean93/pypsrp/llms.txt Executes a raw cmd command via WinRS and returns (stdout, stderr, rc) as unicode strings and an integer. ```APIDOC ## Client.execute_cmd ### Description Executes a raw cmd command via WinRS and returns `(stdout, stderr, rc)` as unicode strings and an integer. ### Method ```python Client.execute_cmd(command: str, environment: Optional[Dict[str, str]] = None) -> Tuple[str, str, int] ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python stdout, stderr, rc = client.execute_cmd("ipconfig /all") print("Exit code:", rc) print(stdout) stdout, stderr, rc = client.execute_cmd( "powershell.exe -Command Get-Process", ) clean_stderr = client.sanitise_clixml(stderr) if rc != 0: print("Error output:", clean_stderr) stdout, stderr, rc = client.execute_cmd( "cmd /c echo %MY_VAR%", environment={"MY_VAR": "hello_world"}, ) print(stdout.strip()) # hello_world ``` ### Response #### Success Response (200) - **stdout** (str) - Standard output of the command. - **stderr** (str) - Standard error of the command. - **rc** (int) - The return code of the command. #### Response Example ``` Exit code: 0 Windows IP Configuration ... (output of ipconfig /all) ``` ``` -------------------------------- ### Execute PowerShell Scripts with RunspacePool/PowerShell Source: https://github.com/jborean93/pypsrp/blob/master/README.md Illustrates how to use pypsrp.powershell.PowerShell with a RunspacePool to execute PowerShell scripts and commands. This involves adding scripts/cmdlets and parameters before invoking the process. Requires a configured WSMan and RunspacePool. ```python from pypsrp.powershell import PowerShell, RunspacePool from pypsrp.wsman import WSMan ``` -------------------------------- ### Initialize WSMan Client for Certificate Authentication Source: https://context7.com/jborean93/pypsrp/llms.txt Configure a WSMan client for mutual TLS (certificate) authentication, providing paths to the client certificate and key. The key password can be omitted if the key is not encrypted. ```python from pypsrp.wsman import WSMan wsman_cert = WSMan( "server.example.com", auth="certificate", certificate_pem="/etc/ssl/certs/client.pem", certificate_key_pem="/etc/ssl/private/client.key", certificate_key_password="keypassword", # omit if key is not encrypted ) ``` -------------------------------- ### Handle pypsrp Exceptions Source: https://context7.com/jborean93/pypsrp/llms.txt Demonstrates how to catch and handle various pypsrp exceptions, including authentication, WSMan faults, and transport errors. Ensure you import the necessary exception classes. ```python from pypsrp.exceptions import ( WinRMError, AuthenticationError, WinRMTransportError, WSManFaultError, InvalidRunspacePoolStateError, InvalidPipelineStateError, InvalidPSRPOperation, FragmentError, SerializationError, ) from pypsrp.wsman import WSMan from pypsrp.powershell import RunspacePool, PowerShell with WSMan("winhost.example.com", username="user", password="badpass") as wsman: try: with RunspacePool(wsman) as pool: ps = PowerShell(pool) ps.add_cmdlet("Get-Date") ps.invoke() except AuthenticationError as e: print("Auth error:", e) except WSManFaultError as e: # e.g. shell already closed, resource not found print(f"WSManFault code={e.code} reason={e.reason} machine={e.machine}") except WinRMTransportError as e: print(f"HTTP {e.protocol.upper()} {e.code}: {e.response_text[:200]}") except WinRMError as e: print("Generic WinRM error:", e) ``` -------------------------------- ### RunspacePool Management and Configuration Source: https://context7.com/jborean93/pypsrp/llms.txt Illustrates managing PowerShell runspace pools, including setting concurrency limits, checking available runspaces, and adjusting pool settings dynamically. Supports protocol version and PowerShell version checks. ```python from pypsrp.powershell import PowerShell, RunspacePool from pypsrp.wsman import WSMan wsman = WSMan("winhost.example.com", username="user", password="pass") # Pool supporting up to 5 concurrent pipelines with wsman, RunspacePool(wsman, min_runspaces=1, max_runspaces=5) as pool: print("Protocol version:", pool.protocol_version) # e.g. "2.3" print("PS version:", pool.ps_version) # e.g. "2.0" # Check available runspaces available = pool.get_available_runspaces() print("Available runspaces:", available) # Dynamic runspace count adjustment while the pool is open pool.min_runspaces = 2 pool.max_runspaces = 10 # Reset variable state (requires protocol 2.3 / Server 2016+) pool.reset_runspace_state() # Disconnect / reconnect pattern with wsman, RunspacePool(wsman) as pool: ps = PowerShell(pool) ps.add_script("Start-Sleep -Seconds 30; 'done'") ps.begin_invoke() pool.disconnect() # disconnect from the running pool # ... reconnect from the same or another client ... pool.connect() ps.end_invoke() print(ps.output[0]) # 'done' # Application arguments (accessible via $PSSenderInfo.ApplicationArguments) with wsman, RunspacePool(wsman) as pool: pool.open(application_arguments={"Environment": "prod", "Version": "1.2.3"}) # Get metadata for all installed commands matching a wildcard with wsman, RunspacePool(wsman) as pool: from pypsrp.complex_objects import CommandType meta_list = pool.get_command_metadata("Get-*", command_types=CommandType.CMDLET) for m in meta_list[:3]: print(m.name) ``` -------------------------------- ### Configure Environment Variables for Remote Testing Source: https://github.com/jborean93/pypsrp/blob/master/README.md Set these environment variables before running tests against a real Windows host. Defaults are provided for port and authentication protocol. ```bash # PYPSRP_SERVER: The hostname or IP of the remote host # PYPSRP_USERNAME: The username to connect with # PYPSRP_PASSWORD: The password to connect with # PYPSRR_PORT: The port to connect with (default: 5986) # PYPSRP_AUTH: The authentication protocol to auth with (default: negotiate) ``` -------------------------------- ### Client.copy Source: https://context7.com/jborean93/pypsrp/llms.txt Copies a local file to a remote Windows path. Returns the resolved absolute remote path. ```APIDOC ## Client.copy ### Description Copies a local file to a remote Windows path. Returns the resolved absolute remote path. ### Method ```python Client.copy(src: str, dest: str, expand_variables: bool = False, configuration_name: Optional[str] = None) -> str ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python remote_path = client.copy( src="/tmp/deploy-package.zip", dest="C:\\Deploy\\deploy-package.zip", ) print("Uploaded to:", remote_path) remote_path = client.copy( src="~/installer.msi", dest="%TEMP%\\installer.msi", expand_variables=True, ) remote_path = client.copy( src="/opt/scripts/run.ps1", dest="C:\\Scripts\\run.ps1", configuration_name="Microsoft.PowerShell", ) ``` ### Response #### Success Response (200) - **remote_path** (str) - The absolute path to the copied file on the remote host. #### Response Example ``` C:\Deploy\deploy-package.zip ``` ``` -------------------------------- ### PowerShell - Pipeline Execution Source: https://context7.com/jborean93/pypsrp/llms.txt Runs cmdlets, scripts, and pipelines within a RunspacePool, mirroring the .NET PowerShell class with fluent builder methods. ```APIDOC ## PowerShell — Pipeline Execution `PowerShell` runs cmdlets, scripts, and pipelines inside a `RunspacePool`. It mirrors the .NET `PowerShell` class with fluent builder methods. ``` -------------------------------- ### Set Environment Variables for Integration Tests Source: https://github.com/jborean93/pypsrp/blob/master/README.md Set these environment variables before running the test suite to enable integration tests. Ensure PYPSRP_CERT_DIR points to the full project directory. ```bash export PYPSRP_RUN_INTEGRATION=1 export PYPSRP_SERVER=127.0.0.1 export PYPSRP_USERNAME=vagrant export PYPSRP_PASSWORD=vagrant export PYPSRP_HTTP_PORT=55985 export PYPSRP_HTTPS_PORT=55986 export PYPSRP_CERT_DIR=/path/to/project ``` -------------------------------- ### Configure pypsrp Logging with JSON Source: https://github.com/jborean93/pypsrp/blob/master/README.md This JSON configuration enables logging for the pypsrp library. Set the PYPSRP_LOG_CFG environment variable to the path of this file to activate logging. Adjust the 'level' in the 'pypsrp' logger to control verbosity. ```json { "version": 1, "disable_existing_loggers": false, "formatters": { "simple": { "format": "% (asctime)s - % (name)s - % (levelname)s - % (message)s" } }, "handlers": { "console": { "class": "logging.StreamHandler", "level": "DEBUG", "formatter": "simple", "stream": "ext://sys.stdout" } }, "loggers": { "pypsrp": { "level": "DEBUG", "handlers": ["console"], "propagate": "no" } } } ``` -------------------------------- ### Execute Raw CMD Commands with Client.execute_cmd Source: https://context7.com/jborean93/pypsrp/llms.txt Executes raw cmd commands via WinRS. Supports passing environment variables and sanitizing CLIXML stderr from PowerShell commands. ```python from pypsrp.client import Client from pypsrp.exceptions import WinRMError, AuthenticationError with Client( "winhost.example.com", username="Administrator", password="P@ssw0rd", ssl=False, auth="ntlm", encryption="never", ) as client: try: stdout, stderr, rc = client.execute_cmd("ipconfig /all") print("Exit code:", rc) print(stdout) # Run an executable with arguments stdout, stderr, rc = client.execute_cmd( "powershell.exe -Command Get-Process", ) # stderr from PowerShell contains CLIXML; decode it: clean_stderr = client.sanitise_clixml(stderr) if rc != 0: print("Error output:", clean_stderr) # Pass environment variables to the cmd process stdout, stderr, rc = client.execute_cmd( "cmd /c echo %MY_VAR%", environment={"MY_VAR": "hello_world"}, ) print(stdout.strip()) # hello_world except AuthenticationError as e: print("Auth failed:", e) except WinRMError as e: print("WinRM error:", e) ``` -------------------------------- ### Copy Files with Client.copy Source: https://context7.com/jborean93/pypsrp/llms.txt Copies a local file to a remote Windows path. Supports expanding environment variables in the destination path and targeting specific PowerShell configuration endpoints. ```python from pypsrp.client import Client with Client("winhost.example.com", username="user", password="pass") as client: # Copy a file to an explicit path remote_path = client.copy( src="/tmp/deploy-package.zip", dest="C:\\Deploy\\deploy-package.zip", ) print("Uploaded to:", remote_path) # Expand environment variables in the remote destination path remote_path = client.copy( src="~/installer.msi", dest="%TEMP%\\installer.msi", expand_variables=True, ) # Use a non-default PowerShell configuration endpoint remote_path = client.copy( src="/opt/scripts/run.ps1", dest="C:\\Scripts\\run.ps1", configuration_name="Microsoft.PowerShell", ) ``` -------------------------------- ### Fluent Command Construction and Synchronous Invocation Source: https://context7.com/jborean93/pypsrp/llms.txt Construct PowerShell commands fluently and invoke them synchronously. Supports adding multiple cmdlets, parameters, and statements. Ensure the PowerShell object is closed and cleared when finished. ```python from pypsrp.powershell import PowerShell, RunspacePool from pypsrp.wsman import WSMan with WSMan("winhost.example.com", username="user", password="pass") as wsman, \ RunspacePool(wsman) as pool, \ PowerShell(pool) as ps: # Get-Process | Select-Object Name, CPU | Sort-Object CPU -Descending ps.add_cmdlet("Get-Process") \ .add_cmdlet("Select-Object").add_parameters({"Property": ["Name", "CPU"]}) \ .add_cmdlet("Sort-Object").add_parameter("Property", "CPU").add_parameter("Descending", True) output = ps.invoke() for obj in output[:5]: print(obj) # Pipeline must be closed before reuse (ps used as context manager handles this) ps.close() ps.clear_commands() ps.clear_streams() # Two statements separated by add_statement (equivalent to semicolon in PS) ps.add_cmdlet("Get-Service").add_argument("wuauserv").add_statement() ps.add_cmdlet("Get-Service").add_argument("bits") services = ps.invoke() for svc in services: print(svc) ps.close() ps.clear_commands() ps.clear_streams() # Raw script with input data piped in script = """ begin { $results = @() } process { $results += $input } end { { $results | Sort-Object | Get-Unique } """ ps.add_script(script) unique_sorted = ps.invoke(input=["banana", "apple", "banana", "cherry", "apple"]) print(unique_sorted) # ['apple', 'banana', 'cherry'] ``` -------------------------------- ### Enable pypsrp Verbose Logging Source: https://context7.com/jborean93/pypsrp/llms.txt Command to run a Python script with verbose protocol-level logging enabled for pypsrp. This requires setting the PYPSRP_LOG_CFG environment variable to the path of the logging configuration file. ```bash # Enable verbose protocol-level logging (includes all SOAP messages) PYPSRP_LOG_CFG=log.json python my_script.py ``` -------------------------------- ### Client.execute_ps Source: https://context7.com/jborean93/pypsrp/llms.txt Executes a PowerShell script via PSRP and returns (output_str, streams, had_errors). ```APIDOC ## Client.execute_ps ### Description Executes a PowerShell script via PSRP and returns `(output_str, streams, had_errors)`. ### Method ```python Client.execute_ps(script: str, configuration_name: Optional[str] = None, environment: Optional[Dict[str, str]] = None) -> Tuple[str, Any, bool] ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python output, streams, had_errors = client.execute_ps("Get-ComputerInfo | Select-Object -Property OsName, WindowsVersion") print(output) script = """ $ErrorActionPreference = 'Stop' $disks = Get-PSDrive -PSProvider FileSystem | Select-Object Name, @{N='FreeGB';E={[math]::Round($_.Free/1GB,2)}} $disks | ConvertTo-Json """ output, streams, had_errors = client.execute_ps(script) if had_errors: for err in streams.error: print("PS Error:", err) else: import json disks = json.loads(output) for d in disks: print(f"Drive {d['Name']}: {d['FreeGB']} GB free") output, streams, had_errors = client.execute_ps( "Write-Output $env:DEPLOY_ENV", environment={"DEPLOY_ENV": "production"}, ) print(output.strip()) # production output, streams, _ = client.execute_ps( "Get-Restricted-Info", configuration_name="JEARole", ) ``` ### Response #### Success Response (200) - **output_str** (str) - The standard output of the PowerShell script. - **streams** (Any) - An object containing various output streams (e.g., error, warning, verbose). - **had_errors** (bool) - True if the script encountered errors, False otherwise. #### Response Example ``` { "OsName": "Microsoft Windows 10 Pro", "WindowsVersion": "10.0.19045" } ``` ``` -------------------------------- ### Configure pypsrp Logging Source: https://context7.com/jborean93/pypsrp/llms.txt A JSON configuration for Python's logging module to enable verbose logging for pypsrp. This configuration directs DEBUG level logs from the 'pypsrp' logger to standard output. ```json { "version": 1, "disable_existing_loggers": false, "formatters": { "simple": { "format": "% (asctime)s - %(name)s - %(levelname)s - %(message)s" } }, "handlers": { "console": { "class": "logging.StreamHandler", "level": "DEBUG", "formatter": "simple", "stream": "ext://sys.stdout" } }, "loggers": { "pypsrp": { "level": "DEBUG", "handlers": ["console"], "propagate": "no" } } } ```