Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To run cmd as administrator along with command?

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.

like image 228
purvang Avatar asked Sep 30 '11 13:09

purvang


People also ask

How do I open Command Prompt here as administrator?

Type cmd in the search box, then press Enter to open the highlighted Command Prompt shortcut. To open the session as an administrator, press Alt+Shift+Enter.


2 Answers

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();
        }
like image 70
Chris Haas Avatar answered Oct 02 '22 18:10

Chris Haas


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>
});
like image 39
mtijn Avatar answered Oct 02 '22 20:10

mtijn