2012-07-12 55 views
1

因此,这里是我的设置:多个SSH与净啤酒花:: SSH(红宝石)

笔记本电脑 - >主机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文件,它会自动路由我通过主机1和主机2,当我尝试连接到笔记本电脑,从主机3。

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

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

这是可能的与净/ 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输入的连接,并在陷阱块I删除配置文件和关闭的连接。