首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Net::SSH的多个SSH跃点(Ruby)

使用Net::SSH的多个SSH跃点(Ruby)
EN

Stack Overflow用户
提问于 2012-07-13 00:46:54
回答 1查看 1.6K关注 0票数 1

下面是我的设置:

Laptop ->主机1 ->主机2 ->主机3

笔记本电脑可以访问主机1,但不能访问主机2或主机3

主机1可以访问主机2,但不能访问主机3

主机3可以访问主机2,但不能访问主机1

我正在尝试做的是设置远程转发,以便在主机3上运行的进程将被路由到在笔记本电脑上运行的服务。我已经使用下面的代码成功地完成了这项工作:

从笔记本电脑运行:

代码语言:javascript
复制
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的本地转发。

从笔记本电脑连接到Host 3的唯一方法是使用我的.ssh/config文件,当我尝试从笔记本电脑连接到Host 3时,该文件会自动通过Host 1和Host 2路由我。

我想要做的是剪掉从笔记本电脑连接到主机3的第二个线程,这样我就可以删除对.ssh/config文件的依赖。我想从第一线程中进行所有的连接。

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

这可以用net/ssh实现吗?

谢谢你的帮忙!

EN

回答 1

Stack Overflow用户

发布于 2012-07-18 22:24:01

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

示例:

代码语言:javascript
复制
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

我将连接包装在begin/rescue阻塞和捕获的ctrl+c输入中,并在陷阱块中删除配置文件并关闭连接。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11456657

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档