核心原理
呼叫遠端電腦的 WMI 類別 Win32_OperatingSystem 的靜態方法 Win32Shutdown (或舊版 Shutdown/Reboot),需提供管理員帳密建立 `ManagementScope` 連線。
完整程式碼
using System;
using System.Management;
public class RemotePowerManager
{
///
/// 關機/重開機/登出/鎖定
///
/// 目標 IP 或主機名
/// 管理員帳號 (含域: domain\user 或 .\user)
/// 密碼
/// 0=登出, 1=關機, 2=重開機, 4=強制關機, 8=強制重開機, 16=關機並關閉電源
/// true 成功
public static bool Execute(string targetIp, string username, string password, uint action)
{
var options = new ConnectionOptions
{
Username = username,
Password = password,
Impersonation = ImpersonationLevel.Impersonate,
EnablePrivileges = true // 需 SeShutdownPrivilege
};
var scope = new ManagementScope($@"\\{targetIp}\root\cimv2", options);
try { scope.Connect(); }
catch (Exception ex)
{
Console.Error.WriteLine($"WMI 連線失敗: {ex.Message}");
return false;
}
var query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
using (var searcher = new ManagementObjectSearcher(scope, query))
using (var collection = searcher.Get())
{
foreach (ManagementObject os in collection)
{
var args = new object[] { action };
var result = os.InvokeMethod("Win32Shutdown", args);
uint ret = Convert.ToUInt32(result);
return ret == 0; // 0 成功
}
}
return false;
}
}
// 使用範例
class Program
{
static void Main()
{
string ip = "192.168.1.100";
string user = "Administrator";
string pwd = "P@ssw0rd";
Console.WriteLine("1. 關機 2. 重開機");
if (int.TryParse(Console.ReadLine(), out int choice))
{
uint action = choice == 1 ? 1u : 2u; // 1=關機, 2=重開機
bool ok = RemotePowerManager.Execute(ip, user, pwd, action);
Console.WriteLine(ok ? "指令送出成功" : "失敗:請檢查 IP/帳密/防火牆/WMI 服務");
}
}
}
關鍵設定與排錯
| 項目 | 設定/檢查 |
| 目標機器防火牆 | 開放 **WMI (TCP 135, 動態高連接埠)** 或預設規則「Windows Management Instrumentation (WMI-In)」 |
| 目標機器服務 | 啟動 **Windows Management Instrumentation** (Winmgmt) 服務 |
| 帳號權限 | 本機 Administrators 群組;非域環境需啟用 `LocalAccountTokenFilterPolicy` 登錄值 (參見下方) |
| UAC 遠端限制 | 非域環境:`reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f` 並重啟 |
| 網路類型 | 目標網路設為「私人/網域」,公用網路預設封鎖 WMI |
| DCOM 權限 | `dcomcnfg` → 元件服務 → 電腦 → 我的電腦 → 屬性 → COM 安全性 → 啟動及啟用權限 → 加入使用者允許「遠端啟動/啟用」 |
Win32Shutdown 動作代碼對照
| 代碼 | 動作 | 備註 |
| 0 | 登出 | |
| 1 | 關機 | |
| 2 | 重開機 | |
| 4 | 強制關機 | 不等待應用程式關閉 |
| 8 | 強制重開機 | |
| 16 | 關機並切斷電源 | 需硬體支援 |
可組合使用 (如 `1+4=5` 強制關機)。
替代方案比較
| 方法 | 優點 | 缺點 |
| WMI (Win32Shutdown) | 標準、支援遠端、可帶參數 | 需開放防火牆、DCOM 設定複雜 |
| PsExec / Sysinternals | 無需額外設定、單一 EXE | 需下載工具、殺毒軟體可能攔截 |
| SSH (PowerShell Core / OpenSSH) | 加密、跨平台、現代標準 | 目標需安裝 OpenSSH Server |
| Scheduled Tasks (schtasks) | 原生排程、可指定觸發 | 需建立/刪除任務、延遲較大 |
總結
WMI `Win32Shutdown` 是 Windows 原生遠端電源管理的標準方式。核心難點在於**目標機器防火牆、DCOM、UAC 遠端權限**的正確配置。建議內網環境優先評估 **SSH/PowerShell Remoting** 等現代加密協議;若必須用 WMI,請依表單逐項檢查設定,並善用 `wbemtest` 工具測試連線與方法呼叫。
- 上一篇文章: ASP.NET 檔案操作完整指南:上傳、下載、刪除、列表與安全實務
- 下一篇文章: C# 實作 SOCKS5 代理用戶端協議完整解析與程式碼
Copyright ©
程式碼之家 All Rights Reserved