C# 从 ASPX 页面运行命令行,并将输出返回到页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/247668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 19:45:57  来源:igfitidea点击:

Running Command line from an ASPX page, and returning output to page

c#asp.net

提问by user32474

I'm trying to access the command line and execute a command, and then return the output to my aspx page. A good example would be running dir on page load of an aspx page and returning the output via Response.Write(). I have tried using the code below. When I try debugging this it runs but never finishes loading and no output is rendered. I am using C# and .NET Framework 3.5sp1. Any help much appreciated.

我正在尝试访问命令行并执行命令,然后将输出返回到我的 aspx 页面。一个很好的例子是在 aspx 页面的页面加载时运行 dir 并通过 Response.Write() 返回输出。我试过使用下面的代码。当我尝试调试它时,它运行但从未完成加载并且没有呈现任何输出。我正在使用 C# 和 .NET Framework 3.5sp1。非常感谢任何帮助。

Thanks, Bryan

谢谢,布莱恩

public partial class CommandLine : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Diagnostics.Process si = new System.Diagnostics.Process();
        si.StartInfo.WorkingDirectory = @"c:\";
        si.StartInfo.UseShellExecute = false;
        si.StartInfo.FileName = "cmd.exe";
        si.StartInfo.Arguments = "dir";
        si.StartInfo.CreateNoWindow = true;
        si.StartInfo.RedirectStandardInput = true;
        si.StartInfo.RedirectStandardOutput = true;
        si.StartInfo.RedirectStandardError = true;
        si.Start();
        string output = si.StandardOutput.ReadToEnd();
        si.Close();
        Response.Write(output);
    }
}

采纳答案by configurator

You have a problem with the syntax of commandline arguments to cmd.exe. This is why cmd never exits.
In order to have cmd.exe run a program and then quit, you need to send it the syntax "/c [command]". Try running the same code with the line

您对 cmd.exe 的命令行参数的语法有问题。这就是为什么 cmd 永远不会退出的原因。
为了让 cmd.exe 运行程序然后退出,您需要向它发送语法“/c [command]”。尝试使用该行运行相同的代码

        si.StartInfo.Arguments = "dir";

replaced with

替换为

        si.StartInfo.Arguments = "/c dir";

and see if it works.

看看它是否有效。

回答by Sunny Milenov

Most likely your problem is with the permissions. The user under which ASP.NET process runs is with very limited rights.

您的问题很可能与权限有关。运行 ASP.NET 进程的用户的权限非常有限。

So, either you have to set the proper permissions for that user, or run ASP.NET under some other user.

因此,要么您必须为该用户设置适当的权限,要么在其他用户下运行 ASP.NET。

This hides a security risks though, so you have to be very careful.

但是,这隐藏了安全风险,因此您必须非常小心。

回答by rp.

This is madness! Use the System.IO namepace to create your file list from inside your C# program! It's very easy to do; although this technique also has authorization issues.

这太疯狂了!使用 System.IO 命名空间从 C# 程序内部创建文件列表!这很容易做到;虽然这种技术也有授权问题。

回答by Corey Trager

Use System.Diagnostics.Process.

使用 System.Diagnostics.Process。

Here is some ASP.NET code shelling out to run subversion commands on the command line.

下面是一些 ASP.NET 代码,用于在命令行上运行 subversion 命令。

    ///////////////////////////////////////////////////////////////////////
    public static string run_svn(string args_without_password, string svn_username, string svn_password)
    {
        // run "svn.exe" and capture its output

        System.Diagnostics.Process p = new System.Diagnostics.Process();
        string svn_path = Util.get_setting("SubversionPathToSvn", "svn");
        p.StartInfo.FileName = svn_path;
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;

        args_without_password += " --non-interactive";
        Util.write_to_log ("Subversion command:" + svn_path + " " + args_without_password);

        string args_with_password = args_without_password;

        if (svn_username != "")
        {
            args_with_password += " --username ";
            args_with_password += svn_username;
            args_with_password += " --password ";
            args_with_password += svn_password;
        }

        p.StartInfo.Arguments = args_with_password;
        p.Start();
        string stdout = p.StandardOutput.ReadToEnd();
        p.WaitForExit();
        stdout += p.StandardOutput.ReadToEnd();

        string error = p.StandardError.ReadToEnd();

        if (error != "")
        {
            Util.write_to_log(error);
            Util.write_to_log(stdout);
        }

        if (error != "")
        {
            string msg = "ERROR:";
            msg += "<div style='color:red; font-weight: bold; font-size: 10pt;'>";
            msg += "<br>Error executing svn.exe command from web server.";
            msg += "<br>" + error;
            msg += "<br>Arguments passed to svn.exe (except user/password):" + args_without_password;
            if (error.Contains("File not found"))
            {
                msg += "<br><br>***** Has this file been deleted or renamed? See the following links:";
                msg += "<br><a href=http://svn.collab.net/repos/svn/trunk/doc/user/svn-best-practices.html>http://svn.collab.net/repos/svn/trunk/doc/user/svn-best-practices.html</a>";
                msg += "<br><a href=http://subversion.open.collab.net/articles/best-practices.html>http://subversion.open.collab.net/articles/best-practices.html</a>";
                msg += "</div>";
            }
            return msg;
        }
        else
        {
            return stdout;
        }
    }