C#实现远程ssh在linux执行命令后读取较多的输出内容,并检测输出结果和是否存在"发布成功"字段并返回
时间: 2024-09-25 20:06:38 浏览: 83
C# 利用Renci库来实现ssh客户端,可以执行ssh命令并获取返回结果
3星 · 编辑精心推荐
在C#中,使用SSH.NET库可以方便地执行远程Linux服务器上的命令,并读取大量输出。下面是一个示例,它展示了如何执行命令、捕获输出并检查结果是否存在特定字符串“发布成功”:
首先,需要安装SSH.NET库,通过NuGet包管理器添加引用:`Install-Package SSH.NET`
```csharp
using SSH.NET;
public class RemoteExecutionService
{
private readonly string _host;
private readonly int _port;
private readonly string _username;
private readonly string _password;
public RemoteExecutionService(string host, int port, string username, string password)
{
_host = host;
_port = port;
_username = username;
_password = password;
}
public async Task<(bool success, string output)> ExecuteAndCheckStatusAsync(string command, string expectedSuccessMessage)
{
try
{
using var client = new SSHClient(_host, _port);
await client.ConnectAsync();
using (var sftp = await client.CreateSftpSessionAsync())
{
using (var session = await sftp.OpenShellAsync())
{
using (var streamReader = new StreamReader(await session.ExecCommandAsync(command)))
{
string output = await streamReader.ReadToEndAsync(); // 读取所有输出
if (output.Contains(expectedSuccessMessage))
{
return (true, output);
}
else
{
return (false, "未找到 '发布成功' 字符串,输出为:" + output);
}
}
}
}
}
catch (Exception ex)
{
return (false, $"执行命令失败: {ex.Message}");
}
finally
{
await client.DisconnectAsync();
}
}
}
```
现在,你可以像这样使用这个服务:
```csharp
string remoteHost = "your_host";
int remotePort = your_port;
string remoteUser = "your_user";
string remotePass = "your_password";
RemoteExecutionService service = new RemoteExecutionService(remoteHost, remotePort, remoteUser, remotePass);
(async () =>
{
(bool result, string output) executionResult = await service.ExecuteAndCheckStatusAsync("your_long_running_command", "发布成功");
Console.WriteLine($"执行状态: {result}, 输出: {output}");
})();
```
阅读全文