25
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2015-06-24

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
25
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?