从 ASP.NET Core 3 应用程序执行 Linux Shell 命令

Gic*_*ica 2 c# linux shell asp.net-mvc asp.net-core

我的问题实际上是,如何从我的应用程序执行 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();
Run Code Online (Sandbox Code Playgroud)

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

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

Lex*_* Li 5

假设你想在 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);
Run Code Online (Sandbox Code Playgroud)

  • @MaximV.Pavlov 假设“bash”在大多数 Linux/UNIX 机器上可用并预配置,而“zsh”尚不存在。 (3认同)