Difference between revisions of "Working with SSH and Ruby"

From PeformIQ Upgrade
Jump to navigation Jump to search
(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:...")
 
 
(3 intermediate revisions by the same user not shown)
Line 3: Line 3:
* http://net-ssh.rubyforge.org/ssh/v2/api/index.html
* http://net-ssh.rubyforge.org/ssh/v2/api/index.html
* http://joeandmotorboat.com/2008/10/13/ssh-and-ruby/
* http://joeandmotorboat.com/2008/10/13/ssh-and-ruby/
* http://ruby.about.com/od/networking/qt/netssh.htm
* http://www.rubyinside.com/how-to-transfer-files-using-ssh-and-ruby-512.html
* http://www.infoq.com/articles/ruby-file-upload-ssh-intro


=Examples=
=Examples=
Line 61: Line 66:
     end
     end
}
}
</pre>
==Three==
<pre>
#!/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
</pre>
==Four==
<pre>
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
</pre>
</pre>




[[Category:Ruby]]
[[Category:Ruby]]

Latest revision as of 13:47, 30 July 2012

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
}

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