Find DrewDahl on Facebook! Find DrewDahl on Twitter! View Andrew Dahl's Profile Drew's Blog

Archive for February, 2011

Using Ruby to run commands on a lab of Linux machines

by Drew Dahl on Feb.24, 2011, under Linux, Programming

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 Comments :, , , , , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!