简体   繁体   English

以管理员身份运行cmd和命令?

[英]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 ? 是否可以在不使用process.standardinput情况下执行命令? I try to execute command I've passed in argument but the command does not executes. 我尝试执行命令我已经传入参数,但命令没有执行。

As @mtijn said you've got a lot going on that you're also overriding later. 正如@mtijn所说,你有很多事情要做,以后你也会压倒一切。 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. 首先,如果您只是通过Process.Start()运行此命令,则会立即打开并关闭一个窗口,因为没有任何东西可以保持窗口打开。 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: 要保持窗口打开,我们可以将命令包装在单独的命令窗口中,并使用/K开关使其保持运行:

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. 要运行该命令,我们可以像使用runas.exe一样使用runas.exe ,除了我们需要更多地转义。 Per the help docs ( runas /? ) any quotes in the command that we pass to runas need to be escaped with a backslash. 根据帮助文档( runas /? ),我们传递给runas的命令中的任何引号都需要使用反斜杠进行转义。 Unfortunately doing that with the above command gives us a double backslash that confused the cmd parser so that needs to be escaped, too. 不幸的是,使用上面的命令执行此操作会给我们一个双重反斜杠,这会使cmd解析器混淆,因此也需要进行转义。 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命令中,并将上面的命令括在另一组引号中:

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();
        }

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). 和btw:你设置参数的最后一位你将'命令'连接到'cmd',这没有多大意义,可能是它失败的地方(看起来你错过了一个空格)。

Also, you are currently using the standard command line, you might want to look into using the runas tool instead. 此外,您当前正在使用标准命令行,您可能希望使用runas工具 you can also call runas from command line. 你也可以从命令行调用runas。

Also, why are you running 'command' from the command line? 另外,为什么要从命令行运行'command'? why not start it directly from Process.Start with admin privileges supplied then and there? 为什么不直接从Process.Start启动它,然后提供管理员权限? 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>
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM