Ruby net-ssh-multi: passing a password as a parameter at runtime

我怕爱的太早我们不能终老 提交于 2019-12-08 00:04:17

问题


I am trying to use net-ssh-multi to run a command on a group of servers. For this taks, ssh-key authentication is not an option; a password has to be passed to each server defined in the session.use lines. Here's the problem, 'net/ssh' can take a password parameter, but 'net/ssh/multi' cannot. What I would like to do is somehting like this:

require 'net/ssh'
require 'net/ssh/multi'

#The necessary data is contained in a Ticket object 

my_ticket = Ticket.new

Net::SSH::Multi.start (:password => 'xxxx') do |session|

  # define the servers we want to use

   my_ticket.servers.each do |serv_id|
     session.use "#{my_ticket.user_name}@#{serv_id}"
   end


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


  # run the aggregated event loop
  session.loop
end

However, this get me:

file.rb:35:in `start': wrong number of arguments (1 for 2) (ArgumentError) from file.rb:35

I know this is a bit of a n00b question, but I would really appreciate some help.

(http://rubydoc.info/gems/net-ssh-multi/1.1/Net/SSH/Multi)


回答1:


Turns out the answer is far simpler than I thought it would be. Poring over the documentation, I noticed this in the Class: Net::SSH::Multi::Server docs:

Class: Net::SSH::Multi::Server

Overview:

Encapsulates the connection information for a single remote server, as well as the Net::SSH session corresponding to that information. You'll rarely need to instantiate one of these directly: instead, you should use Net::SSH::Multi::Session#use.'

So, no class extending or calls to super-classes are necessary. The above can be accomplished with:

require 'net/ssh'
require 'net/ssh/multi'


#The necessary data is contained in a Ticket object 
my_ticket = Ticket.new


Net::SSH::Multi.start do |session|


  # define the servers we want to use
  my_ticket.servers.each do |session_server|
    session.use session_server , :user =>  my_ticket.user_name ,  \
    :password => my_ticket.user_pass
  end


  # execute commands on all servers
  session.exec my_ticket.command_to_do

  # run the aggregated event loop
  session.loop
end


来源:https://stackoverflow.com/questions/6155372/ruby-net-ssh-multi-passing-a-password-as-a-parameter-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!