/
Mikrotik WAN Failover

Mikrotik WAN Failover

This assumes your secondary WAN interface has a route distance of 2

DHCP

/system scheduler
add interval=1m name="Check If PrimaryWAN Down" on-event="/system script run CheckIfPrimaryWANIsDown"
add interval=5m name="Check If PrimaryWAN Up" on-event="/system script run CheckIfPrimaryWANIsUp"
/system script
add name=CheckIfPrimaryWANIsDown\
    source=":if ([/ping 1.1.1.1 count=3 interface=$PrimaryInterface] = 0) do={\r\
    \n :log error \"Primary WAN Down, moving to Secondary WAN\"\r\
    \n /ip dhcp-client set default-route-distance=3 interface=$PrimaryInterface\r\
    \n :delay 3\r\
    \n /ip firewall connection remove [find]\r\
    \n }"
add name=CheckIfPrimaryWANIsUp\
	source=":if ([/ping 1.1.1.1 count=3 interface=$PrimaryInterface] != 0) do={\r\
    \n :if ([ip dhcp-client get [find where interface=$PrimaryInterface] default-route-distance] = 3) do={\r\
    \n  :log error \"Primary WAN Up, moving back to Primary WAN\"\r\
    \n  /ip dhcp-client set default-route-distance=1 interface=$PrimaryInterface\r\
    \n  :delay 3\r\
    \n  /ip firewall connection remove [find]\r\
    \n  }\r\
    \n }"

PPPoE

/system scheduler
add interval=1m name="Check If PrimaryWAN Down" on-event="/system script run CheckIfPrimaryWANIsDown"
add interval=5m name="Check If PrimaryWAN Up" on-event="/system script run CheckIfPrimaryWANIsUp"
/system script
add name=CheckIfPrimaryWANIsDown\
source=":if ([/ping 1.1.1.1 count=3 interface=$PrimaryInterface] = 0) do={\r\
\n :log error \"Primary WAN Down, moving to Secondary WAN\"\r\
\n /interface pppoe-client set default-route-distance=3 interface=$PrimaryInterface\r\
\n :delay 3\r\
\n /ip firewall connection remove [find]\r\
\n }"
add name=CheckIfPrimaryWANIsUp\
source=":if ([/ping 1.1.1.1 count=3 interface=$PrimaryInterface] != 0) do={\r\
\n :if ([interface pppoe-client get [find where interface=$PrimaryInterface] default-route-distance] = 3) do={\r\
\n :log error \"Primary WAN Up, moving back to Primary WAN\"\r\
\n /interface pppoe-client set default-route-distance=1 interface=$PrimaryInterface\r\
\n :delay 3\r\
\n /ip firewall connection remove [find]\r\
\n }\r\
\n }"