2015-12-14 154 views
1
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); 

示出了是該消息:如何檢查特定進程是否在遠程PC /服務器上運行?

值不在所述預期範圍內。

+0

是憑據是否正確?爲什麼在'else'子句的構造函數中添加'null'作爲參數?根據https://msdn.microsoft.com/de-de/library/system.management.managementscope%28v=vs.110%29.aspx,您可以忽略它。另外,你能給出一個更詳細的堆棧跟蹤,它究竟在哪裏崩潰的內部函數? –

+0

它在Scope.Connect崩潰(我在代碼中評論它) –

回答

0

這很可能是由於憑據錯誤或權限不足。在你的情況沒有提供用戶名 - 我相當肯定你不能傳遞空的用戶名。用於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上登錄的用戶相同的憑據。

希望這會有所幫助。

編輯:另外按馬克西米利格哈特評論,跳過NULL這一行:

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