c++ createprocess as administrator and get its output

Maposa Takalani picture Maposa Takalani · Nov 14, 2013 · Viewed 8.3k times · Source

I have a problem, I have been looking for two things that must go together, running a process through Createprocess() as an administrator and get the output.

When I Google how to CreateProcess() as an administrator I get people replying to use shellexecute. I go to shellexecute, while I am there, shellexecute does not output what ran on the console(process).

I Google again how do I get the output of a process with shellexecute, I get answers that say you cannot do that with shellexecute, use createprocess, so I go to createprocess. I am struggling to convert what I am doing with shellexecute to createprocess.

What I am doing with shellexecute does what I am looking for, run as administrator. but no output.

Here is my shellexecute code.

SHELLEXECUTEINFO si = {0};

si.cbSize = sizeof(SHELLEXECUTEINFO);
si.fMask = SEE_MASK_NOCLOSEPROCESS;
si.hwnd =NULL;
si.lpVerb = "runas";
si.lpFile = "netsh.exe";
si.lpParameters = "advfirewall firewall      add rule name=\"dummy_rule\" action=allow protocol=TCP dir=in localport=3300";
si.lpDirectory=NULL;
si.nShow=SW_SHOW;
si.hInstApp =NULL;
ShellExecuteEx(&si);
WaitForSingleObject(si.hProcess, INFINITE);
CloseHandle(si.hProcess);

This code runs in a method and what it does is add a firewall rule to open a port for imcoming connections. It is working fine as it is, the problem is I won't know whether the process was successfull, not shellexecute. so I need output.

Answer

friedrich kuhler picture friedrich kuhler · Nov 14, 2013

Your code is actually Creates two process runas.exe and netsh.exe , where it could create only one instead . The right way of doing that would be:

  1. Use LogonUser() functions with the Administrator credentials, to get an administrative token.
  2. Call CreateProcessAsUser() with your IO redirection and the above token.

note that for CreateProcessAsUser() you should specify netsh.exe as the process you'd like to execute, and your argument in LPTSTR lpCommandLine.