1

I have a web service, and I want to be able to run a shell command which requires admin privileges. (The command is DJOIN, to pre-stage AD with a computer account and create a file.)

I am testing this as follows:

System.Diagnostics.Process proc = new System.Diagnostics.Process();
System.Security.SecureString ssPwd = new System.Security.SecureString();
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.Arguments = "/C echo %username% > c:\\test\\user.txt";
proc.StartInfo.Domain = "mydomain";
proc.StartInfo.UserName = "myadmin";
string password = "mypassword";
for (int x = 0; x < password.Length; x++)
{
    ssPwd.AppendChar(password[x]);
}
proc.StartInfo.Password = ssPwd;
proc.Start();

The c:\test folder on the web server has the correct permissions, and the code-block runs fine if I run it without specifying credentials. However, it fails when I add them in.

I have also tried including:

proc.StartInfo.Verb = "runas"

but this doesn't work either.

How can I run the command as an elevated user?

Ben
  • 4,281
  • 8
  • 62
  • 103
  • https://support.microsoft.com/en-us/kb/306158 check the "Impersonate a Specific User in Code" – Gusman May 03 '16 at 18:29
  • 1
    Possible duplicate of [Elevating process privilege programatically?](http://stackoverflow.com/questions/133379/elevating-process-privilege-programatically) – Xiaoy312 May 03 '16 at 18:30
  • I've tried using the "runas" verb, too, but this doesn't work either. – Ben May 03 '16 at 18:37

1 Answers1

1

The way I got this working was to use this code:

System.Diagnostics.Process proc = new System.Diagnostics.Process();
System.Security.SecureString ssPwd = new System.Security.SecureString();
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.Arguments = "/C echo %username% > c:\\test\\user.txt";
proc.StartInfo.Domain = "mydomain";
proc.StartInfo.Verb = "runas";
proc.StartInfo.UserName = "myadmin";
string password = "mypassword";
for (int x = 0; x < password.Length; x++)
{
    ssPwd.AppendChar(password[x]);
}
proc.StartInfo.Password = ssPwd;
proc.Start();

And also setting the application pool Identity in IIS to use this same user.

Ben
  • 4,281
  • 8
  • 62
  • 103