October 13, 2008

SSH and Ruby

The last couple days I have been a bit distracted from the Erlang stuff I have been doing lately and ended up some how playing with Ruby and the SSH library. For running commands on a bunch of machines at once it would work really well. Here’s some code I wrote and paraphrased from various sources.

require ‘rubygems’
require ‘net/ssh’

username=”yourusername”
hostnames=["node01","node02"]
script=”date;uptime;”

hostnames.each {|hostname|
Net::SSH.start( hostname, username ) do |session|
session.open_channel do |channel|
channel.on_data { |chan,output| puts “#{output.inspect}” }
channel.on_extended_data { |chan,type,output| print output }
channel.exec script
end
session.loop
end
}

This will run the commands contained in the script variable on the hosts in the hostnames array as the specified user. As it is currently it does not supply a password, so you’ll need keys setup. Adding your password is pretty simple, just check out the API here.

Leave a Comment

(required)

(will not be published) (required)