In an earlier blog I wrote about a tiny hello world script. Now I want to raise the bar a little bit, by creating a ping script. After a quick search on the internet I found a several kinds of scripts. Each having their own maturity an complexity level. A script like this is convenient addition when setting up a lab. In case you need to check connectivity time and time again.
In this script we ping a number predefined host. If three consecutive pings get a reply than pinging this host is successful.
Lets start coding;
Create a script on the flash drive
puts [ open "flash:pingbulk.tcl" w+ ] {
Define the IP addresses we want to ping. Pay attention: this is static list.
foreach ip { 1.1.1.1 2.2.2.2 } {
Now the three consecutive ping logic will go here…
If a regexp find “!!!” than the ping is successful.
if { [regexp "(!!!)" [exec "ping $ip timeout 1" ]] } { puts "$ip" } else { puts "$ip **** failed ***" } } }
As some habits die hard, we create an alias called pingbulk.
Once the alias is executed we see the following result;
R1#pingbulk 1.1.1.1 2.2.2.2 **** failed *** R1#
Entirely as expected; ip address 1.1.1.1 is assigned to the loopback0 interface.
Ip address 2.2.2.2 is assigned anywhere nor is the router connected to any network.nowhere to be found.
The complete script looks like;
puts [ open "flash:pingbulk.tcl" w+ ] { foreach ip { 1.1.1.1 2.2.2.2 } { if { [regexp "(!!!)" [exec "ping $ip timeout 1" ]] } { puts "$ip" } else { puts "$ip **** failed ***" } } }
Additional notes: Please take note of the accolade placement. TCL interprets on a per rule basis. If you type “puts [open “flash:file.tcl” w+ ]” than only a file is opened and closed with the name nvram:file.tcl. Nothing is read or written to and from this file.
Same applies to other constructs like “foreach” “if/else” etc…. Another nice addition would be to use the “ip host” statements present in the config. Making the scripts more dynamic.