lib.winrm
This library collects some Microsoft WinRM related functions.
1#!/usr/bin/env python3 2# -*- coding: utf-8; py-indent-offset: 4 -*- 3# 4# Author: Linuxfabrik GmbH, Zurich, Switzerland 5# Contact: info (at) linuxfabrik (dot) ch 6# https://www.linuxfabrik.ch/ 7# License: The Unlicense, see LICENSE file. 8 9# https://github.com/Linuxfabrik/lib/blob/main/CONTRIBUTING.md 10 11"""This library collects some Microsoft WinRM related functions.""" 12 13__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland' 14__version__ = '2026102403' 15 16import base64 17import re 18import threading 19import warnings 20 21try: 22 import winrm 23 24 HAVE_WINRM = True 25except ImportError: 26 HAVE_WINRM = False 27 28try: 29 from pypsrp.client import Client 30 31 HAVE_JEA = True 32except ImportError: 33 HAVE_JEA = False 34 35from . import txt 36 37_AUTH_MAP = { 38 'kerberos': 'kerberos', 39 'negotiate': 'negotiate', 40 'ntlm': 'ntlm', 41 'credssp': 'credssp', 42 'basic': 'basic', 43 'plaintext': 'basic', 44 'ssl': 'basic', 45} 46 47 48def _build_auth(args): 49 """ 50 Build a `(username, password)` tuple from `args`. 51 52 For Kerberos/negotiate transports with missing credentials, 53 returns `(None, None)` so the library falls back to the 54 Kerberos credential cache (`kinit`). Otherwise prepends 55 `WINRM_DOMAIN` to the username when set. 56 57 Parameters 58 ---------- 59 args 60 Object with `WINRM_USERNAME`, 61 `WINRM_PASSWORD`, `WINRM_TRANSPORT`, and optionally 62 `WINRM_DOMAIN`. 63 64 Returns 65 ------- 66 tuple 67 `(username, password)` suitable for 68 pypsrp or pywinrm. 69 """ 70 username = getattr(args, 'WINRM_USERNAME', None) 71 password = getattr(args, 'WINRM_PASSWORD', None) 72 transport = (getattr(args, 'WINRM_TRANSPORT', None) or '').lower() 73 if transport in ('kerberos', 'negotiate') and (not username or not password): 74 return (None, None) 75 if getattr(args, 'WINRM_DOMAIN', None): 76 return (f'{username}@{args.WINRM_DOMAIN}', password) 77 return (username, password) 78 79 80def _map_transport(args): 81 """ 82 Derive PSRP auth method, SSL flag, and port from `args`. 83 84 Parameters 85 ---------- 86 args 87 Object with `WINRM_TRANSPORT`. 88 89 Returns 90 ------- 91 tuple 92 `(psrp_auth, use_ssl, port)`. 93 """ 94 transport = (getattr(args, 'WINRM_TRANSPORT', None) or '').lower() 95 psrp_auth = _AUTH_MAP.get(transport, 'negotiate') 96 use_ssl = transport == 'ssl' 97 port = 5986 if use_ssl else 5985 98 return (psrp_auth, use_ssl, port) 99 100 101def _pywinrm_transport(args, auth): 102 """ 103 Return the pywinrm transport for `args`, which knows no `negotiate`. 104 105 `negotiate`, the documented default, is what pypsrp speaks; pywinrm refuses it with 106 "unsupported auth method", and a missing transport the same way. Negotiate picks 107 Kerberos or NTLM, so without credentials, where `_build_auth()` leaves the Kerberos 108 credential cache to it, it becomes `kerberos`, and with credentials `ntlm`. Every 109 other value is one pywinrm knows and passes as it is. Verified against pywinrm 110 v0.5.0 (`winrm/transport.py`, `build_session()`). 111 112 Parameters 113 ---------- 114 args 115 Object with `WINRM_TRANSPORT`. 116 auth : tuple 117 `(username, password)` as `_build_auth()` returns it. 118 119 Returns 120 ------- 121 str 122 The transport to hand to `winrm.Session()`. 123 """ 124 transport = (getattr(args, 'WINRM_TRANSPORT', None) or '').lower() 125 if transport in ('', 'negotiate'): 126 return 'ntlm' if auth[0] and auth[1] else 'kerberos' 127 return transport 128 129 130def _ps_literal(value): 131 """ 132 Return a PowerShell expression that evaluates to `str(value)`, whatever it holds. 133 134 The value travels base64-encoded and is decoded on the remote host, so it never 135 appears in the script text. Quoting cannot give that guarantee: PowerShell closes a 136 single-quoted string on the typographic quotes U+2018 to U+201B as well, so a value 137 carrying one of them ends the literal and turns the rest into script, however the 138 ASCII quote is escaped. Verified against Windows PowerShell 5.1 on Windows Server 139 2025 and PowerShell 7.6 on RHEL 9. The base64 alphabet contains no quote and no 140 operator, which fixes the boundaries of the value before the value is known. 141 142 Parameters 143 ---------- 144 value 145 The value (converted to `str`). 146 147 Returns 148 ------- 149 str 150 A parenthesized expression, usable as an argument or parameter value. 151 """ 152 encoded = txt.to_text(base64.b64encode(txt.to_bytes(str(value)))) 153 return ( 154 f"([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('{encoded}')))" 155 ) 156 157 158def _native_call(cmd, params): 159 """ 160 Return a command line that runs `cmd` with `params` without `cmd.exe` parsing them. 161 162 WinRS hands a command line to `cmd.exe`, where `&`, `|` and `>` in an argument start 163 a second command. The command line returned here holds nothing but base64: it starts 164 PowerShell with an encoded script that calls `cmd` with each argument decoded from 165 its own literal. A program that cannot be started yields return code 1 and the 166 reason on stderr, as it would from `cmd.exe`, instead of `exit $null` reporting 167 success. 168 169 Parameters 170 ---------- 171 cmd : str 172 The program to run. 173 params : list 174 Its arguments (each converted to `str`). 175 176 Returns 177 ------- 178 str 179 The command line to hand to WinRS. 180 """ 181 call = ' '.join(['&', *(_ps_literal(item) for item in [cmd, *params])]) 182 script = ( 183 "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; " 184 f'try {{ {call} }} ' 185 'catch { [Console]::Error.WriteLine($_.ToString()); exit 1 }; ' 186 'exit $LASTEXITCODE' 187 ) 188 encoded = txt.to_text(base64.b64encode(txt.to_bytes(script, encoding='utf-16-le'))) 189 return f'powershell.exe -NoProfile -NonInteractive -EncodedCommand {encoded}' 190 191 192def _within(timeout, func, *args): 193 """ 194 Return what `func(*args)` returns, or a timeout result when it takes longer. 195 196 Neither backend bounds a whole call: both poll for output again and again while the 197 remote command runs, so a command that hangs blocks the caller forever. The call 198 runs in a daemon thread instead, which the caller leaves behind when the timeout 199 has passed; it ends with the process. The remote command keeps running until the 200 WinRM service closes the shell nobody polls any more: after `_IDLE_TIMEOUT` for the 201 runspace of `run_ps()` over pypsrp 0.9 and newer, after the idle timeout of the 202 service otherwise (two hours by default). 203 204 Parameters 205 ---------- 206 timeout : int or float or None 207 Seconds to wait. `None` waits as long as the call takes. 208 func : callable 209 The call, returning a result dictionary. 210 *args 211 Its arguments. 212 213 Returns 214 ------- 215 dict 216 The result of `func`, or `{'retc': 1, 'stdout': '', 217 'stderr': 'Timeout after <timeout> seconds.'}`. 218 """ 219 if timeout is None: 220 return func(*args) 221 results = [] 222 worker = threading.Thread(target=lambda: results.append(func(*args))) 223 worker.daemon = True 224 worker.start() 225 worker.join(timeout) 226 if results: 227 return results[0] 228 return { 229 'retc': 1, 230 'stdout': '', 231 'stderr': f'Timeout after {timeout} seconds.', 232 } 233 234 235def _run_cmd(args, cmd, params): 236 """Run `run_cmd()` without a timeout, see there.""" 237 auth = _build_auth(args) 238 command = _native_call(cmd, params) if params else cmd 239 240 if HAVE_JEA: 241 try: 242 _psrp_auth, _use_ssl, _port = _map_transport(args) 243 session = Client( 244 server=args.WINRM_HOSTNAME, 245 username=auth[0], 246 password=auth[1], 247 auth=_psrp_auth, 248 ssl=_use_ssl, 249 port=_port, 250 cert_validation=True, 251 ) 252 253 stdout, stderr, rc = session.execute_cmd(command) 254 return { 255 'retc': rc, 256 'stdout': txt.to_text(stdout, errors='strict_or_latin1'), 257 'stderr': txt.to_text(stderr, errors='strict_or_latin1'), 258 } 259 except Exception as e: 260 return { 261 'retc': 1, 262 'stdout': '', 263 'stderr': txt.exception2text(e), 264 } 265 266 if HAVE_WINRM: 267 try: 268 session = winrm.Session( 269 args.WINRM_HOSTNAME, 270 auth=auth, 271 transport=_pywinrm_transport(args, auth), 272 ) 273 274 result = session.run_cmd(command) 275 return { 276 'retc': result.status_code, 277 'stdout': txt.to_text(result.std_out, errors='strict_or_latin1'), 278 'stderr': txt.to_text(result.std_err, errors='strict_or_latin1'), 279 } 280 except Exception as e: 281 return { 282 'retc': 1, 283 'stdout': '', 284 'stderr': txt.exception2text(e), 285 } 286 287 return { 288 'retc': 1, 289 'stdout': '', 290 'stderr': 'No compatible remoting library available (pypsrp or pywinrm).', 291 } 292 293 294def run_cmd(args, cmd, params=None, timeout=None): 295 """ 296 Run a native command on a remote Windows host via WinRM/PSRP and return a 297 normalized result dictionary. 298 299 Prefers **pypsrp (PSRP)** if available (for JEA/PowerShell Remoting 300 compatibility); otherwise falls back to **pywinrm**. Authentication, 301 transport and SSL/port selection are derived from the provided `args`. 302 303 Parameters 304 ---------- 305 args 306 An object (e.g., `argparse.Namespace`) that provides at least: 307 308 - `WINRM_HOSTNAME` (`str`): Target host or IP. 309 - `WINRM_USERNAME` (`str`, optional): Username. If `None` or empty when using 310 Kerberos transport, will use existing Kerberos credentials from credential cache 311 (e.g., obtained via `kinit`). 312 - `WINRM_PASSWORD` (`str`, optional): Password. If `None` or empty when using 313 Kerberos transport, will use existing Kerberos credentials from credential cache. 314 - `WINRM_TRANSPORT` (`str`, optional): Transport (e.g., `'negotiate'`, `'kerberos'`, 315 `'ntlm'`, `'credssp'`, `'basic'`, `'ssl'`). Defaults to `'negotiate'` if unset. 316 - `WINRM_DOMAIN` (`str`, optional): If set, username is sent as `user@domain`. 317 (Additional fields may be honored by the underlying libraries if present.) 318 cmd : str 319 The executable/command to run remotely (native command, not a PowerShell 320 script block). Without `params` it is handed to `cmd.exe` as it stands, so it 321 must not contain untrusted data. 322 params : list[str], optional 323 Positional arguments passed to the command. Each 324 one reaches the program as a single argument, whatever it contains: `cmd.exe` 325 never parses them. Defaults to `None`, which sends no arguments. 326 timeout : int or float, optional 327 Seconds to wait for the result. After that the call returns a result with 328 `retc` 1 and `Timeout after <timeout> seconds.` in `stderr`. Defaults to 329 `None` (no timeout). 330 331 Returns 332 ------- 333 dict 334 A normalized result with: 335 336 - `retc` (`int`): Process return code (`0` on success). 337 - `stdout` (`str`): Captured standard output (text). 338 - `stderr` (`str`): Captured standard error (text). 339 340 Notes 341 ----- 342 - If **pypsrp** is available, maps `WINRM_TRANSPORT` to an appropriate PSRP auth 343 and chooses SSL/port (5986 for SSL, 5985 otherwise), then executes the command 344 via `Client.execute_cmd()`. 345 - If pypsrp is unavailable but **pywinrm** is installed, executes via 346 `Session.run_cmd()`. 347 - With `params`, the command runs through an encoded PowerShell call rather than 348 through `cmd.exe`, which would read `&`, `|` or `>` in an argument as the start 349 of another command. Return code, stdout and stderr are those of the program. A 350 `.bat` or `.cmd` file is still interpreted by `cmd.exe`, arguments included. 351 - For Kerberos authentication: if `WINRM_USERNAME` and `WINRM_PASSWORD` are not provided 352 (or are empty/None), the function will attempt to use existing Kerberos credentials 353 from the credential cache (obtained via `kinit`). 354 - On any exception, returns `{'retc': 1, 'stdout': '', 'stderr': <exception text>}`. 355 - If neither backend is present, returns an error indicating that no compatible 356 remoting library is available. 357 358 Examples 359 -------- 360 >>> # With explicit credentials: 361 >>> run_cmd(args, 'ipconfig', ['/all']) 362 {'retc': 0, 'stdout': 'Windows IP Configuration\\r\\n...','stderr': ''} 363 >>> # With Kerberos using kinit credentials (username/password can be None): 364 >>> run_cmd(args, 'ipconfig', ['/all']) 365 {'retc': 0, 'stdout': 'Windows IP Configuration\\r\\n...','stderr': ''} 366 """ 367 return _within(timeout, _run_cmd, args, cmd, params) 368 369 370def _psrp_objects_to_text(output): 371 """ 372 Render the output objects of a PSRP pipeline as text, like `Format-List`. 373 374 Behind a JEA endpoint the pipeline cannot end in `Out-String`, which the endpoint 375 may not expose, so the objects arrive deserialized, and `str()` of one is only 376 what its `ToString()` returns: the name of a service, the type name of most 377 others. Each property of a complex object becomes a line `Name : Value`, objects 378 are separated by an empty line; a plain value (a string, a number) stays as it is. 379 380 Parameters 381 ---------- 382 output : list 383 What `PowerShell.invoke()` returned. 384 385 Returns 386 ------- 387 str 388 The text. 389 """ 390 blocks = [] 391 for obj in output: 392 properties = {} 393 properties.update(getattr(obj, 'adapted_properties', None) or {}) 394 properties.update(getattr(obj, 'extended_properties', None) or {}) 395 if not properties: 396 blocks.append(str(obj)) 397 continue 398 width = max(len(str(name)) for name in properties) 399 blocks.append( 400 '\n'.join( 401 f'{str(name).ljust(width)} : {"" if value is None else value}' 402 for name, value in properties.items() 403 ) 404 ) 405 separator = '\n\n' if any('\n' in block for block in blocks) else '\n' 406 return separator.join(blocks) 407 408 409# What PowerShell accepts as a parameter name. A name is spliced into the script text as 410# it stands, so anything else could carry script of its own. 411_PS_PARAMETER_NAME = re.compile(r'[A-Za-z_][A-Za-z0-9_]*') 412 413 414# Seconds after which the WinRM service closes a runspace whose client stopped polling, 415# such as one left behind by a timeout. A client that waits for output polls at least 416# every 20 seconds, so a command that runs longer is not affected. The service default 417# of two hours lets abandoned runspaces pile up until the shell quota of the account 418# (30 by default) refuses every further connection. Verified against Windows Server 419# 2025: such a runspace was gone about two minutes later instead of two hours. 420_IDLE_TIMEOUT = 60 421 422 423def _runspace_pool(runspace_pool_class, wsman, configuration_name): 424 """ 425 Create the pypsrp runspace pool, with `_IDLE_TIMEOUT` where pypsrp supports it. 426 427 `idle_timeout` exists from pypsrp 0.9.0 on, which needs Python 3.10. On Python 3.9, 428 as on RHEL 8 and 9, the newest pypsrp is 0.8.1, whose pool takes no such argument and 429 keeps the idle timeout of the service. Verified against pypsrp 0.8.1 and 0.9.1. 430 431 Parameters 432 ---------- 433 runspace_pool_class : type 434 `pypsrp.powershell.RunspacePool`. 435 wsman : pypsrp.wsman.WSMan 436 The connection the pool runs on. 437 configuration_name : str 438 The session configuration (endpoint) to connect to. 439 440 Returns 441 ------- 442 pypsrp.powershell.RunspacePool 443 The pool, not opened yet. 444 """ 445 try: 446 return runspace_pool_class( 447 wsman, 448 configuration_name=configuration_name, 449 idle_timeout=_IDLE_TIMEOUT, 450 ) 451 except TypeError: 452 # pypsrp 0.8.1 and older: unexpected keyword argument 'idle_timeout' 453 return runspace_pool_class(wsman, configuration_name=configuration_name) 454 455 456def _run_ps(args, cmd, params): 457 """Run `run_ps()` without a timeout, see there.""" 458 auth = _build_auth(args) 459 460 configuration_name = getattr( 461 args, 462 'WINRM_CONFIGURATION_NAME', 463 None, 464 ) 465 if configuration_name and not HAVE_JEA: 466 return { 467 'retc': 1, 468 'stdout': '', 469 'stderr': 'WINRM_CONFIGURATION_NAME requires ' 470 'pypsrp (JEA). Install pypsrp or ' 471 'unset ' 472 '--winrm-configuration-name.', 473 } 474 475 if HAVE_JEA: 476 try: 477 from pypsrp.powershell import ( 478 PowerShell, 479 RunspacePool, 480 ) 481 from pypsrp.wsman import WSMan 482 483 _psrp_auth, _use_ssl, _port = _map_transport(args) 484 485 wsman = WSMan( 486 server=args.WINRM_HOSTNAME, 487 username=auth[0], 488 password=auth[1], 489 auth=_psrp_auth, 490 ssl=_use_ssl, 491 port=_port, 492 cert_validation=True, 493 ) 494 495 with _runspace_pool( 496 RunspacePool, 497 wsman, 498 configuration_name or 'Microsoft.PowerShell', 499 ) as pool: 500 ps = PowerShell(pool) 501 if params is not None: 502 ps.add_cmdlet(cmd) 503 if isinstance(params, dict): 504 for name, value in params.items(): 505 ps.add_parameter(name, value) 506 else: 507 for param in params: 508 ps.add_argument(param) 509 else: 510 ps.add_script(cmd) 511 if not configuration_name: 512 # Over PSRP the output arrives as objects, and `str()` of an object is 513 # its type name ("System.ServiceProcess.ServiceController"), not what 514 # PowerShell shows for it. Render it as text on the remote side, the 515 # way pywinrm and a local run deliver it. A JEA endpoint may not 516 # expose Out-String, so there the objects stay as they are. 517 ps.add_cmdlet('Out-String').add_parameter('Stream', True) 518 output = ps.invoke() 519 520 if configuration_name: 521 # Without Out-String the objects arrive deserialized; show their 522 # properties the way Format-List does, so the text says what they hold. 523 stdout = _psrp_objects_to_text(output) 524 else: 525 stdout = '\n'.join(str(o) for o in output) 526 527 stderr_lines = [] 528 for err in ps.streams.error: 529 try: 530 stderr_lines.append( 531 err.to_string(), 532 ) 533 except Exception: 534 msg = getattr(err, 'message', None) or str(err) 535 stderr_lines.append(str(msg)) 536 stderr = '\n'.join(stderr_lines) 537 538 return { 539 'retc': 0 if not ps.had_errors else 1, 540 'stdout': txt.to_text(stdout, errors='strict_or_latin1'), 541 'stderr': txt.to_text(stderr, errors='strict_or_latin1'), 542 } 543 except Exception as e: 544 return { 545 'retc': 1, 546 'stdout': '', 547 'stderr': txt.exception2text(e), 548 } 549 550 if HAVE_WINRM: 551 try: 552 session = winrm.Session( 553 args.WINRM_HOSTNAME, 554 auth=auth, 555 transport=_pywinrm_transport(args, auth), 556 ) 557 558 # pywinrm only runs script text, so the structured call pypsrp makes is 559 # rebuilt here: the command and every value are decoded from literals of 560 # their own, and a parameter name has to be one before it is spliced in. 561 if params is not None: 562 if isinstance(params, dict): 563 for name in params: 564 # fullmatch: `$` would let a trailing newline through 565 if not _PS_PARAMETER_NAME.fullmatch(str(name)): 566 return { 567 'retc': 1, 568 'stdout': '', 569 'stderr': f'Invalid PowerShell parameter name: {name}', 570 } 571 arguments = [ 572 f'-{name} {_ps_literal(value)}' 573 for name, value in params.items() 574 ] 575 else: 576 arguments = [_ps_literal(param) for param in params] 577 ps_cmd = ' '.join(['&', _ps_literal(cmd), *arguments]) 578 else: 579 ps_cmd = cmd 580 581 # pywinrm turns the CLIXML progress stream of PowerShell into text and says 582 # so with a Python warning on stderr when that stream is not well-formed, 583 # which the German progress messages of Windows Server 2025 are not. That 584 # warning would end up in the output; the stream itself is dropped 585 # below on success anyway. 586 with warnings.catch_warnings(): 587 warnings.simplefilter('ignore') 588 result = session.run_ps(ps_cmd) 589 590 result = { 591 'retc': result.status_code, 592 'stdout': txt.to_text(result.std_out, errors='strict_or_latin1'), 593 'stderr': txt.to_text(result.std_err, errors='strict_or_latin1'), 594 } 595 if result['retc'] == 0 and result['stderr'].startswith( 596 '#< CLIXML', 597 ): 598 result['stderr'] = '' 599 return result 600 except Exception as e: 601 return { 602 'retc': 1, 603 'stdout': '', 604 'stderr': txt.exception2text(e), 605 } 606 607 return { 608 'retc': 1, 609 'stdout': '', 610 'stderr': 'No compatible remoting library available (pypsrp or pywinrm).', 611 } 612 613 614def run_ps(args, cmd, params=None, timeout=None): 615 """ 616 Run PowerShell on a remote Windows host via WinRM/PSRP 617 and return a normalized result dictionary. 618 619 Prefers **pypsrp (PSRP)** if available (best for 620 JEA/PowerShell Remoting); otherwise falls back to 621 **pywinrm**. 622 623 Parameters 624 ---------- 625 args 626 Object (e.g. `argparse.Namespace`) with: 627 628 - `WINRM_HOSTNAME` (`str`): Target host or IP. 629 - `WINRM_USERNAME` (`str`, optional): Username. 630 If empty with Kerberos transport, the credential 631 cache (`kinit`) is used. 632 - `WINRM_PASSWORD` (`str`, optional): Password. 633 Same Kerberos fallback as username. 634 - `WINRM_TRANSPORT` (`str`, optional): Transport 635 (e.g. `'negotiate'`, `'kerberos'`, `'ntlm'`, 636 `'credssp'`, `'basic'`, `'ssl'`). 637 Defaults to `'negotiate'`. 638 - `WINRM_DOMAIN` (`str`, optional): If set, 639 username is sent as `user@domain`. 640 - `WINRM_CONFIGURATION_NAME` (`str`, optional): 641 JEA endpoint name. Defaults to 642 `'Microsoft.PowerShell'`. Only with **pypsrp**. 643 cmd : str 644 What to execute remotely. Meaning 645 depends on `params`: 646 647 - `params is None`: `cmd` is an arbitrary 648 PowerShell script (pipelines, expressions, etc.) 649 executed via `add_script()`. 650 - `params` given (`list` or `dict`): `cmd` is a 651 single cmdlet name executed via `add_cmdlet()` 652 (optimal for JEA allow/deny). 653 params : list[str], dict, or None 654 - `None` (default): no params, `cmd` is run as a 655 script. 656 - `list[str]`: positional arguments added via 657 `add_argument()`. 658 - `dict`: named parameters added via 659 `add_parameter(name, value)`. 660 Values may be untrusted: each one reaches the cmdlet 661 as a single value, whatever it contains. With 662 **pywinrm** every value is converted to `str`, and a 663 parameter name that PowerShell would not accept is 664 refused with `retc` 1. 665 timeout : int or float, optional 666 Seconds to wait for the result. After that the call returns a result with 667 `retc` 1 and `Timeout after <timeout> seconds.` in `stderr`. Defaults to 668 `None` (no timeout). 669 670 Returns 671 ------- 672 dict 673 Normalized result with: 674 675 - `retc` (`int`): `0` if no errors. 676 - `stdout` (`str`): Captured output. 677 - `stderr` (`str`): Error/diagnostic output. 678 For **pywinrm**: CLIXML progress noise is 679 suppressed when `retc == 0`. 680 681 Examples 682 -------- 683 Pipeline (params=None, uses add_script): 684 >>> run_ps(args, 'Get-Process | Select -First 1') 685 686 Positional params (uses add_cmdlet + add_argument): 687 >>> run_ps(args, 'Get-Service', ['WinRM']) 688 689 Named params (uses add_cmdlet + add_parameter): 690 >>> run_ps( 691 ... args, 692 ... 'Get-WmiObject', 693 ... {'Class': 'Win32_OperatingSystem'}, 694 ... ) 695 """ 696 return _within(timeout, _run_ps, args, cmd, params)
295def run_cmd(args, cmd, params=None, timeout=None): 296 """ 297 Run a native command on a remote Windows host via WinRM/PSRP and return a 298 normalized result dictionary. 299 300 Prefers **pypsrp (PSRP)** if available (for JEA/PowerShell Remoting 301 compatibility); otherwise falls back to **pywinrm**. Authentication, 302 transport and SSL/port selection are derived from the provided `args`. 303 304 Parameters 305 ---------- 306 args 307 An object (e.g., `argparse.Namespace`) that provides at least: 308 309 - `WINRM_HOSTNAME` (`str`): Target host or IP. 310 - `WINRM_USERNAME` (`str`, optional): Username. If `None` or empty when using 311 Kerberos transport, will use existing Kerberos credentials from credential cache 312 (e.g., obtained via `kinit`). 313 - `WINRM_PASSWORD` (`str`, optional): Password. If `None` or empty when using 314 Kerberos transport, will use existing Kerberos credentials from credential cache. 315 - `WINRM_TRANSPORT` (`str`, optional): Transport (e.g., `'negotiate'`, `'kerberos'`, 316 `'ntlm'`, `'credssp'`, `'basic'`, `'ssl'`). Defaults to `'negotiate'` if unset. 317 - `WINRM_DOMAIN` (`str`, optional): If set, username is sent as `user@domain`. 318 (Additional fields may be honored by the underlying libraries if present.) 319 cmd : str 320 The executable/command to run remotely (native command, not a PowerShell 321 script block). Without `params` it is handed to `cmd.exe` as it stands, so it 322 must not contain untrusted data. 323 params : list[str], optional 324 Positional arguments passed to the command. Each 325 one reaches the program as a single argument, whatever it contains: `cmd.exe` 326 never parses them. Defaults to `None`, which sends no arguments. 327 timeout : int or float, optional 328 Seconds to wait for the result. After that the call returns a result with 329 `retc` 1 and `Timeout after <timeout> seconds.` in `stderr`. Defaults to 330 `None` (no timeout). 331 332 Returns 333 ------- 334 dict 335 A normalized result with: 336 337 - `retc` (`int`): Process return code (`0` on success). 338 - `stdout` (`str`): Captured standard output (text). 339 - `stderr` (`str`): Captured standard error (text). 340 341 Notes 342 ----- 343 - If **pypsrp** is available, maps `WINRM_TRANSPORT` to an appropriate PSRP auth 344 and chooses SSL/port (5986 for SSL, 5985 otherwise), then executes the command 345 via `Client.execute_cmd()`. 346 - If pypsrp is unavailable but **pywinrm** is installed, executes via 347 `Session.run_cmd()`. 348 - With `params`, the command runs through an encoded PowerShell call rather than 349 through `cmd.exe`, which would read `&`, `|` or `>` in an argument as the start 350 of another command. Return code, stdout and stderr are those of the program. A 351 `.bat` or `.cmd` file is still interpreted by `cmd.exe`, arguments included. 352 - For Kerberos authentication: if `WINRM_USERNAME` and `WINRM_PASSWORD` are not provided 353 (or are empty/None), the function will attempt to use existing Kerberos credentials 354 from the credential cache (obtained via `kinit`). 355 - On any exception, returns `{'retc': 1, 'stdout': '', 'stderr': <exception text>}`. 356 - If neither backend is present, returns an error indicating that no compatible 357 remoting library is available. 358 359 Examples 360 -------- 361 >>> # With explicit credentials: 362 >>> run_cmd(args, 'ipconfig', ['/all']) 363 {'retc': 0, 'stdout': 'Windows IP Configuration\\r\\n...','stderr': ''} 364 >>> # With Kerberos using kinit credentials (username/password can be None): 365 >>> run_cmd(args, 'ipconfig', ['/all']) 366 {'retc': 0, 'stdout': 'Windows IP Configuration\\r\\n...','stderr': ''} 367 """ 368 return _within(timeout, _run_cmd, args, cmd, params)
Run a native command on a remote Windows host via WinRM/PSRP and return a normalized result dictionary.
Prefers pypsrp (PSRP) if available (for JEA/PowerShell Remoting
compatibility); otherwise falls back to pywinrm. Authentication,
transport and SSL/port selection are derived from the provided args.
Parameters
args: An object (e.g.,
argparse.Namespace) that provides at least:WINRM_HOSTNAME(str): Target host or IP.WINRM_USERNAME(str, optional): Username. IfNoneor empty when using Kerberos transport, will use existing Kerberos credentials from credential cache (e.g., obtained viakinit).WINRM_PASSWORD(str, optional): Password. IfNoneor empty when using Kerberos transport, will use existing Kerberos credentials from credential cache.WINRM_TRANSPORT(str, optional): Transport (e.g.,'negotiate','kerberos','ntlm','credssp','basic','ssl'). Defaults to'negotiate'if unset.WINRM_DOMAIN(str, optional): If set, username is sent asuser@domain. (Additional fields may be honored by the underlying libraries if present.)
- cmd (str):
The executable/command to run remotely (native command, not a PowerShell
script block). Without
paramsit is handed tocmd.exeas it stands, so it must not contain untrusted data. - params (list[str], optional):
Positional arguments passed to the command. Each
one reaches the program as a single argument, whatever it contains:
cmd.exenever parses them. Defaults toNone, which sends no arguments. - timeout (int or float, optional):
Seconds to wait for the result. After that the call returns a result with
retc1 andTimeout after <timeout> seconds.instderr. Defaults toNone(no timeout).
Returns
dict: A normalized result with:
retc(int): Process return code (0on success).stdout(str): Captured standard output (text).stderr(str): Captured standard error (text).
Notes
- If pypsrp is available, maps
WINRM_TRANSPORTto an appropriate PSRP auth and chooses SSL/port (5986 for SSL, 5985 otherwise), then executes the command viaClient.execute_cmd(). - If pypsrp is unavailable but pywinrm is installed, executes via
Session.run_cmd(). - With
params, the command runs through an encoded PowerShell call rather than throughcmd.exe, which would read&,|or>in an argument as the start of another command. Return code, stdout and stderr are those of the program. A.bator.cmdfile is still interpreted bycmd.exe, arguments included. - For Kerberos authentication: if
WINRM_USERNAMEandWINRM_PASSWORDare not provided (or are empty/None), the function will attempt to use existing Kerberos credentials from the credential cache (obtained viakinit). - On any exception, returns
{'retc': 1, 'stdout': '', 'stderr': <exception text>}. - If neither backend is present, returns an error indicating that no compatible remoting library is available.
Examples
>>> # With explicit credentials:
>>> run_cmd(args, 'ipconfig', ['/all'])
{'retc': 0, 'stdout': 'Windows IP Configuration\r\n...','stderr': ''}
>>> # With Kerberos using kinit credentials (username/password can be None):
>>> run_cmd(args, 'ipconfig', ['/all'])
{'retc': 0, 'stdout': 'Windows IP Configuration\r\n...','stderr': ''}
615def run_ps(args, cmd, params=None, timeout=None): 616 """ 617 Run PowerShell on a remote Windows host via WinRM/PSRP 618 and return a normalized result dictionary. 619 620 Prefers **pypsrp (PSRP)** if available (best for 621 JEA/PowerShell Remoting); otherwise falls back to 622 **pywinrm**. 623 624 Parameters 625 ---------- 626 args 627 Object (e.g. `argparse.Namespace`) with: 628 629 - `WINRM_HOSTNAME` (`str`): Target host or IP. 630 - `WINRM_USERNAME` (`str`, optional): Username. 631 If empty with Kerberos transport, the credential 632 cache (`kinit`) is used. 633 - `WINRM_PASSWORD` (`str`, optional): Password. 634 Same Kerberos fallback as username. 635 - `WINRM_TRANSPORT` (`str`, optional): Transport 636 (e.g. `'negotiate'`, `'kerberos'`, `'ntlm'`, 637 `'credssp'`, `'basic'`, `'ssl'`). 638 Defaults to `'negotiate'`. 639 - `WINRM_DOMAIN` (`str`, optional): If set, 640 username is sent as `user@domain`. 641 - `WINRM_CONFIGURATION_NAME` (`str`, optional): 642 JEA endpoint name. Defaults to 643 `'Microsoft.PowerShell'`. Only with **pypsrp**. 644 cmd : str 645 What to execute remotely. Meaning 646 depends on `params`: 647 648 - `params is None`: `cmd` is an arbitrary 649 PowerShell script (pipelines, expressions, etc.) 650 executed via `add_script()`. 651 - `params` given (`list` or `dict`): `cmd` is a 652 single cmdlet name executed via `add_cmdlet()` 653 (optimal for JEA allow/deny). 654 params : list[str], dict, or None 655 - `None` (default): no params, `cmd` is run as a 656 script. 657 - `list[str]`: positional arguments added via 658 `add_argument()`. 659 - `dict`: named parameters added via 660 `add_parameter(name, value)`. 661 Values may be untrusted: each one reaches the cmdlet 662 as a single value, whatever it contains. With 663 **pywinrm** every value is converted to `str`, and a 664 parameter name that PowerShell would not accept is 665 refused with `retc` 1. 666 timeout : int or float, optional 667 Seconds to wait for the result. After that the call returns a result with 668 `retc` 1 and `Timeout after <timeout> seconds.` in `stderr`. Defaults to 669 `None` (no timeout). 670 671 Returns 672 ------- 673 dict 674 Normalized result with: 675 676 - `retc` (`int`): `0` if no errors. 677 - `stdout` (`str`): Captured output. 678 - `stderr` (`str`): Error/diagnostic output. 679 For **pywinrm**: CLIXML progress noise is 680 suppressed when `retc == 0`. 681 682 Examples 683 -------- 684 Pipeline (params=None, uses add_script): 685 >>> run_ps(args, 'Get-Process | Select -First 1') 686 687 Positional params (uses add_cmdlet + add_argument): 688 >>> run_ps(args, 'Get-Service', ['WinRM']) 689 690 Named params (uses add_cmdlet + add_parameter): 691 >>> run_ps( 692 ... args, 693 ... 'Get-WmiObject', 694 ... {'Class': 'Win32_OperatingSystem'}, 695 ... ) 696 """ 697 return _within(timeout, _run_ps, args, cmd, params)
Run PowerShell on a remote Windows host via WinRM/PSRP and return a normalized result dictionary.
Prefers pypsrp (PSRP) if available (best for JEA/PowerShell Remoting); otherwise falls back to pywinrm.
Parameters
args: Object (e.g.
argparse.Namespace) with:WINRM_HOSTNAME(str): Target host or IP.WINRM_USERNAME(str, optional): Username. If empty with Kerberos transport, the credential cache (kinit) is used.WINRM_PASSWORD(str, optional): Password. Same Kerberos fallback as username.WINRM_TRANSPORT(str, optional): Transport (e.g.'negotiate','kerberos','ntlm','credssp','basic','ssl'). Defaults to'negotiate'.WINRM_DOMAIN(str, optional): If set, username is sent asuser@domain.WINRM_CONFIGURATION_NAME(str, optional): JEA endpoint name. Defaults to'Microsoft.PowerShell'. Only with pypsrp.
cmd (str): What to execute remotely. Meaning depends on
params:params is None:cmdis an arbitrary PowerShell script (pipelines, expressions, etc.) executed viaadd_script().paramsgiven (listordict):cmdis a single cmdlet name executed viaadd_cmdlet()(optimal for JEA allow/deny).
- params (list[str], dict, or None):
None(default): no params,cmdis run as a script.list[str]: positional arguments added viaadd_argument().dict: named parameters added viaadd_parameter(name, value). Values may be untrusted: each one reaches the cmdlet as a single value, whatever it contains. With pywinrm every value is converted tostr, and a parameter name that PowerShell would not accept is refused withretc1.
- timeout (int or float, optional):
Seconds to wait for the result. After that the call returns a result with
retc1 andTimeout after <timeout> seconds.instderr. Defaults toNone(no timeout).
Returns
dict: Normalized result with:
retc(int):0if no errors.stdout(str): Captured output.stderr(str): Error/diagnostic output. For pywinrm: CLIXML progress noise is suppressed whenretc == 0.
Examples
Pipeline (params=None, uses add_script):
>>> run_ps(args, 'Get-Process | Select -First 1')
Positional params (uses add_cmdlet + add_argument):
>>> run_ps(args, 'Get-Service', ['WinRM'])
Named params (uses add_cmdlet + add_parameter):
>>> run_ps(
... args,
... 'Get-WmiObject',
... {'Class': 'Win32_OperatingSystem'},
... )