2016-09-27 09:32:39 -05:00
|
|
|
using System;
|
|
|
|
using System.IO;
|
|
|
|
using System.Text;
|
|
|
|
using System.Diagnostics;
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
|
|
|
namespace AniNIX.Shared {
|
|
|
|
|
|
|
|
public static class ExecuteCommand {
|
2016-09-27 10:34:16 -05:00
|
|
|
|
|
|
|
// Allow anyone using this class to modify the timeout at will.
|
|
|
|
public static int TimeOut = 5000;
|
2016-09-27 09:32:39 -05:00
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// This method allows a CSharp app to execute a command on the OS.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name=command>The command string to run as the string argument to "bash -c 'command'"</param>
|
|
|
|
/// <param name=input>The effective replacement for the command's stdin</param
|
|
|
|
/// <return>The stdout of the command</return>
|
|
|
|
/// </summary>
|
|
|
|
public static String Run(String command, String input) {
|
|
|
|
//Sanitize inputs.
|
2017-03-01 08:31:47 -06:00
|
|
|
|
|
|
|
command = command.Replace("\\'","'").Replace("'","\\'");
|
2016-09-27 09:32:39 -05:00
|
|
|
|
|
|
|
//Create process.
|
|
|
|
Process proc = new Process();
|
|
|
|
proc.StartInfo.CreateNoWindow = true;
|
|
|
|
proc.StartInfo.FileName = "/bin/bash";
|
|
|
|
proc.StartInfo.Arguments = String.Format("-c \'{0}\'",command);
|
|
|
|
proc.StartInfo.UseShellExecute=false;
|
2017-05-27 16:38:32 -05:00
|
|
|
ReportMessage.Log(Verbosity.VeryVerbose,String.Format("{0} {1}",proc.StartInfo.FileName,proc.StartInfo.Arguments));
|
2016-09-27 09:32:39 -05:00
|
|
|
|
|
|
|
//Redirect input
|
|
|
|
proc.StartInfo.RedirectStandardOutput=true;
|
|
|
|
proc.StartInfo.RedirectStandardInput=true;
|
|
|
|
|
|
|
|
//Start process
|
|
|
|
proc.Start();
|
|
|
|
|
|
|
|
//Add input and read output.
|
|
|
|
proc.StandardInput.Write(input);
|
|
|
|
proc.StandardInput.Close();
|
2016-09-27 10:34:16 -05:00
|
|
|
proc.WaitForExit(TimeOut);
|
|
|
|
if (!proc.HasExited) {
|
|
|
|
proc.Kill();
|
|
|
|
}
|
2016-09-27 09:32:39 -05:00
|
|
|
if (proc.ExitCode != 0) {
|
|
|
|
throw new Exception(String.Format("Failed to exit command with return code {0}",proc.ExitCode));
|
|
|
|
}
|
|
|
|
String stdoutString = proc.StandardOutput.ReadToEnd();
|
|
|
|
|
|
|
|
//Close up and return
|
|
|
|
proc.Close();
|
|
|
|
return stdoutString;
|
|
|
|
}
|
|
|
|
|
|
|
|
//Add polymorphism to allow no stdin
|
|
|
|
public static String Run(String command) {
|
|
|
|
return Run(command,null);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|