Windows Management Instrumentation (WMI) Python Library

1.5.1 · maintenance · verified Sat Apr 11

The Python WMI module is a lightweight wrapper on top of the `pywin32` extensions, providing a more Python-friendly interface to Microsoft's Windows Management Instrumentation (WMI) API. It allows Python to query and manage various aspects of Windows systems, both locally and remotely, by abstracting the complexities of COM and WMI scripting. The latest version is 1.5.1, released in April 2020. The library is in maintenance mode with infrequent updates, as newer alternatives like `PyMI` and `windows-tools.wmi_queries` exist.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to the local WMI service, retrieve basic operating system information, list a few running processes, and find automatically starting services that are currently stopped. It includes a placeholder for remote connections, emphasizing the use of environment variables for credentials for security best practice, and basic error handling for common WMI issues.

import wmi
import os

# Connect to the local machine WMI service
# For remote connection, set WMI_USERNAME and WMI_PASSWORD environment variables:
# c = wmi.WMI(computer="remote_machine_ip", user=os.environ.get('WMI_USERNAME', ''), password=os.environ.get('WMI_PASSWORD', ''))

try:
    c = wmi.WMI()

    # Get information about the operating system
    for os_info in c.Win32_OperatingSystem():
        print(f"OS Name: {os_info.Caption}")
        print(f"Version: {os_info.Version}")
        print(f"Service Pack: {os_info.CSDVersion}")
        print(f"Architecture: {os_info.OSArchitecture}")
        print(f"Free Physical Memory: {int(os_info.FreePhysicalMemory) / (1024**2):.2f} GB")

    print("\n--- Listing Running Processes (top 5) ---")
    # Get information about running processes (top 5)
    for process in c.Win32_Process()[:5]:
        print(f"Process: {process.Name}, ID: {process.ProcessId}, Status: {process.Status}")

    print("\n--- Listing Stopped Services (Auto Start) ---")
    # Find and list automatically starting services that are currently stopped
    for s in c.Win32_Service(StartMode="Auto", State="Stopped"):
        print(f"Service: {s.Caption}, State: {s.State}")

except wmi.x_wmi as e:
    print(f"WMI Error: {e}")
    if "Access is denied" in str(e):
        print("Ensure the script is run with administrator privileges, or correct remote authentication.")
    elif "RPC server is unavailable" in str(e):
        print("Ensure the remote machine is reachable and the WMI service is running.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →