Python library for Windows Remote Management (WinRM) service enabling remote command execution and PowerShell scripts on Windows machines.
npx @tessl/cli install tessl/pypi-pywinrm@0.5.0A Python client library for Windows Remote Management (WinRM) service that enables remote command execution and PowerShell scripts on Windows machines from any Python-capable system. It supports multiple authentication methods including basic, NTLM, Kerberos, CredSSP, and certificate-based authentication, with built-in encryption capabilities for secure communication.
pip install pywinrmOptional dependencies:
pip install pywinrm[kerberos]pip install pywinrm[credssp]import winrmFor direct class access:
from winrm import Session, Response, Protocol
from winrm.exceptions import WinRMError, WSManFaultErrorimport winrm
# Create a session with target Windows host
s = winrm.Session('windows-host.example.com', auth=('username', 'password'))
# Run a command
r = s.run_cmd('ipconfig', ['/all'])
print(f"Status: {r.status_code}")
print(f"Output: {r.std_out.decode('utf-8')}")
print(f"Error: {r.std_err.decode('utf-8')}")
# Run PowerShell script
ps_script = """
Get-ComputerInfo | Select-Object WindowsProductName, TotalPhysicalMemory
"""
r = s.run_ps(ps_script)
print(f"PowerShell result: {r.std_out.decode('utf-8')}")PyWinRM follows a layered architecture:
The Session class provides the most convenient interface for typical use cases, while the Protocol class offers fine-grained control over WinRM operations including shell management, streaming I/O, and timeout handling.
High-level interface for executing commands and PowerShell scripts on remote Windows machines. Provides automatic shell management and simplified error handling.
class Session:
def __init__(self, target: str, auth: tuple[str, str], **kwargs): ...
def run_cmd(self, command: str, args: collections.abc.Iterable[str | bytes] = ()) -> Response: ...
def run_ps(self, script: str) -> Response: ...Low-level SOAP protocol implementation providing full control over WinRM operations including shell lifecycle management, command streaming, and advanced configuration options.
class Protocol:
def __init__(self, endpoint: str, transport: str = "plaintext", username: str | None = None, password: str | None = None, **kwargs): ...
def open_shell(self, **kwargs) -> str: ...
def close_shell(self, shell_id: str, close_session: bool = True): ...
def run_command(self, shell_id: str, command: str, arguments: collections.abc.Iterable[str | bytes] = (), **kwargs) -> str: ...
def get_command_output(self, shell_id: str, command_id: str) -> tuple[bytes, bytes, int]: ...Response containers that encapsulate command execution results including output streams and exit codes.
class Response:
std_out: bytes
std_err: bytes
status_code: int
def __init__(self, args: tuple[bytes, bytes, int]): ...Support for multiple authentication methods and secure communication protocols with message-level encryption capabilities.
# Version information
__version__: str # Library version (e.g., "0.5.0")
# Feature flags for client capability detection
FEATURE_SUPPORTED_AUTHTYPES: list[str] # ["basic", "certificate", "ntlm", "kerberos", "plaintext", "ssl", "credssp"]
FEATURE_READ_TIMEOUT: bool # Read timeout support
FEATURE_OPERATION_TIMEOUT: bool # Operation timeout support
FEATURE_PROXY_SUPPORT: bool # Proxy support
# Utility functions
def strtobool(value: str) -> bool:
"""
Convert string representation of truth to True or False.
Accepts: 'true', 't', 'yes', 'y', 'on', '1' (case-insensitive) for True
Accepts: 'false', 'f', 'no', 'n', 'off', '0' (case-insensitive) for False
"""
# Transport and encryption classes
class Transport: ...
class Encryption: ...Comprehensive exception hierarchy for handling WinRM-specific errors, transport failures, and authentication issues.
class WinRMError(Exception): ...
class WSManFaultError(WinRMError): ...
class WinRMTransportError(Exception): ...
class WinRMOperationTimeoutError(Exception): ...
class AuthenticationError(WinRMError): ...# Required imports for type annotations
from typing import Literal, Any
import uuid
import collections.abc
import requests
# Response tuple format for command output
CommandOutput = tuple[bytes, bytes, int] # (stdout, stderr, status_code)
# Authentication tuple format
AuthTuple = tuple[str, str] # (username, password)
# Transport types
TransportType = Literal["auto", "basic", "certificate", "ntlm", "kerberos", "credssp", "plaintext", "ssl"]
# Server certificate validation options
CertValidationType = Literal["validate", "ignore"]
# Message encryption options
EncryptionType = Literal["auto", "always", "never"]
# CA trust path options
CATrustPathType = Literal["legacy_requests"] | str
# Proxy configuration options
ProxyType = Literal["legacy_requests"] | str | None