# Mikrotik Failover script, ver 1.0.
3
# Auth: Lógico Software (@logico-dev)
# Date: 2018-10-06
# Based on: https://wiki.mikrotik.com/wiki/Failover_Scripting by Tomas Kirnak
# Released under MIT License (MIT)
# Copyright (c) 2018 Lógico Software <[email protected]>
# Please fill the WAN interface names
:local InterfaceISP1 ETH_ISP1
:local InterfaceISP2 ETH_ISP2
# Please fill the gateway IPs (or interface names in case of PPP)
:local GatewayISP1 192.168.1.1
:local GatewayISP2 172.16.1.1
# Please fill the ping check host - currently: google dns
:local PingTarget 8.8.8.8
# Please fill how many ping failures are allowed before fail-over happends
:local FailTreshold 3
# Declare the global variables
:global PingFailCountISP1
:global LastPingOk
# This inicializes the PingFailCount variables, in case this is the 1st time the
script has ran
:if ([:typeof $PingFailCountISP1] = "nothing") do={:set PingFailCountISP1 0}
:if ([:typeof $LastPingOk] = "nothing") do={:set LastPingOk 1}
# This variable will be used to keep results of individual ping attempts
:local PingResult
# Check ISP1
:set PingResult [ping $PingTarget count=1 interface=$InterfaceISP1]
:put $PingResult
:if ($PingResult = 0) do={
:if ($LastPingOk = 1) do={
:set PingFailCountISP1 ($PingFailCountISP1 + 1)
:if ($PingFailCountISP1 > 1) do={
:if ($PingFailCountISP1 > $FailTreshold) do={
:foreach i in=[/ip route find gateway=$GatewayISP1 && static]
do=\
{/ip route set $i distance=2}
:foreach i in=[/ip route find gateway=$GatewayISP2 &&
static] do=\
{/ip route set $i distance=1}
:log warning "ISP1 Down - Changing to ISP2."
:set LastPingOk 0
}
}
} else={
:set PingFailCountISP1 4
}
} else={
:if ($LastPingOk = 0) do={
:set PingFailCountISP1 ($PingFailCountISP1 - 1)
:if ($PingFailCountISP1 = 1) do={
:foreach i in=[/ip route find gateway=$GatewayISP1 && static]
do=\
{/ip route set $i distance=1}
:foreach i in=[/ip route find gateway=$GatewayISP2 &&
static] do=\
{/ip route set $i distance=2}
:log warning "ISP1 is back"
:set PingFailCountISP1 ($PingFailCountISP1 - 1)
:set LastPingOk 1
}
} else={
:set PingFailCountISP1 0
}
}