ruby使用Net::SSH.start抛出异常处理

ruby中使用Net::SSH.start,当输入的用户名或密码等出错,如果不做处理,会卡死,另外发现日志中会打印3次输入密码的提示,这里可以把交互给去了,另外捕捉异常。可以通过以下方式实现。

      begin

        Net::SSH.start(ip,username,:password => password,:timeout => 10, :non_interactive=>true) do |ssh|

          # output = ssh.exec!("hostname")

          # puts output

        end

      rescue Timeout::Error

        @result = "  Timed out"

      rescue Errno::EHOSTUNREACH

        @result = "  Host unreachable"

      rescue Errno::ECONNREFUSED

        @result = "  Connection refused"

      rescue Net::SSH::AuthenticationFailed

        @result = "  Authentication failure"

      end

1)加入non_interactive=>true该参数可以去除交互。

2)以下用于捕捉异常

rescue Timeout::Error

  @result = "  Timed out"

rescue Errno::EHOSTUNREACH

  @result = "  Host unreachable"

rescue Errno::ECONNREFUSED

  @result = "  Connection refused"

rescue Net::SSH::AuthenticationFailed

  @result = "  Authentication failure"

end



PS

下方是我个人订阅号,会一直更新各类技术文章,欢迎关注  :)