Droo-Labs

the perspicacious ramblings of droo

Distributed Commands With Ruby

Lately, I’ve been getting acquainted with Rails development at work. It’s been a pretty steep learning curve (for that matter, I guess it still is), but I’ve enjoyed it thus far. So, with my new found Ruby skills (or, I guess more-so my new found need to learn Ruby), I wrote a script that uses SSH to iteratively connect to every computer in a lab and update them. This could be used for just about anything, but for my instance it was updating a lab. There was a bit more to my script as I needed to recompile some device drivers when there was a new kernel, but for simplicities sake, I’ve ripped them out. Hope this helps someone else!

First, you’ll need to install the ruby-ssh library.

sudo gem install net-ssh
sudo gem install highline

And, the script is:

#!/usr/bin/ruby

require 'rubygems'
require 'net/ssh'
require 'highline/import'

hosts=[ "host1",
            "host2" ]

cmds = ["yum -y update",
             "init 6"]

username = "root"

# Assuming that all hosts have the same password
password = ask("Enter Password: ") { |q| q.echo = false }

hosts.each do |host|
    Net::SSH.start( host , username, :password => password) do |ssh|
        puts "Connected to #{host}"
        cmds.each do |cmd|
            puts "Performing #{cmd} on #{host}"
            output = ssh.exec! cmd do |ch, stream, data|
                if stream == :stderr
                    puts "Error: #{data}"
                else
                    puts data
                end
            end
        end
    end
end

And, that’s all there is to it! There’s a real lack of comments, but I feel it’s pretty self-explanatory. Enjoy!

, , , , ,

2 thoughts on “Distributed Commands With Ruby

Leave a Reply to Alex Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>