c# - 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。
解决方案
尝试这个
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";
}
推荐阅读
- python - use redis and mongo alongside postgres in docker
- java - Oozie 作业失败 Mapr 6.x
- css - Sass loop @import, a.scss need class on b.scss, b.scss need class on a.scss
- javascript - 这里通过 JavaScript 中的函数传递的事件是什么
- html - 输入字段中的清除/重置按钮 (x) 未显示
- python - Python 数据转换
- flutter - 将 toImage 与自定义小部件一起使用而不是 RenderRepaintBoundary?
- json - Yii 1.x 响应总是返回附加字符
- database - MS Access SQL If Row(n) = Row(n-1)
- python - Pandas 数据帧每列的计数值和新索引中的总和