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

后端 未结 3 2116
囚心锁ツ
囚心锁ツ 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:21

    I find the following way of running processes with Net::SSH much more useful. It provides you with distinct stdout and stderr, exit code and exit signal.

    require 'rubygems'
    require 'net/ssh'
    require 'etc'
    
    server = 'localhost'
    
    def ssh_exec!(ssh, command)
      stdout_data = ""
      stderr_data = ""
      exit_code = nil
      exit_signal = nil
      ssh.open_channel do |channel|
        channel.exec(command) do |ch, success|
          unless success
            abort "FAILED: couldn't execute command (ssh.channel.exec)"
          end
          channel.on_data do |ch,data|
            stdout_data+=data
          end
    
          channel.on_extended_data do |ch,type,data|
            stderr_data+=data
          end
    
          channel.on_request("exit-status") do |ch,data|
            exit_code = data.read_long
          end
    
          channel.on_request("exit-signal") do |ch, data|
            exit_signal = data.read_long
          end
        end
      end
      ssh.loop
      [stdout_data, stderr_data, exit_code, exit_signal]
    end
    
    Net::SSH.start(server, Etc.getlogin) do |ssh|
      puts ssh_exec!(ssh, "true").inspect
      # => ["", "", 0, nil]
    
      puts ssh_exec!(ssh, "false").inspect  
      # => ["", "", 1, nil]
    
    end
    

    Hope this helps.

提交回复
热议问题