or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.mdversion-compatibility.mdwinrm-hook.mdwinrm-operator.md

winrm-hook.mddocs/

0

# WinRM Hook

1

2

Comprehensive WinRM connection management and command execution hook for Apache Airflow. Provides low-level interface for establishing secure connections to Windows systems and executing commands or PowerShell scripts remotely.

3

4

## Types

5

6

```python { .api }

7

from winrm.protocol import Protocol

8

from airflow.providers.microsoft.winrm.version_compat import BaseHook

9

```

10

11

## Capabilities

12

13

### Hook Initialization

14

15

Create WinRM hook instances with flexible configuration options supporting multiple authentication methods and security settings.

16

17

```python { .api }

18

class WinRMHook(BaseHook):

19

def __init__(

20

self,

21

ssh_conn_id: str | None = None,

22

endpoint: str | None = None,

23

remote_host: str | None = None,

24

remote_port: int = 5985,

25

transport: str = "plaintext",

26

username: str | None = None,

27

password: str | None = None,

28

service: str = "HTTP",

29

keytab: str | None = None,

30

ca_trust_path: str | None = None,

31

cert_pem: str | None = None,

32

cert_key_pem: str | None = None,

33

server_cert_validation: str = "validate",

34

kerberos_delegation: bool = False,

35

read_timeout_sec: int = 30,

36

operation_timeout_sec: int = 20,

37

kerberos_hostname_override: str | None = None,

38

message_encryption: str | None = "auto",

39

credssp_disable_tlsv1_2: bool = False,

40

send_cbt: bool = True,

41

) -> None:

42

"""

43

Initialize WinRM hook with connection parameters.

44

45

Parameters:

46

- ssh_conn_id: Airflow connection ID containing WinRM settings

47

- endpoint: Full WinRM endpoint URL (auto-constructed if not provided)

48

- remote_host: Target Windows host IP address or hostname

49

- remote_port: WinRM service port (5985 for HTTP, 5986 for HTTPS)

50

- transport: Authentication transport ('plaintext', 'kerberos', 'ssl', 'ntlm', 'credssp')

51

- username: Username for authentication (auto-detected if not provided)

52

- password: Password for authentication

53

- service: Service name for Kerberos authentication

54

- keytab: Path to Kerberos keytab file

55

- ca_trust_path: Certificate Authority trust path for SSL validation

56

- cert_pem: Client certificate file in PEM format

57

- cert_key_pem: Client certificate private key file in PEM format

58

- server_cert_validation: Certificate validation mode ('validate' or 'ignore')

59

- kerberos_delegation: Enable Kerberos ticket delegation

60

- read_timeout_sec: HTTP connection read timeout

61

- operation_timeout_sec: WinRM operation timeout

62

- kerberos_hostname_override: Override hostname for Kerberos

63

- message_encryption: Message encryption setting ('auto', 'always', 'never')

64

- credssp_disable_tlsv1_2: Disable TLS v1.2 for CredSSP authentication

65

- send_cbt: Send channel binding tokens over HTTPS

66

"""

67

```

68

69

**Usage Examples:**

70

71

```python

72

# Using Airflow connection

73

hook = WinRMHook(ssh_conn_id='windows_server_1')

74

75

# Direct configuration with NTLM

76

hook = WinRMHook(

77

remote_host='192.168.1.100',

78

username='administrator',

79

password='SecurePass123',

80

transport='ntlm'

81

)

82

83

# SSL with certificate authentication

84

hook = WinRMHook(

85

remote_host='winserver.company.com',

86

remote_port=5986,

87

transport='ssl',

88

cert_pem='/path/to/client.pem',

89

cert_key_pem='/path/to/client-key.pem',

90

server_cert_validation='validate'

91

)

92

93

# Kerberos authentication

94

hook = WinRMHook(

95

remote_host='winserver.domain.com',

96

transport='kerberos',

97

service='HTTP',

98

kerberos_delegation=True

99

)

100

```

