萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 透過 SSH 呼叫 PowerShell 監控 Windows:自動化採集 CPU、記憶體、磁碟、網路與程序資訊

Windows 原生缺乏 SSH 服務,但安裝 PowerShell(Win7/2008 內建)後,可透過 SSH 執行 PowerShell 指令獲取豐富系統資訊。本文封裝 ssh_win32 類別,使用 pexpect 驅動 SSH 連線,自動解析 Get-WmiObject、ps、netstat 等指令輸出為 Python 物件。

核心類別架構

class ssh_win32:
    def __init__(self, user, host, password=None, systemroot='c',
                 papath='', timeout=5, verbose=0):
        self.user = user
        self.host = host
        self.password = password
        self.timeout = timeout
        self.systemroot = systemroot
        self.powershell_path = (papath or
            f"{systemroot}:/WINDOWS/system32/WindowsPowerShell/v1.0/powershell.exe ")
        self.key = ['authenticity', 'assword:', '@@@@@@@@@@@@',
                    'Command not found.', EOF]
        self.f = open('ssh.out', 'w')

    def ssh(self, command):
        cmd = f'ssh -l {self.user} {self.host} {command}'
        con = spawn(cmd, timeout=self.timeout)
        seen = con.expect(self.key)
        if seen == 0: con.sendline('yes'); seen = con.expect(self.key)
        if seen == 1: con.sendline(self.password)
        try: return con.read()
        except: return con.before

主要監控方法

方法PowerShell 指令回傳結構
ssh_disk()Get-WmiObject win32_logicaldisk{'C:'{'FreeSpace':10.5,'Size':100,'DriveType':'3'}}
ssh_cpu()gwmi win32_Processor{'Name':'Intel...','NumberOfCores':4,...}
ssh_memory()Get-WmiObject win32_OperatingSystem TotalVisibleMemorySize/FreePhysicalMemory{'TotalVisibleMemorySize':'8388608','FreePhysicalMemory':'2097152'}
ssh_ping(host)ping -n 1 host布林值

解析邏輯精華

  • 輸出以 No such file or directory 分割,取後段
  • Key: Value 格式按冒號分割,strip() 去除空白
  • 磁碟大小換算:bytes / 1024^3 → GB
  • 過濾 DriveType != '3'(非固定磁碟)

使用範例

monitor = ssh_win32('admin', '192.168.1.100', 'password')
print(monitor.ssh_disk())
print(monitor.ssh_cpu())
print(monitor.ssh_memory())
print(monitor.ssh_ping('google.com'))

部署前提

  • 目標 Windows 已啟用 OpenSSH Server(Win10 1809+ 內建,或安裝 Win32-OpenSSH)
  • 防火牆開放 22 埠
  • PowerShell 執行原則允許腳本:Set-ExecutionPolicy RemoteSigned
  • Python 端需安裝 pexpect(Windows 建議用 wexpect 分支)
copyright © 萬盛學電腦網 all rights reserved