首页 > 代码库 > 一个简单的以User权限启动外部应用程序(用NetUserAdd函数和USER_INFO_1结构体动态添加用户,然后用CreateProcessWithLogonW启动程序)
一个简单的以User权限启动外部应用程序(用NetUserAdd函数和USER_INFO_1结构体动态添加用户,然后用CreateProcessWithLogonW启动程序)
版权声明:本文为博主原创文章,未经博主允许不得转载。
[cpp] view plain copy
- 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
这样需要创建新的账户,可用OpenProcessToken+CreateRestrictedToken削去当前进程的令牌的特权用于CreateProcessAsUser
一个简单的以User权限启动外部应用程序(用NetUserAdd函数和USER_INFO_1结构体动态添加用户,然后用CreateProcessWithLogonW启动程序)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。