Enabling and Disabling Privileges in C++ - Win32 apps | Microsoft Docs
BOOL SetPrivilege(LPCTSTR lpszPrivilege, BOOL bEnablePrivilege) { TOKEN_PRIVILEGES tp; HANDLE hToken; LUID luid; if( !OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken) ) { printf("OpenProcessToken error: %un", GetLastError()); return FALSE; } if( !LookupPrivilegevalue(NULL, // lookup privilege on local system lpszPrivilege, // privilege to lookup &luid) ) // receives LUID of privilege { printf("LookupPrivilegevalue error: %un", GetLastError() ); return FALSE; } tp.PrivilegeCount = 1; tp.Privileges[0].Luid = luid; if( bEnablePrivilege ) tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; else tp.Privileges[0].Attributes = 0; // Enable the privilege or disable all privileges. if( !AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES) NULL, (PDWORD) NULL) ) { printf("AdjustTokenPrivileges error: %un", GetLastError() ); return FALSE; } if( GetLastError() == ERROR_NOT_ALL_ASSIGNED ) { printf("The token does not have the specified privilege、n"); return FALSE; } return TRUE;}
调用
int main(int argc, char *argv[]){// change privilegeif( !SetPrivilege(SE_DEBUG_NAME, TRUE) ) return 1;return 0;}
提升当前进程权限后,可以对其它进程进行读取、写入、改写等操作,若当前Windows用户权限够高,那么就不需要上面提升权限代码,反之则需要。