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

谢谢!

最佳答案

感谢您的帮助,但我可能已经找到了一种方法。我知道这不是最好的方法,但它可以工作。

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

10-04 21:03