代码之家  ›  专栏  ›  技术社区  ›  Ayush

如何将此扩展到远程计算机(获取windows服务)?

  •  0
  • Ayush  · 技术社区  · 15 年前

    我有以下代码,用于获取在某台计算机上运行的所有Windows服务。如果该计算机是我正在运行的计算机,则工作正常,但如果它是远程计算机,则会出现“拒绝访问”异常,因为我没有传入用户名/密码。

    static void Main(string[] args)
            {
                bool filter;
                string machineName = "mymachine";
                string objPath = String.Format("\\\\{0}\\root\\cimv2:Win32_Service",machineName);
    
                ManagementClass servicesMC = new ManagementClass(new ManagementPath(objPath));
                Dictionary<string, string> ServicesDict = new Dictionary<string, string>();
                List<string> Aggregate = new List<string>();
    
                foreach (ManagementObject service in servicesMC.GetInstances())
                {
                    //Console.WriteLine(service.GetPropertyValue("Name"));
                }
    
    1 回复  |  直到 15 年前
        1
  •  1
  •   Aamir    15 年前

    我没有运行此程序,因为我现在不在网络上,但这应该可以工作:

    ConnectionOptions theConnection = new ConnectionOptions();
    
    theConnection.Username = "username";
    theConnection.Password = "password";
    
    ManagementScope scope = new ManagementScope(objPath, theConnection);
    ManagementClass servicesMC = new ManagementClass(scope, new ManagementPath("Win32_Service"), new ObjectGetOptions());