title: How to create a ssh tunnel in ruby and then connect to mysql server on the remote host
body: <p>I would like to create a ruby script that I can run mysql commands on a remote server through a ssh tunnel.  </p>
  
  <p>Right now I have a manual process to do this:</p>
  
  <ol>
  <li>Create a tunnel -> ssh -L 3307:127.0.0.1:3306 </li>
  <li>run ruby script.</li>
  <li>Close tunnel.</li>
  </ol>
  
  <p>I would love to be able to automate this so I can just run the script.</p>
  
  <p>example:</p>
  
  <pre><code>require 'rubygems'   
  require 'net/ssh/gateway'  
  require 'mysql'  
  
  
  #make the ssh connection -&gt; I don't think I am doing this right.
  
  Net::SSH.start('server','user') do |session|
  
    session.forward.local(3307,'127.0.0.1', 3306)&lt;br&gt;
    mysql = Mysql.connect("127.0.0.1","root","","",3307)
  
    dbs = mysql.list_dbs&lt;br&gt;
    dbs.each do |db|&lt;br&gt;
      puts db &lt;br&gt;
    end
  
    session.loop(0){true}&lt;br&gt;
  end
  </code></pre>
  
  <p>An update - 2010-11-10:<br>
  I'm really close with this code:</p>
  
  <pre><code>require 'rubygems'  
  require 'mysql'  
  require 'net/ssh/gateway'  
  
  gateway = Net::SSH::Gateway.new("host","user",{:verbose =&gt; :debug})
  port = gateway.open("127.0.0.1",3306,3307)
  
  #  mysql = Mysql.connect("127.0.0.1","user","password","mysql",3307)  
  #  puts "here"  
  #  mysql.close  
  
  sleep(10)  
  gateway.close(port)
  </code></pre>
  
  <p>When its sleeping, I am able to open a terminal window and connect to mysql on the remote host.  This verifies the tunnel is created and working.</p>
  
  <p>The problem now is when I uncomment the 3 lines, it just hangs. </p>