1

I have an app running as Network Service (I can't change this) and need to run a command (execute as bat script) as a known local user. I seem to get no response and the script doesn't execute. The odd thing is that if i run the code as the local user its works without an issue.

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = @"C:\Windows\System32\cmd.exe";
startInfo.Arguments = "/C " + @"c:\example\script.bat";
startInfo.UseShellExecute = false;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardOutput = true;
var sspw = new SecureString();
foreach (var c in "MyPassword")
{
 sspw.AppendChar(c);
}
startInfo.Domain = Environment.MachineName;
startInfo.UserName = "MyUser";
startInfo.Password = sspw;
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
Karanko
  • 23
  • 1
  • 5
  • have you tried using your `ProcessStartInfo` object to actually run the process (instead of having the separate `Process` object)? – SlimsGhost Sep 30 '16 at 19:06
  • Unfortunately the service need to run as NetworkService its out of my control, I did try using [link](https://www.nuget.org/packages/SimpleImpersonation) but didn't get far. – Karanko Sep 30 '16 at 19:06
  • According to [this article](https://msdn.microsoft.com/en-us/library/windows/desktop/ms684272(v=vs.85).aspx), `NetworkService` "has minimum privileges on the local computer". Interpreting this logically, this would seem to suggest you can't run a process under this account as a different user because all other users would have more access than `NetworkService` has. – Icemanind Sep 30 '16 at 19:09
  • [Here is a SO post](http://stackoverflow.com/a/564429/3407841) where they do what you want to do (start a program as a user from a service running as Network Service). – leetibbett Sep 30 '16 at 19:13
  • @leetibbett that looks good, I'll try it out when I'm back at the dev machine. – Karanko Sep 30 '16 at 19:20
  • thanks @leetibbett this got me what I needed, works a treat. – Karanko Sep 30 '16 at 22:32
  • You're welcome @Karanko – leetibbett Sep 30 '16 at 22:36

2 Answers2

0

I believe you need to set the working directory when using a Username/Password

according to MSDN...

The WorkingDirectory property must be set if UserName and Password are provided. If the property is not set, the default working directory is %SYSTEMROOT%\system32.

Karanko
  • 23
  • 1
  • 5
OOPMichael
  • 50
  • 2
  • 8
0

Not sure whether this solution will help your need but if set the WorkingDirectory to current directory (".") then it should work. Basically the user who is running the process should have permission on the folder that you mention.

Libish Jacob
  • 308
  • 4
  • 8