# Python中怎么遠程獲取Windows主機信息
## 引言
在IT運維、自動化管理或安全監控場景中,遠程獲取Windows主機信息是一項常見需求。Python憑借其豐富的庫生態和跨平臺特性,成為實現這一目標的理想工具。本文將詳細介紹5種主流方法,涵蓋從基礎到進階的完整解決方案。
---
## 方法一:使用WMI協議(pywin32庫)
### 原理說明
Windows Management Instrumentation (WMI) 是微軟提供的系統管理架構,支持通過COM接口查詢系統信息。
### 實現步驟
1. 安裝必要庫:
```bash
pip install pywin32
def get_system_info(host, username, password): try: conn = wmi.WMI( computer=host, user=username, password=password )
# 獲取操作系統信息
for os in conn.Win32_OperatingSystem():
print(f"OS Name: {os.Caption}")
print(f"Version: {os.Version}")
# 獲取CPU信息
for cpu in conn.Win32_Processor():
print(f"CPU: {cpu.Name}")
except Exception as e:
print(f"Error: {str(e)}")
# 使用示例 get_system_info(‘192.168.1.100’, ‘admin’, ‘password123’)
### 可獲取信息類型
- 硬件信息(CPU/內存/磁盤)
- 安裝的軟件列表
- 系統服務狀態
- 事件日志
- 進程列表
### 注意事項
- 需要管理員權限
- 防火墻需開放135和445端口
- 支持NTLM認證
---
## 方法二:PowerShell Remoting(pypsrp庫)
### 技術背景
基于WS-Management協議,是微軟推薦的遠程管理方案。
### 實現示例
```python
from pypsrp.powershell import PowerShell, RunspacePool
from pypsrp.wsman import WSMan
def get_remote_info():
wsman = WSMan(
server="192.168.1.100",
username="admin",
password="password123",
ssl=False
)
with RunspacePool(wsman) as pool:
ps = PowerShell(pool)
ps.add_script("""
Get-CimInstance Win32_ComputerSystem | Select-Object Name,TotalPhysicalMemory
Get-Process | Select-Object Name,CPU
""")
output = ps.invoke()
for line in output:
print(line)
get_remote_info()
Start-Service sshd
Set-Service -Name sshd -StartupType 'Automatic'
import paramiko
def ssh_get_info():
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(
hostname='192.168.1.100',
username='admin',
password='password123'
)
# 執行系統命令
stdin, stdout, stderr = client.exec_command('systeminfo')
print(stdout.read().decode())
finally:
client.close()
ssh_get_info()
| 命令 | 作用 |
|---|---|
systeminfo |
獲取系統摘要信息 |
wmic bios get serialnumber |
獲取BIOS序列號 |
netstat -ano |
查看網絡連接 |
# server.py
from flask import Flask, jsonify
import wmi
app = Flask(__name__)
@app.route('/systeminfo')
def system_info():
c = wmi.WMI()
return jsonify({
"memory": sum([int(x.Capacity) for x in c.Win32_PhysicalMemory()]),
"disks": [x.Caption for x in c.Win32_DiskDrive()]
})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
import requests
response = requests.get('http://192.168.1.100:5000/systeminfo')
print(response.json())
Enable-PSRemoting -Force
Set-Item WSMan:\localhost\Client\TrustedHosts *
import winrm
session = winrm.Session(
'192.168.1.100',
auth=('admin', 'password123')
)
result = session.run_ps('Get-Service | Where Status -eq "Running"')
print(result.std_out.decode())
認證安全:
網絡防護:
權限控制:
conn.Win32_Process.filter(name='chrome.exe')
# remote_monitor.py
import wmi
from datetime import datetime
class WindowsMonitor:
def __init__(self, host, user, pwd):
self.conn = wmi.WMI(
computer=host,
user=user,
password=pwd
)
def get_all_info(self):
return {
"timestamp": datetime.now().isoformat(),
"system": self._get_system_info(),
"performance": self._get_perf_data()
}
def _get_system_info(self):
"""獲取系統基礎信息"""
info = {}
os_info = self.conn.Win32_OperatingSystem()[0]
info.update({
"os_name": os_info.Caption,
"os_arch": os_info.OSArchitecture,
"last_boot": os_info.LastBootUpTime
})
return info
def _get_perf_data(self):
"""獲取性能數據"""
perf = {}
cpu = self.conn.Win32_Processor()[0]
perf.update({
"cpu_usage": cpu.LoadPercentage,
"memory_used": int(self.conn.Win32_OperatingSystem()[0].TotalVisibleMemorySize) -
int(self.conn.Win32_OperatingSystem()[0].FreePhysicalMemory)
})
return perf
# 使用示例
if __name__ == '__main__':
monitor = WindowsMonitor('192.168.1.100', 'admin', 'SecurePass123!')
print(monitor.get_all_info())
本文介紹了五種主流遠程獲取Windows主機信息的方法,每種方案各有優缺點:
| 方法 | 適用場景 | 復雜度 | 安全性 |
|---|---|---|---|
| WMI | 內網管理 | 中 | 高 |
| PowerShell | 復雜運維任務 | 高 | 高 |
| SSH | 跨平臺環境 | 低 | 中 |
| REST API | 互聯網環境 | 中 | 可定制 |
| WinRM | 新版本Windows | 中 | 高 |
實際選擇時,建議根據目標環境、安全要求和運維團隊的技術棧進行綜合考量。對于需要持續監控的場景,可考慮將這些方法封裝為定期執行的監控任務。 “`
文章總字數:約2400字
格式說明:
1. 使用Markdown語法
2. 包含代碼塊、表格、多級標題
3. 采用技術文檔的標準結構
4. 關鍵注意事項使用強調標識
5. 提供可直接運行的代碼示例
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。