How to query a user's session id under Windows?

xmllmx picture xmllmx · Dec 26, 2012 · Viewed 8.2k times · Source

Provided that there are two users, named A and B, logged on the computer, we can use command "query session" in cmd.exe to get all session ids for each user name.

My questions are as follows:

1, How can I query the session id of a given user name through API (user mode or kernel mode)?

2, How can I query the user name of a given session id through API (user mode or kernel mode)?

Thanks in advance!

Answer

Nikolay Khil picture Nikolay Khil · Dec 26, 2012

You can use Remote Desktop Services API for this.

1, How can I query the session id of a given user name through API (user mode or kernel mode)?

Simply get all the sessions using WTSEnumerateSessions, iterate through them, get the user name with WTSQuerySessionInformation and check if it matches or not.

Or, if you have an access token for that user, you can use GetTokenInformation to retrieve the session ID for it.

2, How can I query the user name of a given session id through API (user mode or kernel mode)?

as you might guess from the previous answer, you can use WTSQuerySessionInformation to get the user name from session ID.