Ben
Ben

Reputation: 4319

How do I run a shell command in C# (on a webserver) with elevated credentials?

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?

Upvotes: 1

Views: 1653

Answers (1)

Ben
Ben

Reputation: 4319

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.

Upvotes: 1

Related Questions