【问题标题】:Multiple SSH hops with Net::SSH (Ruby)使用 Net::SSH (Ruby) 进行多个 SSH 跃点
【发布时间】:2012-07-12 16:46:53
【问题描述】:

这是我的设置:

笔记本电脑 -> 主机 1 -> 主机 2 -> 主机 3

笔记本电脑可以连接到主机 1,但不能连接到主机 2 或主机 3
主机 1 可以到达主机 2,但不能到达主机 3
主机 3 可以到达主机 2,但不能到达主机 1

我要做的是设置远程转发,以便将在主机 3 上运行的进程路由到笔记本电脑上正在运行的服务。我已使用以下代码成功完成此操作:

从笔记本电脑运行:

require 'rubygems'
require 'net/ssh'

threads = []
config = {:user => "user", :remote_port => 3333, :service_port => 2222}

threads << Thread.new{
Net::SSH.start("host1", config[:user]) do |ssh|
  puts "Forwarding port #{config[:remote_port]} on host1 to #{config[:service_port]} on localhost"
  ssh.forward.remote(config[:service_port], "localhost", config[:remote_port], "127.0.0.1")
  ssh.exec! "ssh #{config[:user]}@host2 -R #{config[:remote_port]}:localhost:#{config[:remote_port]}"
  ssh.loop {true}
end
}

threads << Thread.new{
Net::SSH.start("host3", config[:user]) do |ssh|
  puts "Creating local forward for port #{config[:service_port]} on host3 to port #{config[:remote_port]} on host2"
  ssh.exec! "ssh #{config[:user]}@host2 -L #{config[:service_port]}:localhost:#{config[:remote_port]}"
  ssh.loop {true}
end
}

threads.each {|t| t.join}

在一个线程中,我正在设置从笔记本电脑到主机 1 的远程转发,然后从主机 1 到主机 2 的另一个远程转发。在单独的线程中,我正在启动从笔记本电脑到主机 3 的另一个连接,然后运行从主机 3 到主机 2 的本地转发。

我可以从笔记本电脑连接到主机 3 的唯一方法是因为我的 .ssh/config 文件,当我尝试从笔记本电脑连接到主机 3 时,它会自动路由我通过主机 1 和主机 2。

我想要做的是切断我从笔记本电脑连接到主机 3 的第二个线程,以便我可以删除对 .ssh/config 文件的依赖。我想在第一个线程中完成所有连接。

所以基本上我需要做来自笔记本电脑的多个跃点。我可以启动从笔记本电脑到主机 1 的第一个连接,然后在主机 1 上执行命令,但之后我就无法再进一步了。我需要做的是启动从笔记本电脑到主机 1 的连接,在主机 1 上设置转发,从主机 1 连接到主机 2,然后在主机 2 上设置第二个转发。

这可能与net/ssh有关吗?

感谢您的帮助!

【问题讨论】:

    标签: ruby ssh portforwarding net-ssh


    【解决方案1】:

    我通过写出 SSH 配置文件,然后在启动连接时指定配置文件来解决此问题。配置文件包含代理命令,这些命令将自动通过必要的主机路由到我的目的地。

    例子:

    def write_config_file
    
        File.open('confi_file', 'w') { |f|
          f << "host host1\n"
          f << "HostName host1.something.net\n"
          f << "user user_name\n"
          f << "\n"
          f << "host host2\n"
          f << "HostName host2.something.net\n"
          f << "ProxyCommand ssh host1 nc %h %p 2> /dev/null\n"
          f << "user user_name\n"
          f << "\n"
          f << "host host3\n"
          f << "HostName host3.something.net\n"
          f << "ProxyCommand ssh host2 nc %h %p 2> /dev/null\n"
          f << "user user_name\n"
        } 
    
    end
    
    write_config_file
    
    Net::SSH.start("host3", "user_name", :config => './config_file') do |ssh|
      #whatever you need to do...
    end
    

    我将连接包裹在一个开始/救援阻塞和捕获的 ctrl+c 输入中,并在陷阱块中删除配置文件并关闭连接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 2012-03-24
      • 1970-01-01
      • 2016-02-02
      • 1970-01-01
      • 2019-12-20
      相关资源
      最近更新 更多