Friday, August 27, 2010

Exception handling for Net::SSH

I'm writing a bit of Ruby automation code which requires me to connect to multiple servers using ssh and gather specific information from them using a loop like so:

hostList.each do |h|
  Net::SSH.start(h, "user", :password => "password", :timeout => 10) do |ssh|
  end
end


However, my test script kept dying at various points due to issues with the ssh connection to specific servers.

Naturally I thought of wrapping the Net::SSH.start call in a begin/rescue/end but couldn't for the life of me find any information about the exceptions that the start method could throw.  Finally after a bit of digging on google I came across this page which details them rather handily :-)  In short, here's how I have it wrapped now:

hostList.each do |h| 
  begin
    Net::SSH.start(h, "user", :password => "password", :timeout => 10) do |ssh|
    end 
  rescue Timeout::Error
    puts "  Timed out"
  rescue Errno::EHOSTUNREACH
    puts "  Host unreachable"
  rescue Errno::ECONNREFUSED
    puts "  Connection refused"
  rescue Net::SSH::AuthenticationFailed
    puts "  Authentication failure"
  end
end


This works fabulously since I don't really need to handle the exceptions but would like to know about them.

4 comments: