ASP.NET Core如何执行Linux shell命令?

15

我在Linux上有一个ASP.NET Core Web应用程序。我想执行shell命令并获取命令的结果。

是否有一种方法可以从ASP.NET Core应用程序内部执行Linux shell命令并将值返回到变量中?


1
Process.Execute? - Lex Li
1个回答

13
string RunCommand(string command, string args)
{
    var process = new Process()
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = command,
            Arguments = args,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true,
        }
    };
    process.Start();
    string output = process.StandardOutput.ReadToEnd();
    string error = process.StandardError.ReadToEnd();
    process.WaitForExit();

    if (string.IsNullOrEmpty(error)) { return output; }
    else { return error; }
}

// ...

string rez = RunCommand("date", string.Empty);

我还想添加一种方法来判断返回的字符串是错误的还是正常的输出(返回Tuple<bool, string>或抛出异常,并将error作为消息)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接