Advanced Features : Script samples : TCL scripts : TCL loops
 
TCL loops
Even though the last script used a loop, that script’s main purpose was storing information in the array. The next script uses a loop to create a preset number of users on the FortiGate device, in this case 10 users. The output is only shown for the first two users due to space considerations.
To create 10 users from usr0001 to usr0010:
Script
#!
proc do_cmd {cmd} {
puts [exec "$cmd\n" "# " 15]
}
set num_users 10
do_cmd "config vdom"
do_cmd "edit root"
do_cmd "config user local"
for {set i 1} {$i <= $num_users} {incr i} {
set name [format "usr%04d" $i]
puts "Adding user: $name"
do_cmd "edit $name"
do_cmd "set status enable"
do_cmd "set type password"
do_cmd "next"
}
do_cmd "end"
do_cmd "end"
 
do_cmd "config vdom"
do_cmd "edit root"
do_cmd "show user local"
do_cmd "end"
Output
View the log of script running on device:FortiGate-VM64
 
------- Executing time: 2013-10-16 15:27:18 ------
Starting log (Run on device)
config vdom
FortiGate-VM64 (vdom) #
edit root
current vf=root:0
FortiGate-VM64 (root) #
config user local
FortiGate-VM64 (local) #
Adding user: usr0001
edit usr0001
new entry 'usr0001' added
FortiGate-VM64 (usr0001) #
set status enable
FortiGate-VM64 (usr0001) #
set type password
FortiGate-VM64 (usr0001) #
next
 
FortiGate-VM64 (local) #
Adding user: usr0002
edit usr0002
new entry 'usr0002' added
FortiGate-VM64 (usr0002) #
set status enable
FortiGate-VM64 (usr0002) #
set type password
FortiGate-VM64 (usr0002) #
next
Variations
There are a number of uses for this kind of looping script. One example is to create firewall policies for each interface that deny all non-HTTPS and non-SSH traffic by default. Another example is a scheduled script to loop through the static routing table to check that each entry is still reachable, and if not remove it from the table.
This script loops 10 times creating a new user each time whose name is based on the loop counter. The format command is used to force a four digit number.
In analyzing this script:
line 1 is the required #! to indicate this is a TCL script
lines 2-4 open CLI command wrapper procedure
line 5 declares the number of users to create
line 6 gets the FortiGate ready for entering local users
line 7 opens the for loop that will loop ten times
line 8 sets the username based on the incremented loop counter variable
line 9 is just a comment to the administrator which user is being created
lines 10-13 create and configure the user, leaving the CLI ready for the next user to be added
line 14 ends the for loop
line 15 ends the adding of users in the CLI
line 16 executes a CLI command to prove the users were added properly