0
# Session Interface
1
2
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.
3
4
## Capabilities
5
6
### Session Creation
7
8
Creates a WinRM session to a target Windows host with authentication and transport configuration.
9
10
```python { .api }
11
class Session:
12
def __init__(
13
self,
14
target: str,
15
auth: tuple[str, str],
16
**kwargs
17
):
18
"""
19
Create WinRM session to target host.
20
21
Parameters:
22
- target: Windows host (hostname, IP, or URL)
23
- auth: (username, password) tuple
24
- transport: authentication method ("plaintext", "ssl", "ntlm", "kerberos", "credssp", "basic", "certificate")
25
- server_cert_validation: "validate" or "ignore" (default: "validate")
26
- ca_trust_path: CA certificate path or "legacy_requests" (default: "legacy_requests")
27
- cert_pem: client certificate file path (for certificate auth)
28
- cert_key_pem: client certificate key file path (for certificate auth)
29
- read_timeout_sec: HTTP read timeout in seconds (default: 30)
30
- operation_timeout_sec: WinRM operation timeout in seconds (default: 20)
31
- kerberos_delegation: enable Kerberos delegation (default: False)
32
- kerberos_hostname_override: override hostname for Kerberos (optional)
33
- message_encryption: "auto", "always", or "never" (default: "auto")
34
- proxy: proxy configuration or "legacy_requests" (default: "legacy_requests")
35
"""
36
```
37
38
The target parameter supports flexible URL formats:
39
- `windows-host` → `http://windows-host:5985/wsman`
40
- `windows-host:1111` → `http://windows-host:1111/wsman`
41
- `http://windows-host` → `http://windows-host:5985/wsman`
42
- `http://windows-host:1111/wsman` → `http://windows-host:1111/wsman`
43
44
### Command Execution
45
46
Execute Windows batch commands with arguments and receive structured output.
47
48
```python { .api }
49
def run_cmd(
50
self,
51
command: str,
52
args: collections.abc.Iterable[str | bytes] = ()
53
) -> Response:
54
"""
55
Execute a command on the remote Windows host.
56
57
Parameters:
58
- command: command to execute (e.g., 'ipconfig', 'dir', 'powershell')
59
- args: command arguments as iterable of strings or bytes
60
61
Returns:
62
Response object with std_out, std_err, and status_code
63
64
Example:
65
r = session.run_cmd('ipconfig', ['/all'])
66
r = session.run_cmd('dir', ['C:\\', '/w'])
67
"""
68
```
69
70
**Usage Example:**
71
72
```python
73
import winrm
74
75
s = winrm.Session('192.168.1.100', auth=('Administrator', 'password'))
76
77
# Simple command
78
r = s.run_cmd('hostname')
79
print(r.std_out.decode('utf-8'))
80
81
# Command with arguments
82
r = s.run_cmd('dir', ['C:\\Windows', '/b'])
83
if r.status_code == 0:
84
files = r.std_out.decode('utf-8').strip().split('\n')
85
print(f"Found {len(files)} items")
86
```
87
88
### PowerShell Script Execution
89
90
Execute PowerShell scripts with automatic base64 UTF-16LE encoding and CLIXML error processing.
91
92
```python { .api }
93
def run_ps(self, script: str) -> Response:
94
"""
95
Execute PowerShell script on remote host.
96
97
The script is automatically encoded in base64 UTF-16LE format
98
and executed using 'powershell -encodedcommand'. CLIXML error
99
messages are automatically cleaned and made human-readable.
100
101
Parameters:
102
- script: PowerShell script as string
103
104
Returns:
105
Response object with processed output and errors
106
107
Example:
108
script = "Get-Process | Where-Object {$_.CPU -gt 100}"
109
r = session.run_ps(script)
110
"""
111
```
112
113
**Usage Example:**
114
115
```python
116
# System information script
117
ps_script = """
118
$computer = Get-ComputerInfo
119
[PSCustomObject]@{
120
'Computer' = $computer.CsName
121
'OS' = $computer.WindowsProductName
122
'Version' = $computer.WindowsVersion
123
'Memory' = [math]::Round($computer.CsTotalPhysicalMemory / 1GB, 2)
124
}
125
"""
126
127
r = s.run_ps(ps_script)
128
if r.status_code == 0:
129
print("System Info:", r.std_out.decode('utf-8'))
130
else:
131
print("Error:", r.std_err.decode('utf-8'))
132
133
# Service management
134
service_script = """
135
Get-Service | Where-Object {$_.Status -eq 'Running'} |
136
Select-Object Name, DisplayName, Status | ConvertTo-Json
137
"""
138
139
r = s.run_ps(service_script)
140
```
141
142
### Internal URL Building
143
144
Utility method for constructing WinRM endpoint URLs from various target formats.
145
146
```python { .api }
147
@staticmethod
148
def _build_url(target: str, transport: str) -> str:
149
"""
150
Build WinRM endpoint URL from target specification.
151
152
Handles various target formats and adds appropriate defaults
153
based on transport type (SSL/HTTP ports, wsman path).
154
155
Parameters:
156
- target: target specification (hostname, IP, or partial URL)
157
- transport: transport type affecting default ports
158
159
Returns:
160
Complete WinRM endpoint URL
161
"""
162
```
163
164
## Transport Configuration
165
166
### Authentication Methods
167
168
- **plaintext**: HTTP without encryption (default, port 5985)
169
- **ssl**: HTTPS transport (port 5986)
170
- **basic**: HTTP Basic authentication
171
- **ntlm**: NTLM authentication with optional message encryption
172
- **kerberos**: Kerberos authentication (requires `pywinrm[kerberos]`)
173
- **credssp**: CredSSP authentication (requires `pywinrm[credssp]`)
174
- **certificate**: Client certificate authentication
175
176
### Secure Transport Example
177
178
```python
179
# NTLM with encryption
180
s = winrm.Session(
181
'windows-host.domain.com',
182
auth=('domain\\user', 'password'),
183
transport='ntlm',
184
message_encryption='always'
185
)
186
187
# Kerberos authentication
188
s = winrm.Session(
189
'windows-host.domain.com',
190
auth=('user@DOMAIN.COM', 'password'),
191
transport='kerberos',
192
kerberos_delegation=True
193
)
194
195
# SSL with custom certificate validation
196
s = winrm.Session(
197
'https://windows-host:5986/wsman',
198
auth=('user', 'password'),
199
transport='ssl',
200
server_cert_validation='ignore' # Only for testing
201
)
202
```