Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

.net - Multi hop SSH through SSH.NET in C#

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...