using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace Hncore.Infrastructure.Common { public class ShellHelper { public static string Bash(string cmd) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { var escapedArgs = cmd.Replace("\"", "\\\""); var process = new Process() { StartInfo = new ProcessStartInfo { FileName = "/bin/bash", Arguments = $"-c \"{escapedArgs}\"", RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true } }; process.Start(); string result = process.StandardOutput.ReadToEnd(); process.WaitForExit(); return result; } return ""; } public static void RedirectOutputBash(string cmd) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { cmd = cmd.Replace("\"", "\\\""); Console.WriteLine("执行命令"); Console.WriteLine(cmd); var process = new Process() { StartInfo = new ProcessStartInfo { FileName = "/bin/bash", Arguments = $"-c \"{cmd}\"", RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true, } }; process.OutputDataReceived += (sender, args) => Console.WriteLine(args.Data); process.Start(); process.BeginOutputReadLine(); process.WaitForExit(); } } } }