本文共 2131 字,大约阅读时间需要 7 分钟。
//Function to run a process as active user from windows servicevoid ImpersonateActiveUserAndRun(){ DWORD session_id = -1; DWORD session_count = 0; WTS_SESSION_INFOA *pSession = NULL; if (WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pSession, &session_count)) { printf("pSession=====%d\n", pSession); printf("session_count=====%d\n", session_count); } else { printf("WTSEnumerateSessions ===============failed \n"); return; } for (DWORD i = 0; i < session_count; i++) { session_id = pSession[i].SessionId; printf("session_id=====%d\n", session_id); WTS_CONNECTSTATE_CLASS wts_connect_state = WTSDisconnected; WTS_CONNECTSTATE_CLASS* ptr_wts_connect_state = NULL; DWORD bytes_returned = 0; if (::WTSQuerySessionInformation( WTS_CURRENT_SERVER_HANDLE, session_id, WTSConnectState, reinterpret_cast(&ptr_wts_connect_state), &bytes_returned)) { wts_connect_state = *ptr_wts_connect_state; ::WTSFreeMemory(ptr_wts_connect_state); printf("wts_connect_state=====%d\n", wts_connect_state); // if (wts_connect_state != WTSActive) continue; } else { printf("WTSQuerySessionInformation ===============failed \n"); continue; } HANDLE hImpersonationToken = 0; BOOL bRet = WTSQueryUserToken(session_id, &hImpersonationToken); if (bRet == false) { printf(" WTSQueryUserTokenERROR: %d\n", GetLastError()); } printf("hImpersonationToken=====%d\n", hImpersonationToken); //Get real token from impersonation token DWORD neededSize1 = 0; HANDLE *realToken = new HANDLE; if (GetTokenInformation(hImpersonationToken, (::TOKEN_INFORMATION_CLASS) TokenLinkedToken, realToken, sizeof(HANDLE), &neededSize1)) { CloseHandle(hImpersonationToken); hImpersonationToken = *realToken; } else { //log error continue; } }}
转载地址:http://jhagx.baihongyu.com/