首页 > 解决方案 > ASP.NET Core API 在 Linux 服务器上执行 bash 命令

问题描述

我对 ASP.NET Core 完全陌生。

我想向托管我的 ASP.NET Core API 的 Linux 服务器发送一个 GET 请求,以执行一些 bash 命令并在我的 GET 响应中返回给定的输出。

我发现了一个类似的问题:ASP.NET Core 执行 Linux shell 命令,但我不确定答案是否真的是我的问题的解决方案,也不知道如何使用这个包。

有没有这样的解决方案:

[HttpGet]
public async Task<ActionResult<IEnumerable<TodoItem>>> GetTodoItems()
{
    bashOutput = BASHCOMMAND(whoami);
    return await bashOutput;
}  

或者是否有更好的方法在我的 linux 服务器上执行命令并通过 API 返回值?它不必是 ASP.NET Core。

标签: c#asp.netlinuxapiasp.net-core

解决方案


尝试这个

 public static string Run(string cmd, bool sudo = false)
    {
        try
        {
            var psi = new ProcessStartInfo
            {
                FileName = "/bin/bash",
                Arguments = (sudo ? "sudo " : "") + "-c '" + cmd + "'",
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true,
                RedirectStandardError = true,
                RedirectStandardInput = true,
            };

            Process proc = new Process() { StartInfo = psi, };
            proc.Start();
            string result = proc.StandardOutput.ReadToEnd();
            proc.WaitForExit();

            if (string.IsNullOrWhiteSpace(result))
            {
                Console.WriteLine("The Command '" + psi.Arguments + "' endet with exitcode: " + proc.ExitCode);
                return proc.ExitCode.ToString();
            }
            return result;
        }
        catch (Exception exc) 
        {
            Debug.WriteLine("Native Linux comand failed: " + cmd);
            Debug.WriteLine(exc.ToString()); 
        }

        return "-1";
    }

推荐阅读