Net::SSH::Multi using the session.exec, how do you get the output straight away? Ruby

StackOverflow https://stackoverflow.com/questions/1383282

  •  21-09-2019
  •  | 
  •  

Question

So I've been trying to use the Net::SSH::Multi to login to multiple machines using the via SSH, and then executing shell commands on the remote machines with session.exec("some_command").

The Code:

#!/usr/bin/ruby
require 'rubygems'
require 'net/ssh'
require 'net/ssh/multi'

Net::SSH::Multi.start do |session|
        # Connect to remote machines
        ### Change this!!###
        session.use 'user@server'

        loop = 1
        while loop == 1
                printf(">> ")
                command = gets.chomp
                if command == "quit" then
                        loop = 0
                else
                        session.exec(command)do |ch, stream, data|
                          puts "[#{ch[:host]} : #{stream}] #{data}"
                        end
                end
        end
end

The problem I have at the moment, is when I enter a command in the interactive prompt, the "session.exec" does not return the output util I quit the program, I was wondering if anyone has come across this problem and can tell me how I can go about solving this problem?

Was it helpful?

Solution

Adding session.loop after session.exec allows the program to wait for the output.

Such as:

session.exec(command)do |ch, stream, data|
  puts "[#{ch[:host]} : #{stream}] #{data}"
end

session.loop
# Or session.wait also does the same job.

OTHER TIPS

Take a look a here. The exec method seems to yield it's result to the supplied block.

Example from the documentation:

session.exec("command") do |ch, stream, data|
  puts "[#{ch[:host]} : #{stream}] #{data}"
end

Disclaimer: I didn't test this myself. It may work or not. Let us know when it works!

Remove the while loop and call session.loop after the call to exec. Something like this:

Net::SSH::Multi.start do |session|
  # Connect to remote machines
  ### Change this!!###
  session.use 'user@server'

  session.exec(command)do |ch, stream, data|
    puts "[#{ch[:host]} : #{stream}] #{data}"
  end

  # Tell Net::SSH to wait for output from the SSH server
  session.loop  
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top