Reputation: 325
I am absolutely new to ASP.NET Core.
I want to send a GET-Request to my Linux server which is hosting my ASP.NET Core API to execute some bash commands and return the given output in my GET-Response.
I found a similar question: ASP.NET Core execute Linux shell command but I am not sure if the answer is really the solution for my problem neither how to use this package.
Is there a solution for this like:
[HttpGet]
public async Task<ActionResult<IEnumerable<TodoItem>>> GetTodoItems()
{
bashOutput = BASHCOMMAND(whoami);
return await bashOutput;
}
Or is there may a better way to execute commands on my linux server and return the value via API? It doesn't have to be ASP.NET Core.
Upvotes: 0
Views: 1306
Reputation: 60
Try this
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";
}
Upvotes: 1