由于系统服务环境面向的是硬件和操作系统,它默认的窗口桌面、注册表等与管理员权限还不同。如果你要运行诸如pstore等程序是得不到正常的结果。如果要运行前台程序,还需要进行进程令牌的设置,利用CreateProcessAsUser进行启动。
废话就不多说。直接给代码:
#include <windows.h>
#include <stdio.h>
#include <psapi.h>
#pragma comment(lib,"PsApi.lib")
DWORD ProcessToPID(char *InputProcessName)
{
DWORD aProcesses[1024], cbNeeded, cProcesses;
unsigned int i;
HANDLE hProcess;
HMODULE hMod;
char szProcessName[MAX_PATH] = "UnknownProcess";
if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ) return 0;
cProcesses = cbNeeded / sizeof(DWORD);
for ( i = 0; i < cProcesses; i++ )
{
hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,
FALSE, aProcesses[i]);
if ( hProcess )
{
if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), &cbNeeded) )
{
GetModuleBaseName( hProcess, hMod,
szProcessName, sizeof(szProcessName) );
if(!_stricmp(szProcessName, InputProcessName)){
CloseHandle( hProcess );
return aProcesses[i];
}
}
}
}
CloseHandle( hProcess );
return 0;
}
//////////////////////////////////
BOOL GetTokenByName(HANDLE &hToken,LPSTR lpName)
{
if(!lpName) return FALSE;
DWORD ProcessID = ProcessToPID(lpName);
if(ProcessID==0) return FALSE;
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,ProcessID);
return OpenProcessToken(hProcess,TOKEN_ALL_ACCESS,&hToken);
}
int main( int argc, char *argv[])
{
if( argc == 2 )
{
HANLE hToken;
if( !GetTokenByName(hToken,"Explorer.exe") )
{
printf("GetTokenByName Failed!\n");
return 0;
}
PROCESS_INFORMATION pi;
STARTUPINFO si;
ZeroMemory( &si, sizeof(STARTUPINFO) );
siStartInfo.cb = sizeof(STARTUPINFO);
ret = CreateProcessAsUser( hToken,
NULL,
argv[1],
NULL,
NULL,
TRUE,
0,
NULL,
NULL,
&si,
&pi );
CloseHandle(hToken);
printf("CreateProcess Success!\n");
return 1;
}
printf("Parameter Error!\n");
return 0;
}
用法很简单,后面跟你要执行的exe就行。
[注意]传递专业知识、拓宽行业人脉——看雪讲师团队等你加入!