7

リモートマシンにログインしているユーザーを取得する方法を探しています。彼らがローカルにログオンしているかリモートにログオンしているかを知りたいのですが、何よりも彼らのステータスを知らなければなりません。ネット上でVBで書かれた回答を見ましたが、c#で必要です。ここでmarkdmakの回答に示されているソリューションは良いスタートのように見えますが、VBであり、リモートセッションのみを検索します。私はこのコードを持っていますが、これは開始点になる可能性がありますが、LogonIdをユーザー名に結合して、そのステータスを確認したいと思います。

string fqdn = ""; // set!!!    
ConnectionOptions options = new ConnectionOptions();
options.EnablePrivileges = true;
// To connect to the remote computer using a different account, specify these values:
// these are needed in dev environment
options.Username = ConfigurationManager.AppSettings["KerberosImpersonationUser"];
options.Password = ConfigurationManager.AppSettings["KerberosImpersonationPassword"];
options.Authority = "ntlmdomain:" + ConfigurationManager.AppSettings["KerberosImpersonationDomain"];

ManagementScope scope = new ManagementScope("\\\\" + fqdn + "\\root\\CIMV2", options);
try
{
    scope.Connect();
}
catch (Exception ex)
{
    if (ex.Message.StartsWith("The RPC server is unavailable"))
    {
        // The Remote Procedure Call server is unavailable
        // cannot check for logged on users
        return false;
    }
    else
    {
        throw ex;
    }
}

SelectQuery query = new SelectQuery("Select * from Win32_LogonSession");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection results = searcher.Get();
bool returnVal = false;
foreach (ManagementObject os in results)
{
    try
    {
        if (os.GetPropertyValue("LogonId").ToString() != null && os.GetPropertyValue("LogonId").ToString() != "")
        {
            returnVal = true;
        }
    }
    catch (NullReferenceException)
    {
        continue;
    }
}
return returnVal;
}

私が本当に必要としているのは、リモートマシン上のすべてのユーザーとそのステータス(アクティブ、切断済み、ログオフなど)を取得する方法です。

4

2 に答える 2

7

値が 2 (インタラクティブ)Win32_LogonSessionのプロパティには、WMI クラス フィルタリングを使用できます。LogonType

このサンプルを試す

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();
    }
}
}
于 2013-01-09T02:12:36.063 に答える
4

@RRUZ のおかげで始められましたが、多くのオブジェクトAssociatorsがあるリモート マシンではクエリが機能しませんでした (理由はわかりません)。Win32_LoggedOnUser結果は返されませんでした。

リモート デスクトップ セッションも必要だったので、LogonType "10" セッションを使用しましたConnectionOptions

アソシエーターのクエリを次のように置き換えたところWmiObject.GetRelationships("Win32_LoggedOnUser")、速度が大幅に向上し、結果が得られました。

    private void btnUnleash_Click(object sender, EventArgs e)
    {
        string serverName = "serverName";
        foreach (var user in GetLoggedUser(serverName))
        {
            dataGridView1.Rows.Add(serverName, user);
        }            
    }   

    private 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,
            Authentication = AuthenticationLevel.PacketPrivacy,
            Impersonation = ImpersonationLevel.Impersonate,
        };
        return connection;
    }
于 2015-03-20T13:54:16.120 に答える