Working with SSH and Ruby

From PeformIQ Upgrade
Revision as of 13:42, 30 July 2012 by PeterHarding (talk | contribs) (Created page with "=Links= * http://net-ssh.rubyforge.org/ssh/v2/api/index.html * http://joeandmotorboat.com/2008/10/13/ssh-and-ruby/ =Examples= ==One== <pre> require 'net/ssh/multi' Net:...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Links

Examples

One

require 'net/ssh/multi'

  Net::SSH::Multi.start do |session|
    # access servers via a gateway
    session.via 'gateway', 'gateway-user'

    # define the servers we want to use
    session.use 'user1@host1'
    session.use 'user2@host2'

    # define servers in groups for more granular access
    session.group :app do
      session.use 'user@app1'
      session.use 'user@app2'
    end

    # execute commands on all servers
    session.exec "uptime"

    # execute commands on a subset of servers
    session.with(:app).exec "hostname"

    # run the aggregated event loop
    session.loop
  end

Two

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
}