添加测试代码

This commit is contained in:
zpc 2024-06-25 13:02:32 +08:00
parent 3007c9f649
commit c098f51152
2 changed files with 96 additions and 0 deletions

View File

@ -0,0 +1,73 @@
using System.Diagnostics;
namespace CodeRelease.BLL
{
/// <summary>
/// 执行命令
/// </summary>
public class LinuxExecuteCommand
{
/// <summary>
/// 执行命令
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
public async Task<object> 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 };
}
}
}

View File

@ -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
{
/// <summary>
/// 测试
/// </summary>
/// <returns></returns>
public async Task<object> Test()
{
LinuxExecuteCommand linuxExecuteCommand = new LinuxExecuteCommand();
var obj = await linuxExecuteCommand.ExecuteCommand("");
return obj;
}
}
}