简体   繁体   English

检查进程用户是否是管理员C ++

[英]Check if process user is an administrator c++

I want to get the process's user name and check if it is a local administrator . 我想要获取进程的用户名,并检查它是否是本地管理员。 Or check directly if the current procees user is a local administrator 或直接检查当前流程用户是否是本地管理员

Get the current username with GetUserName() , then call NetUserGetInfo() with the server name (NULL for local) and username you just got. 使用GetUserName()获取当前用户名,然后使用服务器名称(本地为NULL)和刚获得的用户名调用NetUserGetInfo() Pass it a USER_INFO_1 structure, and then access usri1_priv in the structure. 向其传递USER_INFO_1结构,然后在该结构中访问usri1_priv If the value is USER_PRIV_ADMIN , then you'll know that the username is an admin. 如果值为USER_PRIV_ADMIN ,则您将知道用户名是管理员。

Tested on Windows XP SP3, Windows 7 32 bit and 64 bit with admin user and non-admin user. 在Windows XP SP3,Windows 7 32位和64位(具有管理员用户和非管理员用户)上进行了测试。 Code ported from equivalent C# and uses ATL windows security wrapper classes. 从等效的C#移植的代码,并使用ATL Windows安全包装器类。

#include <atlbase.h>
#include <atlsecurity.h>

// The function returns true if the user who is running the
// application is a member of the Administrators group,
// which does not necessarily mean the process has admin privileges.
bool IsAdministrator(HRESULT &rHr)
{
    bool bIsAdmin = false;

    try
    {
        // Open the access token of the current process.
        ATL::CAccessToken aToken;
        if (!aToken.GetProcessToken(TOKEN_QUERY))
        {
            throw MAKE_SCODE(SEVERITY_ERROR, FACILITY_WIN32,
                ::GetLastError());
        }


        // Query for the access token's group information.
        ATL::CTokenGroups groups;
        if (!aToken.GetGroups(&groups))
        {
            throw MAKE_SCODE(SEVERITY_ERROR, FACILITY_WIN32,
                ::GetLastError());
        }

        // Iterate through the access token's groups
        // looking for a match against the builtin admins group.
        ATL::CSid::CSidArray groupSids;
        ATL::CAtlArray<DWORD> groupAttribs;
        groups.GetSidsAndAttributes(&groupSids, &groupAttribs);
        for (UINT i = 0; !bIsAdmin && i < groupSids.GetCount(); ++i)
        {
            bIsAdmin = groupSids.GetAt(i) == ATL::Sids::Admins();
        }
        rHr = S_OK;
    }
    catch (HRESULT hr)
    {
        rHr = hr;
    }

    return bIsAdmin;
}

Presuming you're on a Window OS there's a shell function: IsUserAnAdmin 假设您使用的是Window OS,则有一个Shell函数: IsUserAnAdmin

See MSDN article 请参阅MSDN文章

This article does suggest rolling your own function though, use CheckTokenMembership . 本文确实建议您滚动自己的函数,请使用CheckTokenMembership There is even a code example to help you along. 甚至还有一个代码示例可以帮助您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM