[英]Retrieve LoggedOnUsers on Remote Machine
我正在構建一個 C# 應用程序以使用 WMI 和 WQL 查詢監視服務器和工作站工作負載。 我正在使用 WMI,因為與 powershell 查詢相比,它似乎更快。 當我嘗試檢索遠程計算機上的登錄用戶時,我的困難就開始了。 我想我需要使用Win32_LoggedOnUser class。我嘗試了以下查詢:
@"SELECT * FROM Win32_LoggedOnUser"
@"SELECT Antecedent FROM Win32_LoggedOnUser"
我習慣於像這樣檢索所需的值:
var cims = connection.getCimInstances(this, queryUser);
if (cims != null)
{
foreach (CimInstance cim in cims)
{
Komponenten.User user = new Komponenten.User();
user.Name = Convert.ToString(cim.CimInstanceProperties["Name"].Value);
users.Add(user);
}
}
其中queryUser是上面的字符串之一。
在這兩種情況下,我都得到一個Win32_Account object 作為回報,這似乎表明 - 並且調試器似乎確認 - 我應該在返回的Win32_Account
class 上再次使用CimInstanceProperties["Name"].Value
。 但這根本不起作用。 關於如何訪問存儲在 CimInstanceProperity 中的 Win32_Account 的 CimInstanceProperties 的任何想法? 我在相應的 Windows 參考頁 ( https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-loggedonuser ) 或我廣泛的谷歌搜索中找不到任何內容。
謝謝!
在將Antecedent - Object 轉換為字符串后,我最終使用ManagementObject-Class和Regex查找用戶名:
var users = new List<Komponenten.User>();
var searcher = this.connection.makeQuery(this, "SELECT * FROM Win32_LoggedOnUser");
if (searcher != null)
{
foreach (ManagementObject queryObj in searcher.Get())
{
Komponenten.User user = new Komponenten.User();
var win32_account = queryObj["Antecedent"].ToString();
string stripped = Regex.Replace(win32_account, "[^a-zA-Z=]+", "", RegexOptions.Compiled);
int end = stripped.LastIndexOf("=");
user.Name = stripped.Substring(end+1);
users.Add(user);
}
this.users = users;
考慮到LogonSession的替代方法是:
var users = new List<Komponenten.User>();
var searcher = this.connection.makeQuery(this, "SELECT LogonId FROM Win32_LogonSession Where LogonType=2");
var Scope = this.connection.getScope(this, this.connection.getConnection());
if (searcher != null)
{
foreach (ManagementObject queryObj in searcher.Get())
{
ObjectQuery LQuery = new ObjectQuery("Associators of {Win32_LogonSession.LogonId=" + queryObj["LogonId"] + "} Where AssocClass=Win32_LoggedOnUser Role=Dependent");
ManagementObjectSearcher LSearcher = new ManagementObjectSearcher(Scope, LQuery);
foreach (ManagementObject LWmiObject in LSearcher.Get())
{
Komponenten.User user = new Komponenten.User();
user.Name = Convert.ToString(LWmiObject["Name"]);
users.Add(user);
}
}
this.users = users;
}
其中this.connection.getConnection是ConnectionsOption object,具體取決於您各自的域和帳戶數據
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.