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.