C++ 如何检查进程是否具有管理权限

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8046097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:55:04  来源:igfitidea点击:

How to check if a process has the administrative rights

c++winapi

提问by Vitaly

How do I properly check if a process is running with administrative rights?

如何正确检查进程是否以管理权限运行?

I checked the IsUserAnAdimfunction in MSDN, but it is not recommended as it might be altered or unavailable in subsequent versions of Windows. Instead, it is recommended to use the CheckTokenMembershipfunction.

IsUserAnAdim在 MSDN 中检查了该功能,但不建议这样做,因为它可能会在后续版本的 Windows 中被更改或不可用。相反,建议使用该CheckTokenMembership功能。

Then I looked at the alternate example in MSDN from a description of the CheckTokenMembershipfunction. However, there is Stefan Ozminski's comment in MSDN that mentions that this example does not work properly in Windows Vista if UACis disabled.

然后我从CheckTokenMembership函数的描述中查看了 MSDN 中的替代示例。但是,Stefan Ozminski 在 MSDN 中的评论提到如果UAC被禁用,这个例子在 Windows Vista 中不能正常工作。

Finally I tried to use Stefan Ozminski's code from MSDN, but it determines that the process has administrative rights even if I launch it under an ordinary user without the administrative rights in Windows 7.

最后我尝试使用来自 MSDN 的 Stefan Ozminski 的代码,但它确定该进程具有管理权限,即使我在 Windows 7 中没有管理权限的普通用户下启动它。

回答by Beached

This will tell you if you are running with elevated privileges or not. You can set the manifest to run with most possible if you want it to prompt. There are also other ways to ask windows through code for alternate credentials.

这将告诉您是否以提升的权限运行。如果您希望它提示,您可以将清单设置为尽可能多地运行。还有其他方法可以通过代码向 Windows 询问备用凭据。

BOOL IsElevated( ) {
    BOOL fRet = FALSE;
    HANDLE hToken = NULL;
    if( OpenProcessToken( GetCurrentProcess( ),TOKEN_QUERY,&hToken ) ) {
        TOKEN_ELEVATION Elevation;
        DWORD cbSize = sizeof( TOKEN_ELEVATION );
        if( GetTokenInformation( hToken, TokenElevation, &Elevation, sizeof( Elevation ), &cbSize ) ) {
            fRet = Elevation.TokenIsElevated;
        }
    }
    if( hToken ) {
        CloseHandle( hToken );
    }
    return fRet;
}

回答by J.Doe

You can use LsaOpenPolicy()function. The LsaOpenPolicyfunction opens a handle to the Policy object on a local or remote system.

您可以使用LsaOpenPolicy()功能。该LsaOpenPolicy函数打开本地或远程系统上的 Policy 对象的句柄。

You must run the process "As Administrator" so that the call doesn't fail with ERROR_ACCESS_DENIED.

您必须以“管理员身份”运行进程,以便调用不会因ERROR_ACCESS_DENIED.

Source: MSDN

来源:MSDN