如何在 ruby​​ 中创建 ssh 隧道,然后连接到远程主机上的 mysql 服务器

2021-12-23 00:00:00 ssh ruby mysql

我想创建一个 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:

  1. 创建隧道 -> ssh -L 3307:127.0.0.1:3306
  2. 运行 ruby​​ 脚本.
  3. 关闭隧道.

我希望能够自动执行此操作,以便我可以运行脚本.

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

相关文章