Module: Net::SSH::Multi::SessionActions
- Defined in:
- lib/cute/net-ssh.rb
Instance Method Summary collapse
-
#exec!(command, &block) ⇒ Hash
Monkey patch that adds the exec! method.
Instance Method Details
#exec!(command, &block) ⇒ Hash
Monkey patch that adds the exec! method. It executes a command on multiple hosts capturing their associated output (stdout, stderr and status). It blocks until the command finishes returning the resulting output as a Hash. It uses a logger for debugging purposes.
Example
session.exec!("date") #=> {"node3"=>{:stdout=>"Wed Mar 11 12:38:11 UTC 2015", :status=>0},
# "node1"=>{:stdout=>"Wed Mar 11 12:38:11 UTC 2015", :status=>0}, ...}
session.exec!("cmd") #=> {"node4"=>{:stderr=>"bash: cmd: command not found", :status=>127},
# "node3"=>{:stderr=>"bash: cmd: command not found", :status=>127}, ...}
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
# File 'lib/cute/net-ssh.rb', line 92 def exec!(command, &block) results = {} main =open_channel do |channel| channel.exec(command) do |ch, success| raise "could not execute command: #{command.inspect} (#{ch[:host]})" unless success Multi.logger.debug("Executing #{command} on [#{ch.connection.host}]") results[ch.connection.host] ||= {} channel.on_data do |ch, data| if block block.call(ch, :stdout, data) else results[ch.connection.host][:stdout] = data.strip Multi.logger.debug("[#{ch.connection.host}] #{data.strip}") end end channel.on_extended_data do |ch, type, data| if block block.call(ch, :stderr, data) else results[ch.connection.host][:stderr] = data.strip Multi.logger.debug("[#{ch.connection.host}] #{data.strip}") end end channel.on_request("exit-status") do |ch, data| ch[:exit_status] = data.read_long results[ch.connection.host][:status] = ch[:exit_status] if ch[:exit_status] != 0 Multi.logger.info("execution of '#{command}' on #{ch.connection.host} failed with return status #{ch[:exit_status].to_s}") if results[ch.connection.host][:stdout] Multi.logger.info("--- stdout dump ---") Multi.logger.info(results[ch.connection.host][:stdout]) end if results[ch.connection.host][:stderr] Multi.logger.info("--stderr dump ---") Multi.logger.info(results[ch.connection.host][:stderr]) end end end # need to decide severity level if the command fails end end main.wait # we have to wait the channel otherwise we will have void results return results end |