April 19, 2011

Posted by John

Tagged ruby and ssh

Older: Hi My Name is John...

Newer: EventMachine and Passenger

SSH Tunneling in Ruby

The other day I wanted to do some queries in production, but our servers are pretty locked down to the outside world. I was well aware that I could just make an ssh tunnel to connect to the database server, but I decided I wanted to do it in Ruby.

I am not the brightest of crayons in the box, so it took me a bit. Since I struggled with it for a few, I figured others probably will someday as well and decided to post my solution here.

Obviously, replace the strings with <…> with your own information and change the host port information in the gateway.open call.

require 'net/ssh/gateway'

gateway = Net::SSH::Gateway.new('<myremotehostorip.com>', '<remote_user>')

# Open port 27018 to forward to 127.0.0.1:27017
# on the remote host provided above
gateway.open('127.0.0.1', 27017, 27018)

# Connect to local port set in previous statement
conn = Mongo::Connection.new('127.0.0.1', 27018)

# Just printing out stats to show that it works
puts conn.db('<database_name>').stats.inspect

gateway.shutdown!

With just a few lines of Ruby, I can make scripts that use my local ssh key to talk to production. Thanks go to Jamis Buck for all the heavy lifting of writing net-ssh and company.

4 Comments

  1. This is a really useful bit John! Thanks to you and to Jamis for sharing your talents.

  2. Very nice, thanks for the snippet!

  3. This is the sort of thing that capistrano is good at…

  4. Anko Painting Anko Painting

    Apr 19, 2011

    I had a solution like this setup at work, but I found it to lock up occasionally. I tried debugging net::ssh::gateway, but to no avail. Now I just use the ssh client to tunnel and I don’t get any lockups.

Sorry, comments are closed for this article to ease the burden of pruning spam.

About

Authored by John Nunemaker (Noo-neh-maker), a programmer who has fallen deeply in love with Ruby. Learn More.

Projects

Flipper
Release your software more often with fewer problems.
Flip your features.