user1418018
user1418018

Reputation: 189

Not getting output / result of an SSH command

I am connecting to a server, want to run a command and print the output. Here's the code:

def log_in
  Net::SSH.start('hostname', 'username', :password => "password") do |ssh|
    ssh.open_channel do |channel|
      output = channel.exec "ls" do |ch, success, data|
        if success then
          alert "Result: #{output} #{success} #{data}"
        end
      end
    end
  end
end

The result is "output" being an empty list [], "success" being true and "data" being empty. Obviously, this shouldn't be the case, as when I am logged in through the terminal and hit the "ls" command, there are several files / folders listed. Where's my mistake?

Interestingly enough, if I send gibberish as a command, e.g. instead of "ls", I send "asdfgh", it returns the same ([], true, empty). Using Shoes / Ruby.

Upvotes: 1

Views: 697

Answers (2)

user1418018
user1418018

Reputation: 189

This works:

Net::SSH.start('hostname', username, :password => password) do |ssh|
  ssh.open_channel do |channel|
    output = channel.exec "ls" do |ch, success, data|
      if success then
        channel.on_data do |ch, data|
            alert "#{data}"
        end
      end
    end
  end
  ssh.loop
end

Issue was, there exists a welcome message upon logging in (and the first line of it is blank). The "ssh.loop" allows to go through all the lines of welcome message and, finally, to the result of the "ls" command.

Upvotes: 1

mic4ael
mic4ael

Reputation: 8290

Take a look at the docs. The block you are passing as the second argument to the exec method expects only two arguments ch and success. You need to make sure you add a callback which fires once the data is available. For example:

channel.on_data do |ch, data|
  puts "got stdout: #{data}"
end

You can also use ssh.exec method.

Upvotes: 1

Related Questions