【问题标题】:How can I check if a specific process is running on a remote PC/Server?如何检查远程 PC/服务器上是否正在运行特定进程?
【发布时间】:2015-12-14 16:26:11
【问题描述】:
string ComputerName = serverName;
ManagementScope Scope;

if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
{
    ConnectionOptions Conn = new ConnectionOptions();
    Conn.Username = "";
    Conn.Password = "";
    Conn.Authority = "ntlmdomain:DOMAIN";
    Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), Conn);
}
else
    Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);

Scope.Connect(); // CRASH HERE
ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_Process Where Name='" + processName + "'");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);

显示的消息是:

值不在预期范围内。

【问题讨论】:

  • 凭据是否正确?为什么要在else子句的构造函数中添加null作为参数?根据msdn.microsoft.com/de-de/library/… ,您可以忽略它。另外,您能否提供更详细的堆栈跟踪,它究竟在内部函数的哪个位置崩溃?
  • 它在 Scope.Connect 崩溃(我在代码中对其进行了注释)

标签: c# wmi wmi-query


【解决方案1】:

这很可能与错误的凭据或权限不足有关。在您的情况下,没有提供用户名 - 我很确定您不能传递空的用户名。您用于 WMI 查询的用户名/密码必须存在于远程 PC 上(加上用户必须具有足够的权限)。

如果您想使用与您在本地 PC(运行代码)上登录时相同的用户名/密码,您应该省略整个 ConnectionOptions 部分:

    //ConnectionOptions Conn = new ConnectionOptions();
    //Conn.Username = "";
    //Conn.Password = "";
    //Conn.Authority = "ntlmdomain:DOMAIN";

我尝试了您的代码(添加了最后 4 行以进行测试),它出现了与您相同的错误。添加用户名和密码后,一切正常。

string ComputerName = "10.1.2.3";
ManagementScope Scope;

if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
{
    ConnectionOptions Conn = new ConnectionOptions();
    Conn.Username = "Administrator";
    Conn.Password = "pass123";
    //Conn.Authority = "ntlmdomain:DOMAIN";
    Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), Conn);
}
else
    Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);

Scope.Connect(); // CRASH HERE
ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_Process Where Name='" + "cmd.exe" + "'");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);

ManagementObjectCollection queryCollection = Searcher.Get();

foreach (var item in queryCollection)
    Console.WriteLine(item["Description"]);

Console.Read();

我还尝试了相同的代码,将有关 ConnectionOptions 的部分注释掉了,它也可以工作。但是请注意,根据我之前写的内容,我必须在远程 PC 上创建一个用户,该用户与我在本地 PC 上登录的用户具有相同的凭据。

希望这会有所帮助。

编辑:同样根据 Maximilian Gerhardt 的评论,跳过 NULL 这一行:

Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);

【讨论】:

    最近更新 更多