diff --git a/src/CodeRelease/CodeRelease/BLL/LinuxExecuteCommand.cs b/src/CodeRelease/CodeRelease/BLL/LinuxExecuteCommand.cs new file mode 100644 index 0000000..403b2b0 --- /dev/null +++ b/src/CodeRelease/CodeRelease/BLL/LinuxExecuteCommand.cs @@ -0,0 +1,73 @@ +using System.Diagnostics; + +namespace CodeRelease.BLL +{ + /// + /// 执行命令 + /// + public class LinuxExecuteCommand + { + /// + /// 执行命令 + /// + /// + /// + public async Task ExecuteCommand(string command) + { + string outputDataReceived = ""; + string errorDataReceived = ""; + int exitCode = 0; + try + { + // 创建一个新的进程 + using (Process process = new Process()) + { + process.StartInfo.FileName = "/bin/bash"; // 使用 bash + process.StartInfo.Arguments = $"-c \"{command}\""; // 传递的命令 + process.StartInfo.RedirectStandardOutput = true; // 重定向标准输出 + process.StartInfo.RedirectStandardError = true; // 重定向标准错误 + process.StartInfo.UseShellExecute = false; // 不使用shell + process.StartInfo.CreateNoWindow = true; // 不创建窗口 + + // 绑定输出和错误数据接收事件 + process.OutputDataReceived += new DataReceivedEventHandler((sender, e) => + { + if (!string.IsNullOrEmpty(e.Data)) + { + Console.WriteLine($"Output: {e.Data}"); + outputDataReceived = e.Data; + } + }); + + process.ErrorDataReceived += new DataReceivedEventHandler((sender, e) => + { + if (!string.IsNullOrEmpty(e.Data)) + { + Console.WriteLine($"Error: {e.Data}"); + errorDataReceived = e.Data; + } + }); + + // 启动进程 + process.Start(); + + // 开始异步读取输出和错误流 + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + + // 等待进程退出 + await process.WaitForExitAsync(); + + // 输出退出代码 + Console.WriteLine($"Process exited with code {process.ExitCode}"); + exitCode = process.ExitCode; + } + } + catch (Exception ex) + { + Console.WriteLine($"Exception: {ex.Message}"); + } + return new { exitCode, outputDataReceived, errorDataReceived }; + } + } +} diff --git a/src/CodeRelease/CodeRelease/Controllers/PublishController.cs b/src/CodeRelease/CodeRelease/Controllers/PublishController.cs new file mode 100644 index 0000000..9979842 --- /dev/null +++ b/src/CodeRelease/CodeRelease/Controllers/PublishController.cs @@ -0,0 +1,23 @@ +using CodeRelease.BLL; + +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; + +namespace CodeRelease.Controllers +{ + [Route("api/[controller]/[Action]")] + [ApiController] + public class PublishController : ControllerBase + { + /// + /// 测试 + /// + /// + public async Task Test() + { + LinuxExecuteCommand linuxExecuteCommand = new LinuxExecuteCommand(); + var obj = await linuxExecuteCommand.ExecuteCommand(""); + return obj; + } + } +}