pywinrm: Python Library for Windows Remote Management

0.5.0 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

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.

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}")

view raw JSON →