使用c#获取已使用远程计算机的用户的IP地址

时间:2019-07-19 12:48:08

标签: c# wmi remote-server

我正在使用c#控制台应用程序来获取使用了远程计算机的用户的详细信息。 从下面的代码中,我能够获得当前登录的用户名。

现在,我想获取使用远程计算机的用户的IP地址(源IP)。

有人有任何解决方法吗?谢谢。

class Program
    {
        static string serverName = "";
        static string username = "";
        static string password = "";

        static void Main(string[] args)
        {            
            try
            {
                   foreach (var user in GetLoggedUser(serverName))
                    {
                        Console.WriteLine( "Logged in username:  " + user);
                    }                   
              }
            catch (Exception ex)
            {

            }
        }

        private static List<string> GetLoggedUser(string machineName)
        {
            List<string> users = new List<string>();
            try
            {
                var scope = GetManagementScope(machineName);
                scope.Connect();
                var Query = new SelectQuery("SELECT LogonId  FROM Win32_LogonSession Where LogonType=10");
                var Searcher = new ManagementObjectSearcher(scope, Query);
                var regName = new Regex(@"(?<=Name="").*(?="")");

                foreach (ManagementObject WmiObject in Searcher.Get())
                {
                    foreach (ManagementObject LWmiObject in WmiObject.GetRelationships("Win32_LoggedOnUser"))
                    {
                        users.Add(regName.Match(LWmiObject["Antecedent"].ToString()).Value);
                    }
                }
            }
            catch (Exception ex)
            {
                users.Add(ex.Message);
            }

            return users;
        }

        private static ManagementScope GetManagementScope(string machineName)
        {
            ManagementScope Scope;

            if (machineName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
                Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", "."), GetConnectionOptions());
            else
            {
                Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", machineName), GetConnectionOptions());
            }
            return Scope;
        }

        private static ConnectionOptions GetConnectionOptions()
        {
            var connection = new ConnectionOptions
            {
                EnablePrivileges = true,
                Username = username,
                Password = password,
                Authentication = AuthenticationLevel.PacketPrivacy,
                Impersonation = ImpersonationLevel.Impersonate,
            };
            return connection;
        }

        }

0 个答案:

没有答案