如何在ruby中创建ssh隧道,然后连接到远程主机上的mysql服务器 [英] How to create a ssh tunnel in ruby and then connect to mysql server on the remote host
问题描述
我想创建一个ruby脚本,可以通过ssh隧道在远程服务器上运行mysql命令.
I would like to create a ruby script that I can run mysql commands on a remote server through a ssh tunnel.
现在我有一个手动过程可以做到这一点:
Right now I have a manual process to do this:
- 创建隧道-> ssh -L 3307:127.0.0.1:3306
- 运行ruby脚本.
- 关闭隧道.
我希望能够实现此自动化,因此我可以运行脚本.
I would love to be able to automate this so I can just run the script.
示例:
require 'rubygems'
require 'net/ssh/gateway'
require 'mysql'
#make the ssh connection -> I don't think I am doing this right.
Net::SSH.start('server','user') do |session|
session.forward.local(3307,'127.0.0.1', 3306)<br>
mysql = Mysql.connect("127.0.0.1","root","","",3307)
dbs = mysql.list_dbs<br>
dbs.each do |db|<br>
puts db <br>
end
session.loop(0){true}<br>
end
更新-2010-11-10:
我真的很喜欢以下代码:
An update - 2010-11-10:
I'm really close with this code:
require 'rubygems'
require 'mysql'
require 'net/ssh/gateway'
gateway = Net::SSH::Gateway.new("host","user",{:verbose => :debug})
port = gateway.open("127.0.0.1",3306,3307)
# mysql = Mysql.connect("127.0.0.1","user","password","mysql",3307)
# puts "here"
# mysql.close
sleep(10)
gateway.close(port)
当它休眠时,我可以打开一个终端窗口并连接到远程主机上的mysql.这将验证隧道是否已创建并正常工作.
When its sleeping, I am able to open a terminal window and connect to mysql on the remote host. This verifies the tunnel is created and working.
现在的问题是,当我取消注释3行时,它只是挂起.
The problem now is when I uncomment the 3 lines, it just hangs.
推荐答案
我能够使用mysql2 gem在没有fork的情况下使它正常工作
I was able to get this to work without a fork using the mysql2 gem
require 'rubygems'
require 'mysql2'
require 'net/ssh/gateway'
gateway = Net::SSH::Gateway.new(
'remotehost.com',
'username'
)
port = gateway.open('127.0.0.1', 3306, 3307)
client = Mysql2::Client.new(
host: "127.0.0.1",
username: 'dbuser',
password: 'dbpass',
database: 'dbname',
port: port
)
results = client.query("SELECT * FROM projects")
results.each do |row|
p row
end
client.close
这篇关于如何在ruby中创建ssh隧道,然后连接到远程主机上的mysql服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!