在 C# 中通过 SSH.NET 进行多跳 SSH [英] Multi hop SSH through SSH.NET in C#

查看:29
本文介绍了在 C# 中通过 SSH.NET 进行多跳 SSH的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对一台 Linux 机器执行 SSH,然后又想从那里 SSH 连接到另一台 Linux 机器以执行一些 Perforce 任务.

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

其中 ssh 主机名无密码 ssh.如何控制第二个 SSH 会话并向其传递命令?

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

甚至探索了 CreateShell 函数,但似乎不建议将其用于自动化.

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

推荐答案

总的来说,尝试自动化 ssh 命令是一个糟糕的设计.

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

您最好使用端口转发(又名 SSH 隧道)来实现跳跃".

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

<小时>

在某些情况下,自动化 ssh 是可以接受的(虽然仍然不理想).例如.因为在第一个主机上设置了对第二个主机的身份验证.IE..ssh 文件夹中可能有私钥,您不能将该密钥传输到您的客户端计算机.


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.

无论如何,ssh 可以在其命令行上接受命令,例如:

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

command = ssh.CreateCommand("ssh hostname command");
result = command.Execute();
Console.WriteLine(result);

这篇关于在 C# 中通过 SSH.NET 进行多跳 SSH的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