且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从会话ID中查找用户名?

更新时间:2023-11-27 23:13:58

为什么要在拥有进程ID时使用会话ID?使用它来获取用户名。



使用 ProcessIdToSessionId 返回的进程ID可能无法正常工作在我之前的回答中使用会话打印所有流程的C ++代码ID [ ^ ]:

引用:

备注

如果调用进程未在终端服务环境中运行,则pSessionId中返回的值为零

以上内容来自旧版SDK,适用于最高版本为XP的Windows版本。假设您没有在终端服务中执行XP应用程序,会话ID将始终为零。



要从进程ID获取名称,请参阅这些函数(或者搜索网络,例如代码):

OpenProcessToken函数(Windows) [ ^ ]

GetTokenInformation function(Windows) [ ^ ](类 TokenOwner 获取用户的 SID

LookupAccountSid函数(Windows) [ ^ ]


I have an user win32 application . That enumerates all the process details along with ProcessId. I need to print the User name along with the session ID. SessionID is enumerated using ProcessIdToSessionId() method. I want to print the User name of corresponding SessionID. This application is specially designed for WindowsXP , so the API should support WindowsXP. If anyone knows the solution please share it.

What I have tried:

DWORD dwSessionId,dwPid,dwErr;
char* Uname;
ProcessIdToSessionId(dwPid,&dwSessionId);

Why would you want to use the Session ID when you have the Process ID? Use that to get the user name.

Using the process ID returned by ProcessIdToSessionId might not work as already mentioned in my previous answer C++ code to print all process with session ID[^]:
Quote:

Remarks
If the calling process is not running in a Terminal Services environment, the value returned in pSessionId is zero

The above is from an old SDK and applies to Windows versions up to XP. Assuming that you are not executing your XP application in a Terminal Service, the Session ID will be always zero.

To get the name from the Process ID see these functions (or serach the web for example code):
OpenProcessToken function (Windows)[^]
GetTokenInformation function (Windows)[^] (with class TokenOwner to get the user's SID)
LookupAccountSid function (Windows)[^]