Working with Scripts : Script samples : TCL scripts : TCL decisions
 
TCL decisions
TCL has a number of decision structures that allow you to execute different CLI commands based on what information you discover.
This script is more complex than the previous scripts as it uses two procedures that read FortiGate information, make a decision based on that information, and then executes one of the CLI sub-scripts based on that information.
To add information to existing firewall policies
Script
1
2
3
4
5
6
 
7
 
8
 
9
10
11
12
 
 
13
14
15
 
 
16
17
18
#!
# need to define procedure do_cmd
# the second parameter of exec should be "# "
# If split one command to multiple lines use "\" to continue
 
 
proc do_cmd {cmd} {
  puts [exec "$cmd\n" "# "]
}
foreach line [split [exec "show firewall policy\n" "# "] \n] {
  if {[regexp {edit[ ]+([0-9]+)} $line match policyid]} {
    continue
  } elseif {[regexp {set[ ]+(\w+)[ ]+(.*)\r} $line match key value]} {
    lappend fw_policy($policyid) "$key $value"
  }
}
do_cmd "config firewall policy"
foreach policyid [array names fw_policy] {
  if {[lsearch $fw_policy($policyid){diffservcode_forward 000011}] == -1} {
    do_cmd "edit $policyid"
    do_cmd "set diffserv-forward enable"
    do_cmd "set diffservcode-forward 000011"
    do_cmd "next"
  }
}
do_cmd "end"
Output
 
 
Variations
 
This type of script is useful for updating long lists of records. For example if FortiOS version 4.0 MR1 adds new keywords to user accounts, you can create a script similar to this one to get the list of user accounts and for each one edit it, add the new information, and move on to the next.
This script uses two decision statements. Both are involved in text matching. The first decision is checking each line of input for the policy ID and if its not there it skips the line. If it is there, all the policy information is saved to an array for future use. The second decision searches the array of policy information to see which polices are miss
In analyzing this script:
line 1 is the required #! to indicate this is a TCL script
line 2-8 is a loop that reads each policy’s information and appends only the policy ID number to an array variable called fw_policy
line 9 opens the CLI to the firewall policy section to prepare for the loop
line 10 starts the for each loop that increments through all the firewall policy names stored in fw_policy
line 11 checks each policy for an existing differvcode_forward 000011 entry - if its not found lines 12-15 are executed, otherwise they are skipped
line 12 opens the policy determined by the loop counter
line 13-14 enable diffserv_forward, and set it to 000011
line 15 saves this entry and prepares for the next one
line 16 closes the if statement
line 17 closes the for each loop
line 18 saves all the updated firewall policy entries