Technical Tip: How to use TCL script to create static routes by fetching gateway IP from an existing route
Description
This article describes how to use the TCL script in FortiManager to create static routes on FortiGates by fetching gateway IP from an existing route.
Scope
FortiManager.
Solution
- By default, TCL scripts are not enabled in FortiManager, Go to Device Manager -> Scripts, and select 'Create new'. Only the option of 'CLI Script' will be available.

- To enable the TCL script option, configure the following CLI settings:
config system admin setting
(setting) set show_tcl_script enable
(setting) end
Check it under Device manager -> Scripts, select Create new and TCL Script option is now available.

- Checking the existing static route on the FortiGate (gateway is 172.31.200.1):

- Go to Device Manager -> Scripts, select type TCL Script and select 'Create new' and create the below script:
#!
proc do_cmd {cmd} {
puts [exec "$cmd\n" "# " 15]
}
do_cmd "config router static"
#
# Selecting the existing route to fetch the gateway IP from
#
do_cmd "edit 4"
set query [exec "show\n" "# "]
#puts $query
set output [split $query \n]
#
# Find IP address and splitting the octets
# Below regex will first look for 'gateway' and then the IP address.
#
regexp {gateway[ ]([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)} $output match first second third fourth
do_cmd "end"
#
# creating a static routes
#
do_cmd "config router static"
#
do_cmd "edit 0"
do_cmd "set dst 10.0.0.0 255.0.0.0"
do_cmd "set gateway $first.$second.$third.$fourth"
do_cmd "set device port1"
do_cmd "set comment Route_to_Internet"
do_cmd "next"
#
# configure second additional static route
#
do_cmd "edit 0"
do_cmd "set dst 92.168.1.0 255.255.255.0"
do_cmd "set gateway $first.$second.$third.$fourth"
do_cmd "set device port1"
do_cmd "set comment Route_to_Internet"
do_cmd "end"

- TCL script will only have the 'Run script on' option set to 'Remote FortiGate Directly (via CLI)'.
- Select 'OK' to save the script.
- Under Device manager -> Scripts, select the Script and select 'Run Script'.

Select the FortiGate and select the right arrow:

Select Run Now:

Select OK:

The script will start running:

Script ran successfully:

- Checking the new routes on the FortiGate:

Related documents:
Technical Tip: How to troubleshoot TCL Scripts failed in FortiManager
