ShellUtil.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System.Diagnostics;
  2. namespace Admin.NET.Core
  3. {
  4. /// <summary>
  5. /// 系统Shell命令
  6. /// </summary>
  7. public class ShellUtil
  8. {
  9. /// <summary>
  10. /// Bash命令
  11. /// </summary>
  12. /// <param name="command"></param>
  13. /// <returns></returns>
  14. public static string Bash(string command)
  15. {
  16. var escapedArgs = command.Replace("\"", "\\\"");
  17. var process = new Process()
  18. {
  19. StartInfo = new ProcessStartInfo
  20. {
  21. FileName = "/bin/bash",
  22. Arguments = $"-c \"{escapedArgs}\"",
  23. RedirectStandardOutput = true,
  24. UseShellExecute = false,
  25. CreateNoWindow = true,
  26. }
  27. };
  28. process.Start();
  29. string result = process.StandardOutput.ReadToEnd();
  30. process.WaitForExit();
  31. process.Dispose();
  32. return result;
  33. }
  34. /// <summary>
  35. /// cmd命令
  36. /// </summary>
  37. /// <param name="fileName"></param>
  38. /// <param name="args"></param>
  39. /// <returns></returns>
  40. public static string Cmd(string fileName, string args)
  41. {
  42. string output = string.Empty;
  43. var info = new ProcessStartInfo
  44. {
  45. FileName = fileName,
  46. Arguments = args,
  47. RedirectStandardOutput = true
  48. };
  49. using (var process = Process.Start(info))
  50. {
  51. output = process.StandardOutput.ReadToEnd();
  52. }
  53. return output;
  54. }
  55. }
  56. }