取得 WinNT/2000 下的用户名

取得 WinNT/2000 下的用户名

 

// 取得当前用户的 Token
HANDLE hToken = NULL;
OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken);

// 获取 Token Information
DWORD dwReturned = 0;
GetTokenInformation(hToken, TokenOwner, NULL, 0, &dwReturned);

LPVOID pvOwner = new BYTE[dwReturned];
GetTokenInformation(hToken, TokenOwner, pvOwner, dwReturned, &dwReturned);

PTOKEN_OWNER pTokenOwner = (PTOKEN_OWNER)pvOwner;

// 查找 Token 对应的用户名
SID_NAME_USE snu;

TCHAR tszName[256], tszDomain[256];
DWORD cbName = 256, cbDomain = 256;

LookupAccountSid(NULL/* Local system */, 
    pTokenOwner->Owner, tszName, &cbName, tszDomain, &cbDomain, &snu))

// 输出用户名和 Domain
cout << _T("User = ") << tszName << endl;
cout << _T("Domain = ") << tszDomain << endl;

delete[] pvOwner;

 

取 Groups 和比较是否为 Administrators

 

// 获取 Token Information
GetTokenInformation(hToken, TokenGroups, NULL, 0, &dwReturned);

LPVOID pvGroups = new BYTE[dwReturned];
  
GetTokenInformation(hToken, TokenGroups, pvGroups, dwReturned, &dwReturned);

PTOKEN_GROUPS pTokenGroups = (PTOKEN_GROUPS)pvGroups;

// 获取 Administrators 的 SID
PSID pSIDAdmin = NULL;

SID_IDENTIFIER_AUTHORITY SIDAuth = SECURITY_NT_AUTHORITY;
AllocateAndInitializeSid(&SIDAuth, 2, SECURITY_BUILTIN_DOMAIN_RID, 
    DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pSIDAdmin);

// 查找 Token 是否属于 Administrators 组
SID_NAME_USE snu;

TCHAR tszName[256], tszDomain[256];
DWORD cbName = 256, cbDomain = 256;

for (int i = 0; i < pTokenGroups->GroupCount; i ++)
{
    LookupAccountSid(NULL/* Local system */, 
        pTokenGroups->Groups[i].Sid, tszName, &cbName, tszDomain, &cbDomain, &snu);

    if (EqualSid(pSIDAdmin, pTokenGroups->Groups[i].Sid))
        cout << " Administrators:" << endl;

    cout << _T("Group = ") << tszName << endl;
    cout << _T("Domain = ") << tszDomain << endl;
}

FreeSid(pSIDAdmin);
delete[] pvGroups;

 

上述代码在 Windows 2000/XP 下测试通过。

上一篇:Beanstalkd 介绍


下一篇:Disruptor 全解析(1):Ring Buffer 有什么特别?