How to create a ssh tunnel in ruby and then connect to mysql server on the remote host

前端 未结 5 1403
有刺的猬
有刺的猬 2020-12-12 20:56

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:

5条回答
  •  旧巷少年郎
    2020-12-12 21:43

    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
    

提交回复
热议问题