2012-09-14 29 views
3

我的情况有点类似于“How to create a ssh tunnel in ruby and then connect to mysql server on the remote host”。在多个SSH隧道上运行MySQL查询?

从我的本地机器上,我想对生产MySQL数据库主机运行查询。 我的本地机器无法直接连接到数据库主机。但是,如果我通过SSH连接到网关机器,则可以运行MySQL客户机并连接到数据库主机。

我想弄清楚如何以编程方式从我的机器运行查询转发到网关机器,该机器将其转发到数据库服务器,并返回结果。基本上我想要有LOCAL => GATEWAY => DB_HOST转发。

我有一个hacky解决方案,在命令行上运行ssh.exec和MySQL,如下所示,但是,我试图找到一种端口转发两次的方法。 我试过了,但迄今为止还没有成功。

require 'rubygems' 
require 'mysql2' 
require 'net/ssh/gateway' 

gateway = Net::SSH::Gateway.new(
    $gateway_host, $gateway_user,:password => $gateway_pass) 

# This works 
ssh = gateway.ssh($db_host, $db_login_user) 
data = ssh.exec!("mysql -u#{$db_user} -p#{$db_pass} #{$db_name} -e '#{$sql_query}'") 
puts "#{data.class} is the class type" 
puts data 

# Want to do something like this with port forwarding 
# client = Mysql2::Client.new(:host => $db_host, 
#       :username => $db_user, 
#       :password => $db_pass, 
#       :database => $db_name, 
#       :port => port) 
# results = client.query($sql_query) 

puts "end stuff" 
ssh.close 

有什么建议吗?

回答

0

你的图很好地展示了,你需要一个从网关到Db_Host的隧道;以及从本地机器到网关的第二条隧道。这两个通道将通过网关有效地将本地计算机连接到db_host。

下面是tunneling MySQL over SSH的参考文件