1

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.