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.
pip install pywinrmVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to establish a WinRM session using environment variables for credentials and execute both a simple command-line command (`run_cmd`) and a PowerShell command (`run_ps`). It also shows how to access the standard output, standard error, and exit code from the command results.
Always use `import winrm` or `from winrm import Session`.
For development/testing, you can disable SSL verification by passing `verify_ssl_certs=False` to the `winrm.Session` constructor. In production, consider configuring proper certificate trust or using HTTP (port 5985) if appropriate for your security posture.
Always provide the full URL, e.g., `winrm.Session('http://<ip>:5985/wsman', ...)` instead of `winrm.Session(hostname='<ip>', port=5985, ...)`.For simple executable calls (e.g., `ipconfig`), `run_cmd` is fine. For any PowerShell cmdlets or scripts, `run_ps` is recommended. Be mindful of PowerShell's quoting rules (single vs. double quotes, backticks for escaping) when constructing complex commands.
pip install pywinrm
Ensure the WinRM service is running on the Windows host by checking `services.msc` or `Get-Service WinRM` in PowerShell, and verify that network and host firewalls allow inbound connections to the WinRM port.
Verify the username and password, confirm the authentication protocol is enabled on the remote Windows machine (e.g., `winrm set winrm/config/service/auth @{Basic="true"}` for Basic auth), and ensure the user has permissions for remote operations.For untrusted or self-signed certificates in non-production environments, initialize the protocol with `ssl_verify_mode='ignore'`. For production, ensure a valid, trusted certificate is installed on the server or provide the correct CA certificate chain.