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 → GBDriveType != '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'))
Set-ExecutionPolicy RemoteSignedpexpect(Windows 建議用 wexpect 分支)