How to get exit status with Ruby's Net::SSH library?

后端 未结 3 2089
囚心锁ツ
囚心锁ツ 2021-01-30 02:32

I have a snippet of code, simply trying to execute a script on a remote server, in the event that it fails, I\'d like to make a follow-up call, imagine this:

req         


        
3条回答
  •  星月不相逢
    2021-01-30 03:12

    Building on the answer by flitzwald - I've monkey patched my version of this into Net::SSH (Ruby 1.9+)

    class Net::SSH::Connection::Session
      class CommandFailed < StandardError
      end
    
      class CommandExecutionFailed < StandardError
      end
    
      def exec_sc!(command)
        stdout_data,stderr_data = "",""
        exit_code,exit_signal = nil,nil
        self.open_channel do |channel|
          channel.exec(command) do |_, success|
            raise CommandExecutionFailed, "Command \"#{command}\" was unable to execute" unless success
    
            channel.on_data do |_,data|
              stdout_data += data
            end
    
            channel.on_extended_data do |_,_,data|
              stderr_data += data
            end
    
            channel.on_request("exit-status") do |_,data|
              exit_code = data.read_long
            end
    
            channel.on_request("exit-signal") do |_, data|
              exit_signal = data.read_long
            end
          end
        end
        self.loop
    
        raise CommandFailed, "Command \"#{command}\" returned exit code #{exit_code}" unless exit_code == 0
    
        {
          stdout:stdout_data,
          stderr:stderr_data,
          exit_code:exit_code,
          exit_signal:exit_signal
        }
      end
    end
    

提交回复
热议问题