Place the following code in the dhcp-client script section. When the dhcp-client retrieves an IP address it will automatically build the recursive routes and keep the gateways up to date if there are changes. For each dhcp-client used, you will need to pick a different IP to health check and configure the priority of which ISP will be used for primary and failover and the script will do the rest of the work.
HealthCheckIP is the IP that will be pinged. If it fails then recursive routing will force the traffic to flow through the next ISP. You want to use different IPs to prevent both ISPs being marked down when that IP fails a check. Script defaults to 8.8.8.8 but you can use any address available on the internet.
ISPPriority is the order of ISPs you want to use as you failover. This controls the routes distance values. 1 is the highest priority.
Code: Select all
#####APPLY TO /ip dhcp-client add script= section.
#IP to use to check if ISP path is working. Use different IPs for each ISP.
:global HealthCheckIP "8.8.8.8"
#Which ISP path to use first. 1 is the highest priority. Each ISP needs a different priority value.
:global ISPPriority "1"
#####
#This creates the comments for the routes and is used to find and change/delete the entries.
:global ISPName ("ISP_".$interface)
#Make sure to set Add Default Route to "no" on the DHCP Client.
/ip dhcp-client set [ find interface=$interface ] add-default-route=no
#Add Recursive Gateway Health Check IP Monitor
:local count [/ip route print count-only where comment=($ISPName."_Monitor")]
:if ($bound=1) do={
:if ($count = 0) do={
/ip route add comment=($ISPName."_Monitor") disabled=no distance=1 dst-address=($"HealthCheckIP"."/32") gateway=$"gateway-address" scope=10 target-scope=10
} else={
:if ($count = 1) do={
:local test [/ip route find where comment=($ISPName."_Monitor")]
:if ([/ip route get $test gateway] != $"gateway-address") do={
/ip route set $test gateway=$"gateway-address"
}
} else={
:error "Multiple routes found"
}
}
} else={
/ip route remove [find comment=($ISPName."_Monitor")]
}
#Add 0.0.0.0/0 route to ISP Gateway
:local count2 [/ip route print count-only where comment=$ISPName]
:if ($bound=1) do={
:if ($count2 = 0) do={
/ip route add check-gateway=ping comment=$ISPName disabled=no distance=$ISPPriority dst-address=0.0.0.0/0 gateway=$"HealthCheckIP" scope=30 target-scope=11
}
} else={
/ip route remove [find comment=$ISPName]
}