(.Net)使用WMI远程控制windows服务(转载)

最近碰到需要利用WMI来远程控制机器的windows服务的问题(拒绝访问),google一下天行健给出了大部分代码,看上去还挺不错的。
using System;
using System.Management;
namespace ZZ.Wmi
{
     public class Win32ServiceManager
     {
         private string strPath;
         private ManagementClass managementClass;
         public Win32ServiceManager():this(".",null,null)
         {
         }
         public Win32ServiceManager(string host,string userName,string password)
         {
              this.strPath = "\\\\"+host+"\\root\\cimv2:Win32_Service";
              this.managementClass = new ManagementClass(strPath);
               if(userName!=null&&userName.Length>0)
              {
                   ConnectionOptions connectionOptions = new ConnectionOptions();
                   connectionOptions.Username = userName;
                   connectionOptions.Password = password;
                   ManagementScope managementScope = new ManagementScope( "\\\\" +host+ "\\root\\cimv2",connectionOptions) ;
                   this.managementClass.Scope = managementScope;
              }
         }
         // 验证是否能连接到远程计算机
         public static bool RemoteConnectValidate(string host,string userName,string password)
         {
              ConnectionOptions connectionOptions = new ConnectionOptions();
              connectionOptions.Username = userName;
              connectionOptions.Password = password;
              ManagementScope managementScope = new ManagementScope( "\\\\" +host+ "\\root\\cimv2",connectionOptions) ;
              try
              {
                   managementScope.Connect();
              }
              catch
              {
              }
              return managementScope.IsConnected;
         }
         // 获取指定服务属性的值
         public object GetServiceValue(string serviceName,string propertyName)
         {
              ManagementObject mo = this.managementClass.CreateInstance();
              mo.Path = new ManagementPath(this.strPath+".Name=\""+serviceName+"\"");
              return mo[propertyName];
         }
         // 获取所连接的计算机的所有服务数据
         public string [,] GetServiceList()
         {
              string [,] services = new string [this.managementClass.GetInstances().Count,4];
              int i = 0;
              foreach(ManagementObject mo in this.managementClass.GetInstances())
              {
                   services[i,0] = (string)mo["Name"];
                   services[i,1] = (string)mo["DisplayName"];
                   services[i,2] = (string)mo["State"];
                   services[i,3] = (string)mo["StartMode"];
                   i++;
              }
              return services;
         }
         // 获取所连接的计算机的指定服务数据
         public string [,] GetServiceList(string serverName)
         {
              return GetServiceList(new string []{serverName});
         }
         // 获取所连接的计算机的的指定服务数据
         public string [,] GetServiceList(string [] serverNames)
         {
              string [,] services = new string [serverNames.Length,4];
              ManagementObject mo = this.managementClass.CreateInstance();
              for(int i = 0;i<serverNames.Length;i++)
              {
                   mo.Path = new ManagementPath(this.strPath+".Name=\""+serverNames[i]+"\"");
                   services[i,0] = (string)mo["Name"];
                   services[i,1] = (string)mo["DisplayName"];
                   services[i,2] = (string)mo["State"];
                   services[i,3] = (string)mo["StartMode"];
              }
              return services;
         }
         // 停止指定的服务
         public string StartService(string serviceName)
         {
              string strRst = null;
              ManagementObject mo = this.managementClass.CreateInstance();
              mo.Path = new ManagementPath(this.strPath+".Name=\""+serviceName+"\"");
              try
              {
                   if((string)mo["State"]=="Stopped")//!(bool)mo["AcceptStop"]
                       mo.InvokeMethod("StartService",null);
              }
              catch(ManagementException e)
              {
                   strRst =e.Message;
              }
              return strRst;
         }
         // 暂停指定的服务
         public string PauseService(string serviceName)
         {
              string strRst = null;
              ManagementObject mo = this.managementClass.CreateInstance();
              mo.Path = new ManagementPath(this.strPath+".Name=\""+serviceName+"\"");
              try
              {
                   //判断是否可以暂停
                   if((bool)mo["acceptPause"]&&(string)mo["State"]=="Running")
                       mo.InvokeMethod("PauseService",null);
              }
              catch(ManagementException e)
              {
                   strRst =e.Message;
              }
              return strRst;
         }
         // 恢复指定的服务
         public string ResumeService(string serviceName)
         {
              string strRst = null;
              ManagementObject mo = this.managementClass.CreateInstance();
              mo.Path = new ManagementPath(this.strPath+".Name=\""+serviceName+"\"");
              try
              {
                   //判断是否可以恢复
                   if((bool)mo["acceptPause"]&&(string)mo["State"]=="Paused")
                       mo.InvokeMethod("ResumeService",null);
              }
              catch(ManagementException e)
              {
                   strRst =e.Message;
              }
              return strRst;
         }
         // 停止指定的服务
         public string StopService(string serviceName)
         {
              string strRst = null;
              ManagementObject mo = this.managementClass.CreateInstance();
              mo.Path = new ManagementPath(this.strPath+".Name=\""+serviceName+"\"");
              try
              {
                   //判断是否可以停止
                   if((bool)mo["AcceptStop"])//(string)mo["State"]=="Running"
                       mo.InvokeMethod("StopService",null);
              }
              catch(ManagementException e)
              {
                   strRst =e.Message;
              }
              return strRst;
         }
    }
}

在使用的过程中还碰到一个小问题就是利用listview控件显示多列信息时候,用add方法加入一条记录却首尾右移了一列。最后用insert方法才解决的。回到正题,使用WMI在本机测试的时候其实并不需要用户名和密码最好就是注释掉相关语句(web的时候则考虑使用webconfig中的impersonate进行模拟windows登陆,假如远程控制的话则需要密码,另外还得开启WMI和RPC服务(远程或本机时候均要满足此条件),至于账号我使用的是administrator用户组的用户名,可能如果是其他组的用户则需要考虑右键我的电脑/管理/展开服务和应用程序/右键WMI/属性/安全页签/选择CIMV2目录/点击安全设置加入相关账号,下面的就很简单了。
在搜索过程中某个人坚定的说局域网内肯定不可能进行的,但是事实胜于毫无依据的判断,也有人说和需要connectionoptions中的domain属性需要设置下,但是在我的实际测试中(没有域)并没有需要这个属性的地方。
希望我的文章能帮助遇到类似问题的同志。

参考文章:天行健转帖的c#控制远程计算机服务 http://www.cnblogs.com/waxic/archive/2007/04/24/725419.html
原文地址:https://www.cnblogs.com/liubaolongcool/p/2059563.html