如何获取当前Windows帐户的SID?

时间:2008-10-30 18:27:47

标签: c++ windows sid

我正在寻找一种简单的方法来获取当前Windows用户帐户的SID。我知道我可以通过WMI做到这一点,但我不想走那条路。

向在C#中回答的所有人道歉,因为没有指定它的C ++。 : - )

11 个答案:

答案 0 :(得分:49)

在Win32中,调用GetTokenInformation,传递令牌句柄和TokenUser常量。它将为您填写TOKEN_USER结构。其中一个元素是用户的SID。它是BLOB(二进制),但您可以使用ConvertSidToStringSid将其转换为字符串。

要掌握当前令牌句柄,请使用OpenThreadTokenOpenProcessToken

如果您更喜欢ATL,它有CAccessToken类,里面有各种有趣的东西。

.NET具有Thread.CurrentPrinciple属性,该属性返回IPrincipal引用。你可以得到SID:

IPrincipal principal = Thread.CurrentPrincipal;
WindowsIdentity identity = principal.Identity as WindowsIdentity;
if (identity != null)
    Console.WriteLine(identity.User);

同样在.NET中,您可以使用WindowsIdentity.GetCurrent(),它返回当前用户ID:

WindowsIdentity identity = WindowsIdentity.GetCurrent();
if (identity != null)
    Console.WriteLine(identity.User);

答案 1 :(得分:7)

这应该可以满足您的需求:

使用System.Security.Principal;

...

var sid = WindowsIdentity.GetCurrent()。User;

WindowsIdentity的User属性按MSDN Docs

返回SID

答案 2 :(得分:7)

ATL::CAccessToken accessToken;
ATL::CSid currentUserSid;
if (accessToken.GetProcessToken(TOKEN_READ | TOKEN_QUERY) &&
    accessToken.GetUser(&currentUserSid))
    return currentUserSid.Sid();

答案 3 :(得分:2)

CodeProject您可以尝试一些不同的方法......您没有提到您想要解决方案的语言。

如果您想通过批处理文件或其他内容访问它,可以通过Sysinternals查看PsGetSid。它将SID转换为名称,反之亦然。

答案 4 :(得分:2)

在C#中你可以使用

using Microsoft.Win32.Security;

...

string username = Environment.UserName + "@" + Environment.GetEnvironmentVariable("USERDNSDOMAIN");

Sid sidUser = new Sid (username);

或...

using System.Security.AccessControl;

using System.Security.Principal;

...

WindowsIdentity m_Self = WindowsIdentity.GetCurrent();

SecurityIdentifier m_SID = m_Self.Owner;");

答案 5 :(得分:2)

我找到另一种获得SID的方法:

System.Security.Principal.WindowsIdentity id = System.Security.Principal.WindowsIdentity.GetCurrent();
string sid = id.User.AccountDomainSid.ToString();

答案 6 :(得分:1)

在原生代码中:

function GetCurrentUserSid: string;

    hAccessToken: THandle;
    userToken: PTokenUser;
    dwInfoBufferSize: DWORD;
    dw: DWORD;

    if not OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, ref hAccessToken) then
        dw <- GetLastError;
        if dw <> ERROR_NO_TOKEN then
            RaiseLastOSError(dw);

        if not OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, ref hAccessToken) then
            RaiseLastOSError;
    try
        userToken <- GetMemory(1024);
        try
            if not GetTokenInformation(hAccessToken, TokenUser, userToken, 1024, ref dwInfoBufferSize) then
                RaiseLastOSError;
            Result <- SidToString(userToken.User.Sid);
        finally
            FreeMemory(userToken);
    finally
        CloseHandle(hAccessToken);

答案 7 :(得分:0)

您没有指定所需的语言。但是,如果您正在使用C#,那么本文提供了WMI方法以及使用Win32 API的更快(更详细)的方法。

http://www.codeproject.com/KB/cs/processownersid.aspx

我认为目前没有使用WMI或Win32 API的另一种方法。

答案 8 :(得分:0)

这是我认为最短的一个。

UserPrincipal.Current.Sid;

可用.net&gt; = 3.5

答案 9 :(得分:0)

这个问题被标记为c++,我用c++语言回答,所以我建议使用 WMI 工具:

因此,就像powershell中的 WMI 命令一样,下面的命令将获得SID用户的system-pc1

Get-WmiObject win32_useraccount -Filter "name = 'system-pc1'" | Select-Object sid

首先,您需要使用下面的username获取当前的code

char username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserName(username, &username_len);

现在,您可以尝试使用WQL语言并像下面这样在c++中执行此查询(在此示例中,我在system-pc1查询中使用了WQL_WIN32_USERACCOUNT_QUERY用户名:

#define                 NETWORK_RESOURCE                    "root\\CIMV2"
#define                 WQL_LANGUAGE                        "WQL"
#define                 WQL_WIN32_USERACCOUNT_QUERY         "SELECT * FROM Win32_Useraccount where name='system-pc1'"
#define                 WQL_SID                             "SID"

IWbemLocator            *pLoc = 0;              // Obtain initial locator to WMI to a particular host computer
IWbemServices           *pSvc = 0;              // To use of connection that created with CoCreateInstance()
ULONG                   uReturn = 0;
HRESULT                 hResult = S_OK;         // Result when we initializing
IWbemClassObject        *pClsObject = NULL;     // A class for handle IEnumWbemClassObject objects
IEnumWbemClassObject    *pEnumerator = NULL;    // To enumerate objects
VARIANT                 vtSID = { 0 };          // OS name property

// Initialize COM library
hResult = CoInitializeEx(0, COINIT_MULTITHREADED);
if (SUCCEEDED(hResult))
{
    // Initialize security
    hResult = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT,
        RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
    if (SUCCEEDED(hResult))
    {
        // Create only one object on the local system
        hResult = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER,
            IID_IWbemLocator, (LPVOID*)&pLoc);

        if (SUCCEEDED(hResult))
        {
            // Connect to specific host system namespace
            hResult = pLoc->ConnectServer(TEXT(NETWORK_RESOURCE), NULL, NULL,
                0, NULL, 0, 0, &pSvc);
            if (SUCCEEDED(hResult))
            {
                /* Set the IWbemServices proxy
                * So the impersonation of the user will be occurred */
                hResult = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE,
                    NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE,
                    NULL, EOAC_NONE);
                if (SUCCEEDED(hResult))
                {
                    /* Use the IWbemServices pointer to make requests of WMI
                    * For example, query for user account */
                    hResult = pSvc->ExecQuery(TEXT(WQL_LANGUAGE), TEXT(WQL_WIN32_USERACCOUNT_QUERY),
                        WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
                    if (SUCCEEDED(hResult))
                    {
                        // Go to get the next object from IEnumWbemClassObject
                        pEnumerator->Next(WBEM_INFINITE, 1, &pClsObject, &uReturn);
                        if (uReturn != 0)
                        {
                            // Get the value of the "sid, ..." property
                            pClsObject->Get(TEXT(WQL_SID), 0, &vtSID, 0, 0);
                            VariantClear(&vtSID);

                            // Print SID
                            wcout << vtSID.bstrVal;

                            pClsObject->Release();
                            pClsObject = NULL;
                        }
                    }
                }
            }
        }
    }

    // Cleanup
    pSvc->Release();
    pLoc->Release();
    pEnumerator->Release();
    // Uninitialize COM library
    CoUninitialize();

此示例可以正常工作!

答案 10 :(得分:0)

在cmd.exe中

  

用户/用户

如果您需要编程方式,请询问更多指定的人