检索远程计算机上已登录的用户



我正在构建一个C#应用程序,用WMI和WQL查询来监控服务器和工作站的工作负载。我之所以使用WMI,是因为与powershell查询相比,它似乎更快。当我试图在远程机器上检索登录用户时,我的困难就开始了。我想我需要使用Win32_LoggedOnUser类。我尝试了以下查询:

@"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对象,这似乎表明——调试器似乎也确认了——我应该在返回的Win32_Account类上再次使用CimInstanceProperties["Name"].Value。但这根本不起作用。关于如何访问存储在CimInstanceProperity中的Win32_Account的CimInstanceProperties,有什么想法吗?我在相应的Windows参考页上找不到任何内容(https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-loggedonuser)也没有在我广泛的谷歌搜索中。

谢谢!

在将Antecedent-对象转换为字符串后,我最终使用ManagementObject类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;

考虑登录会话的替代方案是:

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.getConnectionConnectionsOption对象,具体取决于您各自的域和帐户数据

最新更新