通过多个SSH隧道运行MySQL查询?

时间:2012-09-14 00:43:27

标签: ruby ssh net-ssh

我的情况有点类似于“How to create a ssh tunnel in ruby and then connect to mysql server on the remote host”。

从我的本地计算机,我想对生产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

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

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

以下是tunneling MySQL over SSH

的具体参考
相关问题