Working with SSH and Ruby
Revision as of 14:46, 30 July 2012 by PeterHarding (talk | contribs)
Links
- http://net-ssh.rubyforge.org/ssh/v2/api/index.html
- http://joeandmotorboat.com/2008/10/13/ssh-and-ruby/
- http://ruby.about.com/od/networking/qt/netssh.htm
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 }
Three
#!/usr/bin/env ruby require 'rubygems' require 'net/ssh' HOST = '192.168.1.113' USER = 'username' PASS = 'password' Net::SSH.start( HOST, USER, :password => PASS ) do|ssh| result = ssh.exec!('ls') puts result end
Four
require 'rubygems' require 'net/ssh' Net::SSH.start("host", "user", :password => "password") do |ssh| puts ssh.exec!("nohup ./script.sh > blah.log 2>&1 &") end