I'm trying to run commands remotely with ruby's net ssh. I need the output as well as the exit code. There are other stackoverflow threads on this topic but the accepted solutions do not work. Some people suggested using net-ssh-shell gem but as I tried it, I got an error saying that this package is in conflict with the version of my net-ssh package... Here is what I have:
Net::SSH.start(remote_ip, username,:keys => [ssh_key_path], :verbose => :debug) do |ssh|
cmd = "blah bla"
result = ssh.exec!(cmd)
puts result
end
It works but it does not raise an exception if it fails. I've also tried using the channel to retrieve the exit code but it always returns 0:
channel.on_request("exit-status") do |ch,data|
exit_code = data.read_long
end
Please help me out. I've already tried several things based on wrong info on the internet.
If you are using Ruby 1.9+ I would suggest
Open3.popen3
: