8

Here is my code:

try
{
    ProcessStartInfo procStartInfo = new ProcessStartInfo(
                                            "cmd.exe", 
                                            "/c " + command);
    procStartInfo.UseShellExecute = true;
    procStartInfo.CreateNoWindow = true;
    procStartInfo.Verb = "runas";
    procStartInfo.Arguments = "/env /user:" + "Administrator" + " cmd" + command;

    ///command contains the command to be executed in cmd
    System.Diagnostics.Process proc = new System.Diagnostics.Process();
    proc.StartInfo = procStartInfo;
    proc.Start();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

I want to keep

procStartInfo.UseShellExecute = true 
procStartInfo.RedirectStandardInput = false;

Is it possible to execute the command without using process.standardinput? I try to execute command I've passed in argument but the command does not executes.

sll
  • 61,540
  • 22
  • 104
  • 156
purvang
  • 339
  • 4
  • 6
  • 15
  • **Is it possible to execute the command without using process.standardinput? I try to execute command I've passed in argument but the command does not executes.** You are currently not using it, so this question, does not make a great deal of sense. Please do your user's favor and allow the command prompt to be visible, so they know whats going on. – Security Hound Sep 30 '11 at 13:07
  • 1
    You don't want `Verb`. That doesn't mean what you think it means. I think. – Roger Lipscombe Sep 30 '11 at 13:08
  • @Ramhound procStartInfo.Arguments = "/env /user:" + "Administrator" + " cmd" + **command**; – purvang Sep 30 '11 at 13:09
  • @mtijn yes it fails at that point. so i want to know is it possible to give the command some other way – purvang Sep 30 '11 at 13:11
  • This might help: [Start Process with administrator right in C#](http://stackoverflow.com/questions/4106628/start-process-with-administrator-right-in-c) – DK. Sep 30 '11 at 13:52

2 Answers2

6

As @mtijn said you've got a lot going on that you're also overriding later. You also need to make sure that you're escaping things correctly.

Let's say that you want to run the following command elevated:

dir c:\

First, if you just ran this command through Process.Start() a window would pop open and close right away because there's nothing to keep the window open. It processes the command and exits. To keep the window open we can wrap the command in separate command window and use the /K switch to keep it running:

cmd /K "dir c:\"

To run that command elevated we can use runas.exe just as you were except that we need to escape things a little more. Per the help docs (runas /?) any quotes in the command that we pass to runas need to be escaped with a backslash. Unfortunately doing that with the above command gives us a double backslash that confused the cmd parser so that needs to be escaped, too. So the above command will end up being:

cmd /K \"dir c:\\\"

Finally, using the syntax that you provided we can wrap everything up into a runas command and enclose our above command in a further set of quotes:

runas /env /user:Administrator "cmd /K \"dir c:\\\""

Run the above command from a command prompt to make sure that its working as expected.

Given all that the final code becomes easier to assemble:

        //Assuming that we want to run the following command:
        //dir c:\

        //The command that we want to run
        string subCommand = @"dir";

        //The arguments to the command that we want to run
        string subCommandArgs = @"c:\";

        //I am wrapping everything in a CMD /K command so that I can see the output and so that it stays up after executing
        //Note: arguments in the sub command need to have their backslashes escaped which is taken care of below
        string subCommandFinal = @"cmd /K \""" + subCommand.Replace(@"\", @"\\") + " " + subCommandArgs.Replace(@"\", @"\\") + @"\""";

        //Run the runas command directly
        ProcessStartInfo procStartInfo = new ProcessStartInfo("runas.exe");
        procStartInfo.UseShellExecute = true;
        procStartInfo.CreateNoWindow = true;

        //Create our arguments
        string finalArgs = @"/env /user:Administrator """ + subCommandFinal + @"""";
        procStartInfo.Arguments = finalArgs;

        //command contains the command to be executed in cmd
        using (System.Diagnostics.Process proc = new System.Diagnostics.Process())
        {
            proc.StartInfo = procStartInfo;
            proc.Start();
        }
Chris Haas
  • 53,986
  • 12
  • 141
  • 274
  • I did run the following command you suggested in cmd runas /env /user:Administrator "cmd /K \"dir c:\\\"" It ask the password even if i enter password it fails it gives the below output Unable to run cmd /k "dir c:\" – purvang Oct 01 '11 at 06:41
  • Did you run `runas /env /user:Administrator "cmd /K \"dir c:\\\""` or `cmd runas /env /user:Administrator "cmd /K \"dir c:\\\""`? The first is what you should have run. – Chris Haas Oct 01 '11 at 11:35
  • i run it as runas /env /user:Administrator "cmd /K \"dir c:\\\"" but it gives error as follows Unable to run cmd /k "dir c:\" – purvang Oct 01 '11 at 11:43
  • If you are getting the error `RUNAS ERROR: Unable to run - cmd /K "dir c:\"` you should also be getting a primary error such as `1326: Logon failure: unknown user name or bad password.`, are you? – Chris Haas Oct 01 '11 at 11:49
  • yes i am getting that error too alongwith it!!! I am giving right password after that i removed password and also tried it but it didnt work – purvang Oct 01 '11 at 12:23
  • 1
    If the error is 1326 then its a bad username/password combination and you need to fix that. The problem isn't with the command, its the credentials. If you are in a domain environment you might gave to change `Administrator` to `YOURDOMAIN\Administrator`. If you are getting error code 1327 then there's a Group Policy of some sort blocking it. – Chris Haas Oct 01 '11 at 12:54
  • You may need to change /user:Administrator to the user account you want to run under (which has admin priviledges). So if my administrative account is JohnC, then use /user:JohnC, it will now ask for the password for that user. – Xantix Sep 01 '12 at 22:57
1

why are you initializing the process object with arguments and then later on override those Arguments? and btw: the last bit where you set Arguments you concatenate 'command' right upto 'cmd', that doesn't make much sense and might be where it fails (looks like you're missing a space).

Also, you are currently using the standard command line, you might want to look into using the runas tool instead. you can also call runas from command line.

Also, why are you running 'command' from the command line? why not start it directly from Process.Start with admin privileges supplied then and there? here's a bit of pseudocode:

Process p = Process.Start(new ProcessStartInfo()
{
    FileName = <your executable>,
    Arguments = <any arguments>,
    UserName = "Administrator",
    Password = <password>,
    UseShellExecute = false,
    WorkingDirectory = <directory of your executable>
});
mtijn
  • 3,610
  • 2
  • 33
  • 55
  • thanks for the idea but i dont know how to give admin privileges during process.start.can you give some sample code or example? – purvang Sep 30 '11 at 13:37