如何确定我的应用程序是否在SYSTEM帐户下运行?

时间:2013-11-17 20:41:30

标签: c++ windows

我如何判断我的应用程序是否在LocalSystem帐户下运行?有一个简单的方法吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

感谢您的帮助,但我可能找到了办法。我知道,这不是最好的,但它确实有效。

BOOL CheckIfRunningAsSYSTEM( VOID )  
{
DWORD i, dwSize = 0, dwResult = 0;
HANDLE hToken;
PTOKEN_USER Ptoken_User;

// Open a handle to the access token for the calling process.
if ( !OpenProcessToken( GetCurrentProcess(), TOKEN_QUERY, &hToken ) )
{
    printf( "OpenProcessToken Error %u\n", GetLastError() );
    return FALSE;
}

// Call GetTokenInformation to get the buffer size.
if ( !GetTokenInformation( hToken, TokenUser, NULL, dwSize, &dwSize ) )
{
    dwResult = GetLastError();
    if ( dwResult != ERROR_INSUFFICIENT_BUFFER )
    {
        printf( "GetTokenInformation Error %u\n", dwResult );
        return FALSE;
    }
}

// Allocate the buffer.
Ptoken_User = ( PTOKEN_USER )GlobalAlloc( GPTR, dwSize );

// Call GetTokenInformation again to get the group information.
if ( !GetTokenInformation( hToken, TokenUser, Ptoken_User, dwSize, &dwSize ) )
{
    printf( "GetTokenInformation Error %u\n", GetLastError() );
    return FALSE;
}

LPWSTR SID = NULL;

if ( !ConvertSidToStringSidW( Ptoken_User->User.Sid, &SID ) )
{
    printf( "\nConvertSidToStringSidW failed. Error = %d", GetLastError() );
    return FALSE;
}
else printf( "\nConvertSidToStringSidW succeeded." );

if ( _wcsicmp( L"S-1-5-18", SID ) == 0 ) printf( "\nRunning under SYSTEM" );
else printf( "\nNOT running under SYSTEM" );

if ( Ptoken_User ) GlobalFree( Ptoken_User );

return TRUE;

}//CheckIfRunningAsSYSTEM