Community discussions

MikroTik App
 
User avatar
kwagga
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 90
Joined: Sun Aug 28, 2011 11:49 pm
Location: Pretoria, South Africa

[Useful] Script to email on gateway down

Wed Nov 01, 2023 10:00 am

Hi All,

So we have several sites that make use of dual WAN or failover WAN's, and while we spent many hours trying to get Netwatch to work for us (ideally it can also notify on packet loss, not just a hard down), we found we were getting many false alarms with Netwatch, so we decided to implement recursive route lookups (https://help.mikrotik.com/docs/pages/vi ... d=26476608) to give us more accurate and stable alerts.

Additionally, we wanted to be alerted via email each time a link goes up or down.

While I'm not a scripter, I was able to cobble together the below, which works for us.

Netwatch in RouterOS 7.5 and up is still the best case for most people, but if you are one of the few who deals with constant unstable links, perhaps the below can help, because it's so basic, it can easily be modified and built upon.
:global primarylinkdown 
:local name [/system identity get name]

{
    :local routecheckstatus1 [ip route get value-name=inactive [find gateway=196.25.1.1]]
    :local routecheckstatus2 [ip route get value-name=inactive [find gateway=9.9.9.9]]

    :if ($routecheckstatus1 = true or $routecheckstatus2 = true) do={
        /log error "Primary Gateway is down"
        /tool e-mail send to=notification@domain.tld subject="$name: Primary WAN Down" body="The primary connection at $name is DOWN, switched over to secondary"
        :set primarylinkdown true
    } else={
        :if ($routecheckstatus1 = false and $routecheckstatus2 = false) do={
            :if ($primarylinkdown = true) do={
                /log warning "Primary gateway is UP!"
                /tool e-mail send to=notification@domain.tld subject="$name: Primary WAN Up" body="The primary connection at $name is back up."
                :set primarylinkdown false
            }
        }
    }
}

Who is online

Users browsing this forum: No registered users and 7 guests