101

102

### Connection Management

103

104

Establish and manage WinRM protocol connections with comprehensive configuration from Airflow connections or direct parameters.

105

106

```python { .api }

107

def get_conn(self) -> Protocol:

108

"""

109

Create and return WinRM protocol connection.

110

111

Handles connection parameter resolution from Airflow connections,

112

endpoint construction, authentication setup, and protocol initialization.

113

114

Returns:

115

winrm.protocol.Protocol: Configured WinRM protocol instance

116

117

Raises:

118

AirflowException: Connection creation failures, missing parameters, authentication errors

119

"""

120

```

121

122

**Connection Parameter Resolution:**

123

124

The hook resolves connection parameters in this priority order:

125

1. Constructor parameters (highest priority)

126

2. Airflow connection extra parameters

127

3. Airflow connection basic parameters (host, login, password)

128

4. System defaults (username from getuser())

129

130

**Supported Extra Parameters in Airflow Connections:**

131

132

```json

133

{

134

"endpoint": "https://winserver:5986/wsman",

135

"remote_port": 5986,

136

"transport": "ssl",

137

"service": "HTTP",

138

"keytab": "/etc/krb5.keytab",

139

"ca_trust_path": "/etc/ssl/certs/ca-certificates.crt",

140

"cert_pem": "/path/to/client.pem",

141

"cert_key_pem": "/path/to/client-key.pem",

142

"server_cert_validation": "validate",

143

"kerberos_delegation": "true",

144

"read_timeout_sec": 60,

145

"operation_timeout_sec": 45,

146

"kerberos_hostname_override": "winserver.domain.com",

147

"message_encryption": "auto",

148

"credssp_disable_tlsv1_2": "false",

149

"send_cbt": "true"

150

}

151

```

152

153

### Command Execution

154

155

Execute Windows commands and PowerShell scripts on remote systems with comprehensive output handling and error management.

156

157

```python { .api }

158

def run(

159

self,

160

command: str,

161

ps_path: str | None = None,

162

output_encoding: str = "utf-8",

163

return_output: bool = True,

164

) -> tuple[int, list[bytes], list[bytes]]:

165

"""

166

Execute command on remote Windows host via WinRM.

167

168

Parameters:

169

- command: Command or script to execute on remote host

170

- ps_path: PowerShell executable path ('powershell' for v5.1-, 'pwsh' for v6+)

171

- output_encoding: Encoding for stdout/stderr decoding

172

- return_output: Whether to accumulate and return stdout data

173

174

Returns:

175

tuple: (return_code, stdout_buffer, stderr_buffer)

176

- return_code: Command exit code

177

- stdout_buffer: List of stdout byte chunks

178

- stderr_buffer: List of stderr byte chunks

179

180

Raises:

181

AirflowException: Connection failures, command execution errors

182

"""

183

```

184

185

**Command Execution Examples:**

186

187

```python

188

# Execute Windows command

189

return_code, stdout, stderr = hook.run('dir C:\\Windows\\System32')

190

191

# Execute PowerShell command

192

return_code, stdout, stderr = hook.run(

193

'Get-Service | Where-Object Status -eq "Running" | Select-Object Name, Status',

194

ps_path='powershell'

195

)

196

197

# Execute PowerShell script with modern PowerShell

198

return_code, stdout, stderr = hook.run(

199

'''

200

$processes = Get-Process | Sort-Object CPU -Descending | Select-Object -First 10

201

$processes | Format-Table Name, CPU, WorkingSet -AutoSize

202

''',

203

ps_path='pwsh'

204

)

205

206

# Execute command without output buffering (for large outputs)

207

return_code, stdout, stderr = hook.run(

208

'robocopy C:\\Source D:\\Backup /E /LOG:backup.log',

209

return_output=False

210

)

211

```

212

213

**PowerShell Script Encoding:**

214

215

