Python library for Windows Remote Management (WinRM) service enabling remote command execution and PowerShell scripts on Windows machines.
—
High-level interface for executing commands and PowerShell scripts on remote Windows machines. The Session class provides automatic shell management, simplified error handling, and the most convenient API for typical WinRM usage scenarios.
Creates a WinRM session to a target Windows host with authentication and transport configuration.
class Session:
def __init__(
self,
target: str,
auth: tuple[str, str],
**kwargs
):
"""
Create WinRM session to target host.
Parameters:
- target: Windows host (hostname, IP, or URL)
- auth: (username, password) tuple
- transport: authentication method ("plaintext", "ssl", "ntlm", "kerberos", "credssp", "basic", "certificate")
- server_cert_validation: "validate" or "ignore" (default: "validate")
- ca_trust_path: CA certificate path or "legacy_requests" (default: "legacy_requests")
- cert_pem: client certificate file path (for certificate auth)
- cert_key_pem: client certificate key file path (for certificate auth)
- read_timeout_sec: HTTP read timeout in seconds (default: 30)
- operation_timeout_sec: WinRM operation timeout in seconds (default: 20)
- kerberos_delegation: enable Kerberos delegation (default: False)
- kerberos_hostname_override: override hostname for Kerberos (optional)
- message_encryption: "auto", "always", or "never" (default: "auto")
- proxy: proxy configuration or "legacy_requests" (default: "legacy_requests")
"""The target parameter supports flexible URL formats:
windows-host → http://windows-host:5985/wsmanwindows-host:1111 → http://windows-host:1111/wsmanhttp://windows-host → http://windows-host:5985/wsmanhttp://windows-host:1111/wsman → http://windows-host:1111/wsmanExecute Windows batch commands with arguments and receive structured output.
def run_cmd(
self,
command: str,
args: collections.abc.Iterable[str | bytes] = ()
) -> Response:
"""
Execute a command on the remote Windows host.
Parameters:
- command: command to execute (e.g., 'ipconfig', 'dir', 'powershell')
- args: command arguments as iterable of strings or bytes
Returns:
Response object with std_out, std_err, and status_code
Example:
r = session.run_cmd('ipconfig', ['/all'])
r = session.run_cmd('dir', ['C:\\', '/w'])
"""Usage Example:
import winrm
s = winrm.Session('192.168.1.100', auth=('Administrator', 'password'))
# Simple command
r = s.run_cmd('hostname')
print(r.std_out.decode('utf-8'))
# Command with arguments
r = s.run_cmd('dir', ['C:\\Windows', '/b'])
if r.status_code == 0:
files = r.std_out.decode('utf-8').strip().split('\n')
print(f"Found {len(files)} items")Execute PowerShell scripts with automatic base64 UTF-16LE encoding and CLIXML error processing.
def run_ps(self, script: str) -> Response:
"""
Execute PowerShell script on remote host.
The script is automatically encoded in base64 UTF-16LE format
and executed using 'powershell -encodedcommand'. CLIXML error
messages are automatically cleaned and made human-readable.
Parameters:
- script: PowerShell script as string
Returns:
Response object with processed output and errors
Example:
script = "Get-Process | Where-Object {$_.CPU -gt 100}"
r = session.run_ps(script)
"""Usage Example:
# System information script
ps_script = """
$computer = Get-ComputerInfo
[PSCustomObject]@{
'Computer' = $computer.CsName
'OS' = $computer.WindowsProductName
'Version' = $computer.WindowsVersion
'Memory' = [math]::Round($computer.CsTotalPhysicalMemory / 1GB, 2)
}
"""
r = s.run_ps(ps_script)
if r.status_code == 0:
print("System Info:", r.std_out.decode('utf-8'))
else:
print("Error:", r.std_err.decode('utf-8'))
# Service management
service_script = """
Get-Service | Where-Object {$_.Status -eq 'Running'} |
Select-Object Name, DisplayName, Status | ConvertTo-Json
"""
r = s.run_ps(service_script)Utility method for constructing WinRM endpoint URLs from various target formats.
@staticmethod
def _build_url(target: str, transport: str) -> str:
"""
Build WinRM endpoint URL from target specification.
Handles various target formats and adds appropriate defaults
based on transport type (SSL/HTTP ports, wsman path).
Parameters:
- target: target specification (hostname, IP, or partial URL)
- transport: transport type affecting default ports
Returns:
Complete WinRM endpoint URL
"""pywinrm[kerberos])pywinrm[credssp])# NTLM with encryption
s = winrm.Session(
'windows-host.domain.com',
auth=('domain\\user', 'password'),
transport='ntlm',
message_encryption='always'
)
# Kerberos authentication
s = winrm.Session(
'windows-host.domain.com',
auth=('user@DOMAIN.COM', 'password'),
transport='kerberos',
kerberos_delegation=True
)
# SSL with custom certificate validation
s = winrm.Session(
'https://windows-host:5986/wsman',
auth=('user', 'password'),
transport='ssl',
server_cert_validation='ignore' # Only for testing
)Install with Tessl CLI
npx tessl i tessl/pypi-pywinrm