码迷,mamicode.com
首页 > 其他好文 > 详细

这个函数有搞头,要调试通过就差不多啦--ImpersonateActiveUserAndRun

时间:2016-07-24 01:45:39      阅读:406      评论:0      收藏:0      [点我收藏+]

标签:

//Function to run a process as active user from windows service
void 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<LPTSTR*>(&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;
        }
    }
}

 

这个函数有搞头,要调试通过就差不多啦--ImpersonateActiveUserAndRun

标签:

原文地址:http://www.cnblogs.com/aguncn/p/5699957.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!