首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 實現遠程關機:WMI 連接與 Win32_OperatingSystem

     編輯:關於C語言

利用 System.Management 命名空間,通過 WMI 連接遠程主機並調用 Win32_OperatingSystem.Shutdown 方法實現遠程關機/重啟。

完整代碼

using System;
using System.Management;
using System.Windows.Forms;

namespace Ex18_11
{
    public partial class Form1 : Form
    {
        public Form1() { InitializeComponent(); }

        private void btnShutdown_Click(object sender, EventArgs e)
        {
            ConnectionOptions options = new ConnectionOptions
            {
                Username = "administrator",
                Password = "12345"
            };

            ManagementScope scope = new ManagementScope(
                @"\\121.35.174.154\root\cimv2", options);
            scope.Connect();

            ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            ManagementObjectCollection results = searcher.Get();

            foreach (ManagementObject obj in results)
            {
                obj.InvokeMethod("Shutdown", null); // "Reboot" 為重啟
            }
        }
    }
}

關鍵點

  • 需引用 System.Management.dll。
  • 目標機需開啟 WMI 服務、防火牆允許 135/445 端口、遠程用戶具備管理員權限。
  • 生產環境建議將憑證加密存儲,避免明文硬編碼。
  • 同理可調用 Win32_Process.Create 遠程啟動程序等。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved