Working with Scripts : 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
1
2
3
4
5
 
6
7
8
9
10
11
12
13
14
15
 
16
 
17
#!
proc do_cmd {cmd} {
puts [exec "$cmd\n" "# " 15]
}
set num_users 10
 
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 "show user local"
 
 
Output
 
Starting script execution
config user local
(local)#
Adding user: usr0001
edit usr0001
new entry 'usr0001' added
(usr0001)#
set status enable
(usr0001)#
set type password
(usr0001)#
next
 
(local)#
Adding user: usr0002
edit usr0002
new entry 'usr0002' added
(usr0002)#
set status enable
(usr0002)#
set type password
(usr0002)#
next
 
Fortigate-50A #
show user local
 
config user local
edit "usr0001"
set type password
next
edit "usr0002"
set type password
next
end
 
Fortigate-50A #
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