.net读取Windows登录用户信息(downmoon)

前天,在CodeProject看到一篇文章http://www.codeproject.com/KB/system/LSAEnumUserSessions.aspx

如何读取windows 当前登录用户的状态信息。

主要代码分享如下:

一:导入dll

ContractedBlock.gif ExpandedBlockStart.gif Code
ExpandedBlockStart.gifContractedBlock.gif /**//************************************************************************/
ExpandedBlockStart.gifContractedBlock.gif        
/**//* The following Interop code should be placed in a sealed internal NativeMethod class
InBlock.gif         * but has been left here to simplify the example.
ExpandedBlockEnd.gif        /***********************************************************************
*/

None.gif
None.gif        [DllImport(
"secur32.dll", SetLastError = false)]
None.gif        
private static extern uint LsaFreeReturnBuffer(IntPtr buffer);
None.gif
None.gif        [DllImport(
"Secur32.dll", SetLastError = false)]
None.gif        
private static extern uint LsaEnumerateLogonSessions(out UInt64 LogonSessionCount, out IntPtr LogonSessionList);
None.gif
None.gif        [DllImport(
"Secur32.dll", SetLastError = false)]
None.gif        
private static extern uint LsaGetLogonSessionData(IntPtr luid, out IntPtr ppLogonSessionData);
None.gif
None.gif        [StructLayout(LayoutKind.Sequential)]
None.gif        
private struct LSA_UNICODE_STRING
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            
public UInt16 Length;
InBlock.gif            
public UInt16 MaximumLength;
InBlock.gif            
public IntPtr buffer;
ExpandedBlockEnd.gif        }

None.gif
None.gif        [StructLayout(LayoutKind.Sequential)]
None.gif        
private struct LUID
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            
public UInt32 LowPart;
InBlock.gif            
public UInt32 HighPart;
ExpandedBlockEnd.gif        }

None.gif
None.gif        [StructLayout(LayoutKind.Sequential)]
None.gif        
private struct SECURITY_LOGON_SESSION_DATA
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            
public UInt32 Size;
InBlock.gif            
public LUID LoginID;
InBlock.gif            
public LSA_UNICODE_STRING Username;
InBlock.gif            
public LSA_UNICODE_STRING LoginDomain;
InBlock.gif            
public LSA_UNICODE_STRING AuthenticationPackage;
InBlock.gif            
public UInt32 LogonType;
InBlock.gif            
public UInt32 Session;
InBlock.gif            
public IntPtr PSiD;
InBlock.gif            
public UInt64 LoginTime;
InBlock.gif            
public LSA_UNICODE_STRING LogonServer;
InBlock.gif            
public LSA_UNICODE_STRING DnsDomainName;
InBlock.gif            
public LSA_UNICODE_STRING Upn;
ExpandedBlockEnd.gif        }

None.gif
None.gif        
private enum SECURITY_LOGON_TYPE : uint
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            Interactive 
= 2,    //The security principal is logging on interactively. 
InBlock.gif
            Network,            //The security principal is logging using a network. 
InBlock.gif
            Batch,              //The logon is for a batch process. 
InBlock.gif
            Service,            //The logon is for a service account. 
InBlock.gif
            Proxy,              //Not supported. 
InBlock.gif
            Unlock,             //The logon is an attempt to unlock a workstation.
InBlock.gif
            NetworkCleartext,   //The logon is a network logon with cleartext credentials.
InBlock.gif
            NewCredentials,     // Allows the caller to clone its current token and specify new credentials for outbound connections. The new logon session has the same local identity but uses different credentials for other network connections.
InBlock.gif
            RemoteInteractive,  // A terminal server session that is both remote and interactive.
InBlock.gif
            CachedInteractive, // Attempt to use the cached credentials without going out across the network.
InBlock.gif
            CachedRemoteInteractive, // Same as RemoteInteractive, except used internally for auditing purposes.
InBlock.gif
            CachedUnlock          // The logon is an attempt to unlock a workstation.
ExpandedBlockEnd.gif
        }

None.gif

 二、调用方法,写入一个ListBox中

ContractedBlock.gif ExpandedBlockStart.gif Code
None.gif public void PopulateListbox()
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            System.Security.Principal.WindowsIdentity currentUser 
= System.Security.Principal.WindowsIdentity.GetCurrent();
InBlock.gif
InBlock.gif            DateTime systime 
= new DateTime(1601110000); //win32 systemdate
InBlock.gif

InBlock.gif            UInt64 count;
InBlock.gif            IntPtr luidPtr 
= IntPtr.Zero;
InBlock.gif            LsaEnumerateLogonSessions(
out count, out luidPtr);  //gets an array of pointers to LUIDs
InBlock.gif

InBlock.gif            IntPtr iter 
= luidPtr;      //set the pointer to the start of the array
InBlock.gif

InBlock.gif            
for (ulong i = 0; i < count; i++)   //for each pointer in the array
ExpandedSubBlockStart.gifContractedSubBlock.gif
            dot.gif{
InBlock.gif                IntPtr sessionData;
InBlock.gif
InBlock.gif                LsaGetLogonSessionData(iter, 
out sessionData);
InBlock.gif                SECURITY_LOGON_SESSION_DATA data 
= (SECURITY_LOGON_SESSION_DATA)Marshal.PtrToStructure(sessionData, typeof(SECURITY_LOGON_SESSION_DATA));
InBlock.gif
InBlock.gif                
//if we have a valid logon
InBlock.gif
                if (data.PSiD != IntPtr.Zero)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
//get the security identifier for further use
InBlock.gif
                    System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(data.PSiD);
InBlock.gif               
InBlock.gif                    
//extract some useful information from the session data struct
InBlock.gif
                    string username = Marshal.PtrToStringUni(data.Username.buffer).Trim();          //get the account username
InBlock.gif
                    string domain =  Marshal.PtrToStringUni(data.LoginDomain.buffer).Trim();        //domain for this account  
InBlock.gif
                    string authpackage = Marshal.PtrToStringUni(data.AuthenticationPackage.buffer).Trim();    //authentication package
InBlock.gif
                
InBlock.gif                    SECURITY_LOGON_TYPE secType 
= (SECURITY_LOGON_TYPE)data.LogonType;
InBlock.gif                    DateTime time 
= systime.AddTicks((long)data.LoginTime);                              //get the datetime the session was logged in
InBlock.gif

InBlock.gif                    listBox1.Items.Add(
"User: " + username + " *** Domain: " + domain + " *** Login Type: (" + data.LogonType + "" + secType.ToString() +" *** Login Time: "+time.ToLocalTime().ToString());
InBlock.gif   
ExpandedSubBlockEnd.gif                }

InBlock.gif                iter 
= (IntPtr)((int)iter + Marshal.SizeOf(typeof(LUID)));  //move the pointer forward
InBlock.gif
                LsaFreeReturnBuffer(sessionData);   //free the SECURITY_LOGON_SESSION_DATA memory in the struct
ExpandedSubBlockEnd.gif
            }

InBlock.gif            LsaFreeReturnBuffer(luidPtr);   
//free the array of LUIDs
ExpandedBlockEnd.gif
        }

None.gif

 更多DirectoryEntry的信息,请查阅

http://msdn.microsoft.com/zh-cn/library/system.directoryservices.directoryentry_members.aspx

转载于:https://www.cnblogs.com/downmoon/archive/2008/12/30/1365248.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值