how to get logged on users with their status on remote machine

后端 未结 2 463
遥遥无期
遥遥无期 2020-12-19 05:28

I\'m looking for a way to get the users that are logged in on a remote machine. I would love to know if they are logged on localy or remotely, but most of all I MUST know th

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-19 06:18

    You can use the Win32_LogonSession WMI class filtering for the LogonType property with the value 2 (Interactive)

    Try this sample

    using System;
    using System.Collections.Generic;
    using System.Management;
    using System.Text;
    
    namespace GetWMI_Info
    {
    class Program
    {
    
        static void Main(string[] args)
        {
            try
            {
                string ComputerName = "remote-machine";
                ManagementScope Scope;
    
                if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
                {
                    ConnectionOptions Conn = new ConnectionOptions();
                    Conn.Username = "username";
                    Conn.Password = "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();
                ObjectQuery Query = new ObjectQuery("SELECT LogonId  FROM Win32_LogonSession Where LogonType=2");
                ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
    
                foreach (ManagementObject WmiObject in Searcher.Get())
                {
                    Console.WriteLine("{0,-35} {1,-40}", "LogonId", WmiObject["LogonId"]);// String
                    ObjectQuery LQuery = new ObjectQuery("Associators of {Win32_LogonSession.LogonId=" + WmiObject["LogonId"] + "} Where AssocClass=Win32_LoggedOnUser Role=Dependent");
                    ManagementObjectSearcher LSearcher = new ManagementObjectSearcher(Scope, LQuery);
                    foreach (ManagementObject LWmiObject in LSearcher.Get())
                    {
                        Console.WriteLine("{0,-35} {1,-40}", "Name", LWmiObject["Name"]);                    
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(String.Format("Exception {0} Trace {1}", e.Message, e.StackTrace));
            }
            Console.WriteLine("Press Enter to exit");
            Console.Read();
        }
    }
    }
    

提交回复
热议问题