开发者

Detecting user name from process ID

Ho can i get user account name, that ran the 开发者_高级运维process with specified id. Is there any api function for this?

I am using windows,c++.


There is not an API function that does this directly, however you can combine a few API calls to do this. Of course your program will need to satisfy any ACLs that are applied to the process that you are interested in examining.

First, given the process ID, you'll need to open a handle to the process. You can use OpenProcess for that, requesting the PROCESS_QUERY_INFORMATION access right.

Once you have that handle, you can call OpenProcessToken, requesting the TOKEN_QUERY access right.

Finally, you can then call GetTokenInformation, requesting the TokenUser information class, which will give you the user account of the token. This information is provided to you in the form of a SID. To convert the SID to the actual name of the account, you can call LookupAccountSid.

Don't forget to call CloseHandle on both the process handle and the token handle once you're finished with them.


And this is function using Aaron Klotz algorithm:

public static string GetProcessOwnerByID(int processId)
{
  IntPtr processHandle = IntPtr.Zero;
  IntPtr tokenHandle = IntPtr.Zero;
  try
  {
    processHandle = OpenProcess(PROCESS_QUERY_INFORMATION, false, processId);
    if (processHandle == IntPtr.Zero)
      return "NO ACCESS";

    OpenProcessToken(processHandle, TOKEN_QUERY, out tokenHandle);
    using (WindowsIdentity wi = new WindowsIdentity(tokenHandle))
    {
      string user = wi.Name;
      return user.Contains(@"\") ? user.Substring(user.IndexOf(@"\") + 1) : user;
    }
  }
  finally
  {
    if (tokenHandle != IntPtr.Zero) CloseHandle(tokenHandle);
    if (processHandle != IntPtr.Zero) CloseHandle(processHandle);
  }
}

Whole function (with constants) can be found on GitHub gist

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