telnetできなかった時の処理を書きたいのですが、telnetできなかった場合、
/usr/lib/ruby/1.8/net/telnet.rb:352:in `initialize': Connection refused - connect(2) (Errno::ECONNREFUSED)
from /usr/lib/ruby/1.8/net/telnet.rb:352:in `open'
from /usr/lib/ruby/1.8/net/telnet.rb:352:in `initialize'
from /usr/lib/ruby/1.8/timeout.rb:62:in `timeout' 以下略
のようなエラーで、プログラムが止まってしまいます。
もしくは、
/usr/lib/ruby/1.8/net/telnet.rb:557:in `waitfor': timed out while waiting for more data (Timeout::Error)
from /usr/lib/ruby/1.8/net/telnet.rb:742:in `login'
from telnet-test-test01.rb:13
のようなエラーです。(これは恐らくユーザ名とパスワードのミス)
if (telnetに失敗した場合)
print "telnetできませんでした"
end
のような処理を書くやり方を教えて下さい。
ちなみに Net::Telnet は現在以下のような書き方をしています。
telnet = Net::Telnet.new("Host" => "192.168.1.1") {|c| print c}
telnet.login("username", "password") {|c| print c}
よろしくお願い致します。
begin/rescueでエラーハンドリングします。
begin telnet = Net::Telnet.new("Host" => "192.168.1.1") {|c| print c} telnet.login("username", "password") {|c| print c} rescue Errno::ECONNREFUSED # ここでエラー処理 end
if (telnetに失敗した場合) print "telnetできませんでした" end
としたい場合は上記のbegin/rescueを関数内に収め、rescueでfalseを返す物を作れば良いかと思います。
begin/rescueでエラーハンドリングします。
begin telnet = Net::Telnet.new("Host" => "192.168.1.1") {|c| print c} telnet.login("username", "password") {|c| print c} rescue Errno::ECONNREFUSED # ここでエラー処理 end
if (telnetに失敗した場合) print "telnetできませんでした" end
としたい場合は上記のbegin/rescueを関数内に収め、rescueでfalseを返す物を作れば良いかと思います。
例外処理で書くのが普通かな。
begin telnet = Net::Telnet.new("Host" => "192.168.1.1") {|c| print c} telnet.login("username", "password") {|c| print c} rescue print "Failed\n" end
ありがとうございます!
大変助かります。