判断并以管理员权限运行程序

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/yu_sn0w/article/details/80852779


bool IsAdminRunning(void)
{
bool IsMember = FALSE;
SID_IDENTIFIER_AUTHORITY peUse = SECURITY_NT_AUTHORITY;
PSID SidUser = NULL;
HANDLE ProToken = NULL;
LPVOID TokenInformation = NULL;
TOKEN_GROUPS* TokenGroupList = NULL;
DWORD TokenInformationLength = 0;
DWORD ReturnLength = 0;


if (!AllocateAndInitializeSid(&peUse, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &SidUser))
{
return FALSE;
}


if (!OpenThreadToken(GetCurrentThread(), TOKEN_READ | TOKEN_DUPLICATE, TRUE, &ProToken))
{
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ | TOKEN_DUPLICATE, &ProToken))
{
FreeSid(SidUser);
SidUser = NULL;
return FALSE;
}
}


GetTokenInformation(ProToken, TokenGroups, TokenInformation, TokenInformationLength, &ReturnLength);
TokenInformationLength = ReturnLength;
TokenInformation = calloc(TokenInformationLength, sizeof(BYTE));
if (NULL == TokenInformation)
{
FreeSid(SidUser);
SidUser = NULL;
CloseHandle(ProToken);
ProToken = NULL;
return FALSE;
}


GetTokenInformation(ProToken, TokenGroups, TokenInformation, TokenInformationLength, &ReturnLength);
TokenGroupList = (TOKEN_GROUPS*)TokenInformation;


for(int i = 0; i < TokenGroupList->GroupCount; ++i)
{
if (EqualSid(TokenGroupList->Groups[i].Sid, SidUser))
{
if (TokenGroupList->Groups[i].Attributes & SE_GROUP_ENABLED || TokenGroupList->Groups[i].Attributes & SE_GROUP_ENABLED_BY_DEFAULT)
{
IsMember = true;
break;
}
}
}


FreeSid(SidUser);
SidUser = NULL;
CloseHandle(ProToken);
ProToken = NULL;
free(TokenGroupList);
TokenGroupList = NULL;


return IsMember;
}


void RunAsAdmin()
{
SHELLEXECUTEINFO info = {0};
info.lpVerb = "runas";
info.lpFile = "...\a.exe";
info.hwnd = NULL;
info.lpParameters =""; // 自己需要的main参数
info.nShow = SW_NORMAL;
if (ShellExecuteEx(&info))
{


}
else
{
info.lpVerb = NULL;
ShellExecuteEx(&info)
}
}
展开阅读全文

没有更多推荐了,返回首页