pywinrm: Python Library for Windows Remote Management
pywinrm is a Python library that enables remote execution of commands on Windows machines using the Windows Remote Management (WinRM) protocol. It supports various authentication mechanisms like Basic, NTLM, and Kerberos, and allows running both CMD and PowerShell commands. The current stable version is 0.5.0, with updates occurring periodically to address bugs and improve compatibility.
Warnings
- gotcha The package installed via pip is `pywinrm`, but the module to import in your Python code is `winrm`. Forgetting this leads to `ModuleNotFoundError`.
- gotcha By default, pywinrm attempts to verify SSL certificates for HTTPS connections. If connecting to Windows servers with self-signed or untrusted certificates (common in internal networks), this will lead to SSL errors.
- gotcha Older versions of `winrm.Session` expected separate `host` and `port` arguments. Current versions (0.4.x and above) expect a full `url` string for the WinRM endpoint.
- gotcha There are subtle differences between `run_cmd` and `run_ps` when executing commands, especially regarding quoting and special characters. PowerShell commands should generally use `run_ps`.
Install
-
pip install pywinrm -
pip install pywinrm[kerberos]
Imports
- Session
from winrm import Session
- Protocol
from winrm import Protocol
Quickstart
import winrm
import os
# Configure target details using environment variables for security/flexibility
target_host = os.environ.get('WINRM_HOST', 'localhost')
target_port = os.environ.get('WINRM_PORT', '5985') # 5985 for HTTP, 5986 for HTTPS
username = os.environ.get('WINRM_USERNAME', 'Administrator')
password = os.environ.get('WINRM_PASSWORD', 'Password123!') # Use a strong password!
# Establish a WinRM session
# For HTTPS, change the URL prefix to 'https' and consider 'verify_ssl_certs=False'
# if using self-signed certificates (use with caution in production).
session = winrm.Session(
f'http://{target_host}:{target_port}/wsman',
auth=(username, password)
)
# Execute a simple command
print(f"Running 'hostname' on {target_host}...")
result = session.run_cmd('hostname')
print(f"Stdout: {result.std_out.decode('utf-8').strip()}")
print(f"Stderr: {result.std_err.decode('utf-8').strip()}")
print(f"Exit Code: {result.status_code}")
# Execute a PowerShell command
print("\nRunning 'Get-Service' PowerShell command...")
ps_result = session.run_ps('Get-Service Spooler | Select-Object Name, Status')
print(f"Stdout: {ps_result.std_out.decode('utf-8').strip()}")
print(f"Stderr: {ps_result.std_err.decode('utf-8').strip()}")
print(f"Exit Code: {ps_result.status_code}")