在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
下方是我個人訂閱號,會一直更新各類技術文章,歡迎關注 :)