When `ps_path` is specified, commands are automatically encoded using PowerShell's `-encodedcommand` parameter to handle special characters and multi-line scripts properly. The encoding process:

216

217

1. Encodes the command string to UTF-16LE bytes

218

2. Base64 encodes the UTF-16LE bytes

219

3. Executes: `{ps_path} -encodedcommand {base64_encoded_command}`

220

221

This ensures proper handling of Unicode characters, quotes, and multi-line PowerShell scripts.

222

223

### Connection Testing

224

225

Validate WinRM connections with built-in connection testing functionality.

226

227

```python { .api }

228

def test_connection(self) -> tuple[bool, str]:

229

"""

230

Test WinRM connection by executing a simple command.

231

232

Executes 'cd' command to verify connectivity and authentication.

233

234

Returns:

235

tuple: (success, message)

236

- success: True if connection successful, False otherwise

237

- message: Success message or error description

238

"""

239

```

240

241

**Usage Example:**

242

243

```python

244

hook = WinRMHook(ssh_conn_id='windows_server_1')

245

success, message = hook.test_connection()

246

247

if success:

248

print(f"Connection successful: {message}")

249

else:

250

print(f"Connection failed: {message}")

251

```

252

253

## Authentication Methods

254

255

### Plaintext Authentication

256

257

Basic authentication with username and password transmitted in plaintext. Only recommended for trusted networks.

258

259

```python

260

hook = WinRMHook(

261

remote_host='192.168.1.100',

262

username='admin',

263

password='password',

264

transport='plaintext'

265

)

266

```

267

268

### NTLM Authentication

269

270

Windows NTLM authentication providing secure credential transmission with challenge-response protocol.

271

272

```python

273

hook = WinRMHook(

274

remote_host='winserver.local',

275

username='DOMAIN\\user',

276

password='password',

277

transport='ntlm'

278

)

279

```

280

281

### Kerberos Authentication

282

283

Enterprise-grade Kerberos authentication with ticket-based security and delegation support.

284

285

```python

286

hook = WinRMHook(

287

remote_host='winserver.domain.com',

288

username='user@DOMAIN.COM',

289

transport='kerberos',

290

service='HTTP',

291

kerberos_delegation=True,

292

kerberos_hostname_override='winserver.domain.com'

293

)

294

```

295

296

### SSL/TLS Authentication

297

298

Secure transport with SSL/TLS encryption and optional certificate-based client authentication.

299

300

```python

301

hook = WinRMHook(

302

remote_host='winserver.company.com',

303

remote_port=5986,

304

username='admin',

305

password='password',

306

transport='ssl',

307

cert_pem='/path/to/client.pem',

308

cert_key_pem='/path/to/client-key.pem',

309

ca_trust_path='/path/to/ca-bundle.crt',

310

server_cert_validation='validate'

311

)

312

```

313

314

### CredSSP Authentication

315

316

Credential Security Support Provider enabling credential delegation for multi-hop scenarios.

317

318

```python

319

hook = WinRMHook(

320

remote_host='winserver.domain.com',

321

username='DOMAIN\\user',

322

password='password',

323

transport='credssp',

324

credssp_disable_tlsv1_2=False

325

)

326

```

327

328

## Error Handling

329

330

The WinRMHook handles various error conditions:

331

332

- **Connection Errors**: Network connectivity issues, invalid hostnames, port unavailability

333

- **Authentication Errors**: Invalid credentials, expired certificates, Kerberos ticket issues

334

- **Command Execution Errors**: Command failures, timeout conditions, encoding issues

335

- **Configuration Errors**: Missing required parameters, invalid transport types, malformed endpoints

336

- **Timeout Handling**: `WinRMOperationTimeoutError` is caught and handled silently for long-running processes

337

338

All errors are wrapped in `AirflowException` with descriptive error messages for troubleshooting. The hook also handles different pywinrm library versions gracefully by attempting `get_command_output_raw()` first, then falling back to `_raw_get_command_output()` for older versions.