一个简单的以User权限启动外部应用程序

时间:2023-02-11 19:23:48
BOOL ExecuteAsUser(LPCWSTR lpszUserName, LPCWSTR lpszPassword, LPCWSTR lpszApplication, LPCWSTR lpszCmdLine)
{
    if(NULL == lpszUserName)
    {
        return FALSE;
    }
    if(NULL == lpszApplication)
    {
        return FALSE;
    }

    BOOL bRet = FALSE;
    WCHAR* pUserName = NULL;
    WCHAR* pPassword = NULL;
    STARTUPINFO si = {sizeof(si)};
    PROCESS_INFORMATION pi = {0};
    WCHAR szApp[MAX_PATH * 2] = {0};

    // Check User Name
    size_t nLen = wcslen(lpszUserName) + 1;
    pUserName = new WCHAR[nLen];
    StringCchPrintfW(pUserName, nLen, L"%s", lpszUserName);
    
    // Check Password
    nLen = (NULL != lpszPassword) ? (wcslen(lpszPassword) + 1) : 2;
    pPassword = new WCHAR[nLen];
    StringCchPrintfW(pPassword, nLen, L"%s", (NULL != lpszPassword) ? lpszPassword : L"");

    USER_INFO_1 ui;
    DWORD dwError = 0;
    DWORD dwLevel = 1;
    ui.usri1_name = pUserName;
    ui.usri1_password = pPassword;
    ui.usri1_priv = USER_PRIV_USER;
    ui.usri1_home_dir = NULL;
    ui.usri1_comment = NULL;
    ui.usri1_flags = UF_SCRIPT;
    ui.usri1_script_path = NULL;
    // Add User
    if(NERR_Success != NetUserAdd(NULL, dwLevel, (LPBYTE)&ui, &dwError))
    {
        goto _END_;
    }

    if((NULL != lpszCmdLine) && wcslen(lpszCmdLine))
        StringCchPrintfW(szApp, _countof(szApp), L"%s %s", lpszApplication, lpszCmdLine);
    else
        StringCchPrintfW(szApp, _countof(szApp), L"%s", lpszApplication);

    if(CreateProcessWithLogonW(lpszUserName, NULL, lpszPassword, LOGON_WITH_PROFILE, NULL, szApp, 0, NULL, NULL, &si, &pi))
    {
        bRet = TRUE;
        CloseHandle(pi.hThread);
        CloseHandle(pi.hProcess);
    }
    else
    {
        dwError = GetLastError();
        goto _CLEANUP_;
    }
    bRet = TRUE;

_CLEANUP_:
    // Delete User
    NetUserDel(NULL, lpszUserName);
_END_:
    if(NULL != pPassword)
    {
        delete[] pPassword;
        pPassword = NULL;
    }
    if(NULL != pUserName)
    {
        delete[] pUserName;
        pUserName = NULL;
    }
    return bRet;
}

// 测试代码
#include "stdafx.h"

#include <Windows.h>
#include <lm.h>
#include <strsafe.h>
#pragma comment(lib, "Netapi32.lib")

int _tmain(int argc, _TCHAR* argv[])
{
    ExecuteAsUser(L"ABC", L"Hello", L"F:\\11.exe", NULL);
    return 0;
}

参考:http://blog.csdn.net/visualeleven/article/details/7640475