如果失败,Net / SSH.start不会引发异常

时间:2013-01-28 16:17:25

标签: ruby-on-rails ruby exception ssh net-ssh

我正在使用Net::SSH连接到另一台服务器。它工作正常,但我希望能够处理无法连接的情况。该方法的Documentation没有提及异常,只要我看到它不会引起任何异常。在以下示例中,传递不存在且没有键的主机和用户不会引发异常。

我可以检查它是否失败的唯一方法是查看@session,这将是零,但这并没有告诉我它失败的原因。

begin
  @session = Net::SSH.start('no-host', 'no-user', keys: [])
rescue SocketError => e
  connection_failed = true
  logger.error "SOCKET ERROR: "+e.message
rescue Net::SSH::AuthenticationFailed
  connection_failed = true
  logger.error "AUTH ERROR: "+e.message
rescue Exception => e
  logger.error "EXCEPTION: "+e.message
end

[更新]在irb中运行以下命令会引发SocketError:

> require 'net/ssh'
> Net::SSH.start('no-host', 'no-user', keys: [])
= SocketError: getaddrinfo: nodename nor servname provided, or not known

为什么这不会在我的应用中引发异常?

2 个答案:

答案 0 :(得分:3)

我正在尝试拯救一些例外,这对我有用:

def mydef
  begin
    Net::SSH.start("host", "user", :password => "password", :timeout => 10) do |ssh|
      #stuff
    end 
  rescue Timeout::Error
    @error = "  Timed out"
  rescue Errno::EHOSTUNREACH
    @error = "  Host unreachable"
  rescue Errno::ECONNREFUSED
    @error = "  Connection refused"
  rescue Net::SSH::AuthenticationFailed
    @error = "  Authentication failure"
  end
end

然后可能在视图中使用@error

答案 1 :(得分:2)

start()方法设置连接并将其输出到内部块。当你没有传递一个块时,就像在你的例子中一样,它可能连接都没有。你应该尝试做一个简单的循环或其他一些活动:

begin
  Net::SSH.start('no-host', 'no-user', keys: []) do |ssh|
    ssh.loop { true }
  end
rescue SocketError => e
  connection_failed = true
  logger.error "SOCKET ERROR: "+e.message
rescue Net::SSH::AuthenticationFailed
  connection_failed = true
  logger.error "AUTH ERROR: "+e.message
rescue Exception => e
  logger.error "EXCEPTION: "+e.message
end

此外,如果您担心错误处理和失败,则应通过:timeout参数指定连接超时。

相关问题