- 首先,在ASP.Net Core的Startup.cs文件中,注册SSH客户端服务:
services.AddTransient();
- 在创建SSH客户端的类SshClient.cs中,实现ISshClient接口:
public interface ISshClient
{
string ExecuteCommand(string host, string user, string password, int port, string command);
}
public class SshClient : ISshClient
{
public string ExecuteCommand(string host, string user, string password, int port, string command)
{
using (var client = new SshClient(host, port, user, password))
{
client.Connect();
var result = client.RunCommand(command);
return result.Result;
}
}
}
- 在Controller中,注入ISshClient:
private readonly ISshClient _sshClient;
public MyController(ISshClient sshClient)
{
_sshClient = sshClient;
}
public IActionResult Index()
{
var result = _sshClient.ExecuteCommand("host", "user", "password", 22, "ls -la");
//处理结果
return View();
}