繁体   English   中英

如何检查远程PC /服务器上是否正在运行特定进程?

[英]How can I check if a specific process is running on a remote PC/Server?

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);

出现的消息是:

值不在预期范围内。

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

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

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

我尝试了您的代码(在测试的最后四行添加了代码),发现了与您相同的错误。 添加用户名和密码后,一切运行正常。

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM