Multi hop SSH through SSH.NET in C#

北城余情 提交于 2020-01-09 11:25:47

问题


I am doing SSH to a Linux machine and again from there want to SSH to another Linux machine to carry out few Perforce tasks.

using (SshClient ssh = new SshClient("ip address","username", "pwd"))
{
    ssh.Connect();
    command = ssh.CreateCommand("ssh hostname");
    result = command.Execute();
    Console.WriteLine(result);
}

Where the ssh hostname is a password less ssh. How can I control the second SSH session and pass commands to it?

Even explored the CreateShell function, but seems like it is not suggested for automation.


回答1:


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);


来源:https://stackoverflow.com/questions/48759639/multi-hop-ssh-through-ssh-net-in-c-sharp

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