I have the following code that attempts to connect to various hosts and move data. The problem is if one connection attempt fails then the code dies. How can I get it to move to the next host in the array.
h=%w"host1 host2 host3 host4"
h.each do |hostname|
tn = Net::Telnet::new("Host" => "#{hostname}",
"Timeout" => false,
"Prompt" => /[$%#>] \z/n)
tn.cmd('String' =>'user' , 'Match'=>/Password:/) { |c| puts c }
tn.cmd('String' =>'password', 'Match'=>/#/) { |c| puts c }
tn.cmd('String' =>"show run | redirect tftp://192.1.1.1/#{hostname}-#{tdate}.cfg", 'Match'=>/#/) { |c| puts c }
sleep(3)
end
You can continue beyond the first failed connection attempt by handling the exception raised by
Net::Telnet::initialize. You’ll find you aren’t getting the error you think you’re getting:Produces
That is, you’re not actually providing a host name. The argument isn’t called
"Host", it’s called"host", and case matters. Ruby options are also typically passed as symbols, not strings. Try this:Now you’ll get the error you were expecting: