-->

Ruby script to telnet switch

2019-06-01 18:21发布

问题:

I've created the following ruby script that telnet to Cisco devices, that telnet to Cisco devices and run command 'show int status err'.

require 'net/telnet'

C3550_20_PterraEst = "192.168.244.20" #Enter the IP address here

USER = "user" #Enter username here

PASS = "password" #Enter password here

ENABLE = "password" #Enter enable password here

print "Selezionare il piano [0-1-2-All]: ";

# get the input from the console, 
val1 = gets;
tn = Net::Telnet::new("Host" => C3550_20_PterraEst,
"Timeout" => 5,
"Prompt" => /Username/ )
tn.cmd("\n#{USER}") 
tn.cmd(PASS) 
tn.cmd("sh int status err\n") { |c| print c }
exit

Now I want that those Cisco devices output (when I send 'show int status err') should be assigned to a variables inside my script...I explain better:

suppose that command 'show int status err' returns this value:

Int fa0/20 Int fa0/25

I want do something such as... variable1 = 'Int fa0/20,Int fa0/25' and later use variable1 inside my script.

In witch way can I do?

回答1:

I think what you want to do is not:

tn.cmd("sh int status err\n") { |c| print c }

but rather:

response = tn.cmd("sh int status err\n")

According to the docs on NET::Telnet, Telnet#cmd returns the response. If you pass it a block it also yields the response to the block, but if you want to store the response in a variable, my example is the best way to do that.

If you wanted to also print the response to STD out you should be able to do both, like this:

response = tn.cmd("sh int status err\n") { |c| print c }

However, if tn.cmd("sh int status err\n") { |c| print c } is giving you an error, my solution might not work until you figure out why it's producing an error. If you'd like help troubleshooting that, you should add it to the comments.

With all of that said, if you are hoping to have your script produce additional commands in response to the telnet response, you may want to look into using [expect][1].



回答2:

On this line tn.cmd("sh int status err\n") { |c| print c } c is the returned value from the command, but as it's a local variable it exists for that block. You can use an instance variable to contain it though, that'll allow you to use it outside the block.