tags:

views:

296

answers:

3

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?

A: 

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!

Christoph Schiessl
No Unfortunately not, it didn't quite work! I have posted all the relevant code for anyone to test out! :P
chutsu
A: 

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
delano
Well I can't produce a interactive like prompt without the while loop though. I managed to get output without quitting the program. I have just added "session.loop" or "session.wait" after "session.exec" with the while loop. This seems to work! However I am encountering another problem. Lets say I have successfully connected to a few servers, and I type in "mkdir foo", it returns errors like foo already exists or foo not found.... weird...
chutsu
A: 

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.
chutsu