0
# PyWinRM
1
2
A 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.
3
4
## Package Information
5
6
- **Package Name**: pywinrm
7
- **Language**: Python
8
- **Installation**: `pip install pywinrm`
9
10
Optional dependencies:
11
- **Kerberos**: `pip install pywinrm[kerberos]`
12
- **CredSSP**: `pip install pywinrm[credssp]`
13
14
## Core Imports
15
16
```python
17
import winrm
18
```
19
20
For direct class access:
21
22
```python
23
from winrm import Session, Response, Protocol
24
from winrm.exceptions import WinRMError, WSManFaultError
25
```
26
27
## Basic Usage
28
29
```python
30
import winrm
31
32
# Create a session with target Windows host
33
s = winrm.Session('windows-host.example.com', auth=('username', 'password'))
34
35
# Run a command
36
r = s.run_cmd('ipconfig', ['/all'])
37
print(f"Status: {r.status_code}")
38
print(f"Output: {r.std_out.decode('utf-8')}")
39
print(f"Error: {r.std_err.decode('utf-8')}")
40
41
# Run PowerShell script
42
ps_script = """
43
Get-ComputerInfo | Select-Object WindowsProductName, TotalPhysicalMemory
44
"""
45
r = s.run_ps(ps_script)
46
print(f"PowerShell result: {r.std_out.decode('utf-8')}")
47
```
48
49
## Architecture
50
51
PyWinRM follows a layered architecture:
52
53
- **Session**: High-level interface for common operations (run_cmd, run_ps)
54
- **Protocol**: Low-level SOAP/WS-Management implementation for advanced usage
55
- **Transport**: HTTP transport layer with authentication and encryption support
56
- **Encryption**: Message-level encryption for secure protocols (NTLM, Kerberos, CredSSP)
57
58
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.
59
60
## Capabilities
61
62
### Session Interface
63
64
High-level interface for executing commands and PowerShell scripts on remote Windows machines. Provides automatic shell management and simplified error handling.
65
66
```python { .api }
67
class Session:
68
def __init__(self, target: str, auth: tuple[str, str], **kwargs): ...
69
def run_cmd(self, command: str, args: collections.abc.Iterable[str | bytes] = ()) -> Response: ...
70
def run_ps(self, script: str) -> Response: ...
71
```
72
73
[Session Interface](./session.md)
74
75
### Protocol Interface
76
77
Low-level SOAP protocol implementation providing full control over WinRM operations including shell lifecycle management, command streaming, and advanced configuration options.
78
79
```python { .api }
80
class Protocol:
81
def __init__(self, endpoint: str, transport: str = "plaintext", username: str | None = None, password: str | None = None, **kwargs): ...
82
def open_shell(self, **kwargs) -> str: ...
83
def close_shell(self, shell_id: str, close_session: bool = True): ...
84
def run_command(self, shell_id: str, command: str, arguments: collections.abc.Iterable[str | bytes] = (), **kwargs) -> str: ...
85
def get_command_output(self, shell_id: str, command_id: str) -> tuple[bytes, bytes, int]: ...
86
```
87
88
[Protocol Interface](./protocol.md)
89
90
### Response Objects
91
92
Response containers that encapsulate command execution results including output streams and exit codes.
93
94
```python { .api }
95
class Response:
96
std_out: bytes
97
std_err: bytes
98
status_code: int
99
def __init__(self, args: tuple[bytes, bytes, int]): ...
100
```
101
102
[Response Objects](./response.md)
103
104
### Authentication & Security
105
106
Support for multiple authentication methods and secure communication protocols with message-level encryption capabilities.
107
108
```python { .api }
109
# Version information
110
__version__: str # Library version (e.g., "0.5.0")
111
112
# Feature flags for client capability detection
113
FEATURE_SUPPORTED_AUTHTYPES: list[str] # ["basic", "certificate", "ntlm", "kerberos", "plaintext", "ssl", "credssp"]
114
FEATURE_READ_TIMEOUT: bool # Read timeout support
115
FEATURE_OPERATION_TIMEOUT: bool # Operation timeout support
116
FEATURE_PROXY_SUPPORT: bool # Proxy support
117
118
# Utility functions
119
def strtobool(value: str) -> bool:
120
"""
121
Convert string representation of truth to True or False.
122
123
Accepts: 'true', 't', 'yes', 'y', 'on', '1' (case-insensitive) for True
124
Accepts: 'false', 'f', 'no', 'n', 'off', '0' (case-insensitive) for False
125
"""
126
127
# Transport and encryption classes
128
class Transport: ...
129
class Encryption: ...
130
```
131
132
[Authentication & Security](./auth-security.md)
133
134
### Exception Handling
135
136
Comprehensive exception hierarchy for handling WinRM-specific errors, transport failures, and authentication issues.
137
138
```python { .api }
139
class WinRMError(Exception): ...
140
class WSManFaultError(WinRMError): ...
141
class WinRMTransportError(Exception): ...
142
class WinRMOperationTimeoutError(Exception): ...
143
class AuthenticationError(WinRMError): ...
144
```
145
146
[Exception Handling](./exceptions.md)
147
148
## Types
149
150
```python { .api }
151
# Required imports for type annotations
152
from typing import Literal, Any
153
import uuid
154
import collections.abc
155
import requests
156
157
# Response tuple format for command output
158
CommandOutput = tuple[bytes, bytes, int] # (stdout, stderr, status_code)
159
160
# Authentication tuple format
161
AuthTuple = tuple[str, str] # (username, password)
162
163
# Transport types
164
TransportType = Literal["auto", "basic", "certificate", "ntlm", "kerberos", "credssp", "plaintext", "ssl"]
165
166
# Server certificate validation options
167
CertValidationType = Literal["validate", "ignore"]
168
169
# Message encryption options
170
EncryptionType = Literal["auto", "always", "never"]
171
172
# CA trust path options
173
CATrustPathType = Literal["legacy_requests"] | str
174
175
# Proxy configuration options
176
ProxyType = Literal["legacy_requests"] | str | None
177
```