0

I have the following code to get the username associated with a session id:

ppBuffer = ctypes.c_wchar_p()
pBytesReturned = ctypes.c_ulong()
ctypes.windll.wtsapi32.WTSQuerySessionInformationW(0, SessionId, 5, ctypes.byref(ppBuffer), ctypes.byref(pBytesReturned))
logging.info(f'Username: {ppBuffer.value}')

I am having issues trying to enumerate through "WTSEnumerateSessionsW" to get an array of SessionId's and State's

I have gotten as far as:

class WTS_SESSION_INFOW(ctypes.Structure):
 _fields_ = [("SessionId", ctypes.c_ulong),
 ("pWinStationName", ctypes.c_wchar_p),
 ("State", ctypes.c_int)]
ppSessionInfo = WTS_SESSION_INFOW()
pCount = ctypes.c_ulong()
ctypes.windll.wtsapi32.WTSEnumerateSessionsW(0, 0, 1, ctypes.byref(ppSessionInfo), ctypes.byref(pCount))

pCount.value returns the correct number of instances running, however ppSessionInfo.SessionId returns a single large integer that does not match any current session id.

The MS documentation says ppSessionInfo should be an array of WTS_SESSION_INFOW structures, however I am not sure how to accomplish this?

I am able to accomplish the above using win32ts.WTSEnumerateSessions() and win32ts.WTSQuerySessionInformation() however I am limited to what imports are available to me.

Any help would be appreciated.

asked May 9, 2020 at 3:51

1 Answer 1

0

With the help from this post: python ctypes, pass double pointer by reference I was able to resolve my issue.

Here is the solution:

ppSessionInfo = ctypes.POINTER(WTS_SESSION_INFOW)()
pCount = ctypes.c_ulong()
ctypes.windll.wtsapi32.WTSEnumerateSessionsW(0, 0, 1, ctypes.byref(ppSessionInfo), ctypes.byref(pCount))
for index in range(pCount.value):
 ppSessionInfo[index].SessionId
 ppSessionInfo[index].State
 ppSessionInfo[index].pWinStationName

Writing out the problem helped me think of better ways to search for what I needed to accomplish.

answered May 9, 2020 at 5:36
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.