Multi hop SSH through SSH.NET in C#

廉价感情. 提交于 2019-11-28 13:02:29

In general, trying to automate ssh command is a bad design.

You better use a port forwarding (aka SSH tunnel) to implement the "hop".

var firstClient =
    new SshClient(firstHostName, firstUserName, firstPassword);
firstClient.Connect();

var port = new ForwardedPortLocal("127.0.0.1", secondHostName, 22);
firstClient.AddForwardedPort(port);
port.Start();

var secondClient =
    new SshClient(port.BoundHost, (int)port.BoundPort, secondUserName, secondPassword);
secondClient.Connect();

var command = secondClient.CreateCommand("ls");
var result = command.Execute();
Console.WriteLine(result);

There are some cases, when automating the ssh is acceptable (while still not ideal). E.g. because there's an authentication to the second host set up on the first one. I.e. there might be private key in the .ssh folder and you are not allowed to transfer that key to your client machine.

Even then, try talking to the system Administrator to find a better solution. The private key is still accessible using the credentials contained in your application, so it's not protected any better, had the private key itself been contained directly in the application.

Anyway, ssh can accept a command on its command line, like:

command = ssh.CreateCommand("ssh hostname command");
result = command.Execute();
Console.WriteLine(result);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!