【问题标题】:Exectute a Linux Shell command from ASP.NET Core 3 app从 ASP.NET Core 3 应用程序执行 Linux Shell 命令
【发布时间】:2020-09-06 21:28:43
【问题描述】:

我的问题实际上是,如何从我的应用程序执行 Shell 命令。有一个类似的Post,但它显示了如何执行脚本文件并需要该文件的路径。

var process = new Process()
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = command, // Path required here
            Arguments = args,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true,
        }
    };
process.Start();

为什么要将命令作为字符串传递?

因为我想插入它。否则,我将不得不创建一个带有一些输入参数的脚本。由于我对 Shell 不太擅长,所以我更喜欢简单的方法。

【问题讨论】:

    标签: c# linux asp.net-mvc shell asp.net-core


    【解决方案1】:

    假设你想在 bash 中运行 echo hello,那么

        Process process = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = "bash",
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false
            }
        };
        process.Start();
        await process.StandardInput.WriteLineAsync("echo hello");
        var output = await process.StandardOutput.ReadLineAsync();
        Console.WriteLine(output);
    

    【讨论】:

    • 但是为什么在 bash 中?如果外壳是 zsh 怎么办? =)
    • @MaximV.Pavlov bash 假定在大多数 Linux/UNIX 机器上都可用并预配置,而 zsh 尚不存在。
    猜你喜欢
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 2014-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多