在Windows中查询用户会话

时间:2014-12-17 13:57:58

标签: c# .net

有一个内置工具:query.exe,可让您查看Windows中的所有活动用户和会话。

它的输出如下:

PS C:\> query.exe user
 USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME
>testusr               console             1  Active      none   12/16/2014 9:29 AM

现在我的代码只解析query.exe输出,但我们有些人担心未来的操作系统升级可能会改变查询的输出,所以我们正在寻找能够查询的API调用改为使用。

无论如何.Net方式收集相同的信息?

对于替代方案,我们不需要所有字段,但我们需要:用户名,状态和登录时间。我们还需要从System上下文运行此代码,因此任何需要用户上下文的代码或WMI类都不会为我们工作。

3 个答案:

答案 0 :(得分:2)

我所发现的并且我认为对你有用的是Cassia项目。

主页中几乎准备好了你的例子:

ITerminalServicesManager manager = new TerminalServicesManager();
using (ITerminalServer server = manager.GetLocalServer())
{
    server.Open();
    foreach (ITerminalServicesSession session in server.GetSessions())
    {
        Console.WriteLine("Hi there, " + session.UserAccount + " on session " + session.SessionId);
        Console.WriteLine("It looks like you logged on at " + session.LoginTime +
                          " and are now " + session.ConnectionState);
    }
}

正如您所看到的,当您获得TerminalServicesSession时,您会找到UserName,LoginTime和ConnectionState

希望这会对你有所帮助。

答案 1 :(得分:2)

您可以使用WMI简单地获取上次登录时间:

using System;
using System.Management;
using System.Windows.Forms;

namespace WMISample
{
    public class MyWMIQuery
    {
        public static void Main()
        {
            try
            {
                ManagementObjectSearcher searcher = 
                    new ManagementObjectSearcher("root\\CIMV2", 
                    "SELECT * FROM Win32_LogonSession"); 

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine("Win32_LogonSession instance");
                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine("Last Logon: {0}", queryObj["StartTime"]);
                }
            }
            catch (ManagementException e)
            {
                MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
            }
        }
    }
}

答案 2 :(得分:1)

听起来像你想要NetWkstaUserEnum。我找不到本机的.NET版本,但它似乎是一个相当轻松的互操作。