How to get the current number of interactive user sessions in Windows?

I am writing a Windows service that needs to know if there are users on the computer who are currently logged in.

So far I have tried Win32_LogonSession(WMI) and LsaEnumerateLogonSessions/ LsaGetLogonSessionData(secur32.dll).

Both work and seem to return the same data, but they are too slow to update when the user logs out:

  • When the system starts up, they return "0 interactive users". (OK)
  • When I log in, they return "1 interactive user". (OK)
  • But then, when I log out, the number of users is saved to 1. After a new login, the number is 2, etc.

So Win32_LogonSession or LsaEnumerateLogonSessions are good enough. The service should know within 5 minutes after the last interactive user left.

Even SysInternals LogonSessions.exe does not respond to the most recent answers. In addition, the answer cannot be β€œtrack login and output events and have a counter variable”, because the service can be started at any time.

+3
source share
1 answer

As a result, I got the following approach: count the number of interactive sessions in which there is at least one process.

1) Get the login session ID for each interactive session.

  • LsaEnumerateLogonSessions (secur32.dll)
  • LsaGetLogonSessionData (secur32.dll)
  • sessionData.LogonType = SECURITY_LOGON_TYPE.Interactive sessionData.LogonType = SECURITY_LOGON_TYPE.RemoteInteractive
  • sessionData.LoginID < - LUID.
  • LsaFreeReturnBuffer (secur32.dll)

2) .

[ SeDebugPrivilege .]

  • GetCurrentProcess (kernel32.dll)
  • OpenProcessToken TOKEN_ADJUST_PRIVILEGES (advapi32.dll)
  • LookupPrivilegeValue SE_DEBUG_NAME (advapi32.dll)
  • AdjustTokenPrivileges (advapi32.dll)
  • CloseHandle (kernel32.dll)

[ .]

3)

interactiveSessionsCount = | { sessionData.LoginID } ∩ { accessTokenStatistics.AuthenticationId } |

Obs: sessionData.LoginID accessTokenStatistics.AuthenticationId LUID.

+8

All Articles