26
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

RubyでSSHトンネル経由でサーバにアクセスする

net-ssh-gatewayを使うと簡単にできる。

例えば gateway.host を経由して database.host 上で動くMySQLにアクセスするには以下のように書けばいい。

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

# gateway.host  : 踏み台サーバ。1111ポートでSSHできるとする
# database.host : データベースサーバ。アクセスするには踏み台を経由する必要がある

gateway = Net::SSH::Gateway.new(
  'gateway.host',
  'username',
  port: 1111,
  keys: ['~/.ssh/ssh-key']
)

gateway.open('database.host', 3306) do |local_port|

  client = Mysql2::Client.new(
    # 127.0.0.1:local_port に
    # gatewa.host:1111->database.host:3306 というトンネルが作られている
    host: '127.0.0.1',
    port: local_port,

    username: 'username',
    password: 'password',
    database: 'database'
  )

  client.query('SHOW TABLES;').each do |row|
    p row
  end
end
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
26
Help us understand the problem. What are the problem?