Net::openssh - how to get process exit status?

Hi,

I am using net-ssh 2.0.1. I have not been able to figure out how to get
the exit value from a remotely executed process. In the only examples I
could find, only the stdout was returned, like this one:

Net::SSH.start(host, username, :password => password) do |ssh|
print ssh.exec!(“hostname”)
end

I would like to check to see if the remote command returns a non-zero
value to indicate failure.

Thanks,

Ryan

On Sep 26, 2008, at 1:46 PM, Ryan Grow wrote:

I am using net-ssh 2.0.1. I have not been able to figure out how to
get
the exit value from a remotely executed process. In the only
examples I
could find, only the stdout was returned, like this one:

Net::SSH.start(host, username, :password => password) do |ssh|
print ssh.exec!(“hostname”)
end

If you want the process exit status, you have to forgo the ssh.exec!()
convenience method and work at a lower level. Here’s how to do it:

 ssh.open_channel do |channel|
   channel.exec(command) do |ch, success|
     unless success
       abort "FAILED: couldn't execute command (ssh.channel.exec

failure)"
end

     channel.on_data do |ch, data|  # stdout
       print data
     end

     channel.on_extended_data do |ch, type, data|
       next unless type == 1  # only handle stderr
       $stderr.print data
     end

     channel.on_request("exit-status") do |ch, data|
       exit_code = data.read_long
       if exit_code > 0
         puts "ERROR: exit code #{exit_code}"
       else
         puts "success"
       end
     end

     channel.on_request("exit-signal") do |ch, data|
       puts "SIGNAL: #{data.read_long}"
     end
   end
 end
 ssh.loop

–Young