杰瑞科技汇

Python如何用wmi模块实现系统监控?

Of course! The pythonwmi library is a powerful and popular Python wrapper for the Windows Management Instrumentation (WMI) service. It allows you to query and manage virtually every aspect of a Windows system directly from a Python script.

Python如何用wmi模块实现系统监控?-图1
(图片来源网络,侵删)

Here's a comprehensive guide covering what it is, how to install it, and how to use it with plenty of examples.


What is WMI?

  • WMI (Windows Management Instrumentation) is a core Windows management technology. It's a set of extensions to the Windows Driver Model (WDM) that provides an operating system interface for instrumenting resources.
  • In simple terms, it's a way for scripts and applications to get information about the computer's hardware, software, and services, and even control them.
  • Think of it as a universal remote control for Windows. You can use it to check CPU usage, list installed programs, get hard drive information, monitor network connections, and much more.

Installation

First, you need to install the wmi library. Since it's not part of the standard Python library, you'll use pip.

pip install wmi

Important Prerequisite: This library relies on the underlying WMI COM object, which is a native part of Windows. This library will only work on a Windows machine. It will not run on macOS or Linux.


Basic Usage: Connecting to WMI

The first step in any script is to create a connection to the WMI service on the local machine.

Python如何用wmi模块实现系统监控?-图2
(图片来源网络,侵删)
import wmi
# Create a connection to the WMI service on the local machine
c = wmi.WMI()
# You can also connect to a remote machine (requires admin rights and proper DCOM settings)
# c = wmi.WMI('remote_machine_name_or_ip')

Common Examples

The core of using the library is to query WMI "classes." A class represents a type of object, like a Win32_Process (a running process) or Win32_LogicalDisk (a hard drive or partition).

Example 1: Get System Information (OS, Manufacturer, etc.)

You can query the Win32_ComputerSystem class.

import wmi
c = wmi.WMI()
# Query for the computer system information
system_info = c.Win32_ComputerSystem()[0]
print("--- System Information ---")
print(f"Manufacturer: {system_info.Manufacturer}")
print(f"Model: {system_info.Model}")
print(f"Name: {system_info.Name}")
print(f"Total Physical Memory: {int(system_info.TotalPhysicalMemory / (1024**3))} GB")
print(f"Domain: {system_info.Domain}")

Example 2: List Running Processes

Query the Win32_Process class. It returns a list of all running processes.

import wmi
import time
c = wmi.WMI()
print("--- Running Processes ---")
# We limit to the first 10 for brevity
for process in c.Win32_Process()[:10]:
    print(f"PID: {process.ProcessId} | Name: {process.Name}")

Example 3: Get CPU Information and Usage

Query the Win32_Processor class for static info and Win32_PerfFormattedData_PerfProc_Process for current usage.

Python如何用wmi模块实现系统监控?-图3
(图片来源网络,侵删)
import wmi
c = wmi.WMI()
# Get CPU static information
cpu_info = c.Win32_Processor()[0]
print("--- CPU Information ---")
print(f"Name: {cpu_info.Name}")
print(f"Number of Cores: {cpu_info.NumberOfCores}")
print(f"Logical Processors: {cpu_info.NumberOfLogicalProcessors}")
# Get current CPU load
# The '_Total' instance gives the overall CPU usage
cpu_load = c.Win32_PerfFormattedData_PerfProc_Process(Name="_Total")[0]
print(f"\nCurrent CPU Usage: {cpu_load.PercentProcessorTime}%")

Example 4: Get Disk Information (Drives, Space, etc.)

Query the Win32_LogicalDisk class. Filtering for DriveType=3 gets you fixed hard disks.

import wmi
c = wmi.WMI()
print("--- Disk Information ---")
for disk in c.Win32_LogicalDisk(DriveType=3): # DriveType=3 means Fixed Disk
    print(f"Drive: {disk.DeviceID}")
    # Size is in bytes, convert to GB
    size_gb = int(int(disk.Size) / (1024**3))
    free_gb = int(int(disk.FreeSpace) / (1024**3))
    print(f"  Size: {size_gb} GB")
    print(f"  Free Space: {free_gb} GB")
    print(f"  File System: {disk.FileSystem}")

Example 5: List Installed Software

Query the Win32_Product class. Note: This can be slow on systems with many programs, as it triggers a self-repair check for each product.

import wmi
c = wmi.WMI()
print("--- Installed Software (first 10) ---")
# This can be slow, so we limit the output
for software in c.Win32_Product()[:10]:
    print(f"- {software.Name} (Version: {software.Version})")

Example 6: Monitor Network Connections

Query the Win32_NetworkConnection class to see active network shares.

import wmi
c = wmi.WMI()
print("--- Network Connections ---")
for connection in c.Win32_NetworkConnection():
    if connection.ConnectionState == 'Connected': # Only show connected ones
        print(f"Local Name: {connection.LocalName}")
        print(f"Remote Name: {connection.RemoteName}")
        print(f"Status: {connection.ConnectionState}")
        print("-" * 20)

Advanced Features

Handling Queries

The c.Win32_...() syntax is a shortcut for a WQL (WMI Query Language) query. You can write more specific queries for better performance.

import wmi
c = wmi.WMI()
# Get only processes named 'chrome.exe'
chrome_processes = c.query("SELECT * FROM Win32_Process WHERE Name='chrome.exe'")
print(f"Found {len(chrome_processes)} Chrome processes.")
for process in chrome_processes:
    print(f"  - PID: {process.ProcessId}")

Executing Methods

Some WMI classes have methods that you can execute. For example, you can create a new process.

import wmi
c = wmi.WMI()
print("--- Creating a new Notepad process ---)
# The 'win32_process' class has a 'create' method
# It returns a result code (0 is success)
result = c.Win32_Process.Create(
    Commandline="notepad.exe",
    CurrentDirectory="C:\\"
)
if result[0] == 0:
    print(f"Successfully created process with PID: {result[1]}")
else:
    print(f"Failed to create process. Error code: {result[0]}")

Important Considerations

  • Permissions: Your Python script needs to be run with sufficient permissions to access certain WMI information. Running the script as an Administrator is often required for system-wide or remote queries.
  • Performance: WMI is powerful but can be slow, especially for queries that return a lot of data (like Win32_Product or Win32_Process without filters). Be mindful of the queries you run in performance-critical applications.
  • Error Handling: Always wrap your WMI calls in try...except blocks. WMI queries can fail for many reasons (e.g., class not found, permissions denied, remote machine unavailable).
import wmi
try:
    c = wmi.WMI()
    os_info = c.Win32_OperatingSystem()[0]
    print(f"OS Version: {os_info.Caption} {os_info.BuildNumber}")
except wmi.x_wmi as e:
    print(f"WMI Error: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

Summary

The pythonwmi library is an indispensable tool for any Windows system administrator, developer, or power user working in Python. It provides a straightforward and consistent interface to the immense power of the WMI subsystem, making system automation, monitoring, and management tasks significantly easier.

分享:
扫描分享到社交APP
上一篇
下一篇