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

发布于 2024-12-07 19:45:40 字数 874 浏览 1 评论 0原文

这是我的代码:

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

我想保留

procStartInfo.UseShellExecute = true 
procStartInfo.RedirectStandardInput = false;

是否可以在不使用process.standardinput的情况下执行命令? 我尝试执行在参数中传递的命令,但该命令不执行。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

萌逼全场 2024-12-14 19:45:40

正如 @mtijn 所说,你已经做了很多事情,稍后你也会覆盖这些事情。您还需要确保正确转义。

假设您想要运行以下提升的命令:

dir c:\

首先,如果您刚刚通过 Process.Start() 运行此命令,则窗口会立即打开并关闭,因为没有任何东西可以使窗口保持打开状态。它处理命令并退出。要保持窗口打开,我们可以将命令包装在单独的命令窗口中,并使用 /K 开关使其保持运行:

cmd /K "dir c:\"

要运行提升的命令,我们可以使用 runas.exe就像你一样,只是我们需要更多地逃避事情。根据帮助文档 (runas /?),我们传递给 runas 的命令中的任何引号都需要用反斜杠转义。不幸的是,使用上面的命令执行此操作会产生一个双反斜杠,这会混淆 cmd 解析器,因此也需要对其进行转义。因此,上面的命令最终将是:

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

最后,使用您提供的语法,我们可以将所有内容包装到 runas 命令中,并将上面的命令括在另一组引号中

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

:命令提示符以确保其按预期工作。

鉴于所有这些,最终代码变得更容易组装:

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

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();
        }
远昼 2024-12-14 19:45:40

为什么要使用参数初始化流程对象,然后覆盖这些参数?顺便说一句:您设置参数的最后一位将“command”连接到“cmd”,这没有多大意义,可能是它失败的地方(看起来您缺少一个空格)。

另外,您当前正在使用标准命令行,您可能需要考虑使用 runas 工具。您还可以从命令行调用 runas。

另外,为什么要从命令行运行“命令”?为什么不使用当时提供的管理员权限直接从 Process.Start 启动它呢?这是一些伪代码:

Process p = Process.Start(new ProcessStartInfo()
{
    FileName = <your executable>,
    Arguments = <any arguments>,
    UserName = "Administrator",
    Password = <password>,
    UseShellExecute = false,
    WorkingDirectory = <directory of your executable>
});

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>
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文