0

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.

2
  • Did you try the solution you find on the other link? What issues you are facing there? Commented Mar 21, 2020 at 15:11
  • @ChetanRanpariya I have no idea how to use this package Commented Mar 21, 2020 at 17:18

1 Answer 1

1

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";
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.