Syed Jahanzaib Personal Blog to Share Knowledge !

June 12, 2014

Mikrotik WAN monitoring script with multiple host check

Filed under: Mikrotik Related — Tags: , — Syed Jahanzaib / Pinochio~:) @ 2:31 PM

eagle_map


Following is an Mikrotik RouterOS script designed to test internet connectivity by checking connectivity (by Ping method) for two different internet hosts, (like google dns and root dns server in this example). Main benefits of using script is that you can perform customized actions, like sending SMS or Email Alerts / acquire almost accurate results, avoiding false alarms etc etc.

In this script we are doing ping check on two internet hosts if it fails to receive single reply from both hosts, then it will consider the link DOWN. If one host is working and second is down, it will consider the link UP. It is done for cross verification. All sections in the script is customizable to meet your requirements , so make yourself home  😉

Multiple HOST check is recommended, Because if you are using single host check script or net-watch,then it can sometimes give you false alarm for any reason like maintenance or firewall blockage .


ROS SCRIPT CODE: (Script name= wan1mon )

 


# Mikrotik WAN/Intenret Link monitoring SCRIPT with optional Email and SMS Alert,
# We are using local KANNEL as SMS gateway and GMAIL as email sender
# Make sure to change email settings, because without backup link, email will not be send using gmail
# by Syed Jahanzaib
# https://aacable.wordpress.com
# Email : aacable at hotmail dot com
# Script Last Modified : 16th-AUG-2017

# Setting Variables
:local i 0;
:local F 0;
:local date;
:local time;
:local sub1 ([/system identity get name])
:local sub2 ([/system clock get time])
:local sub3 ([/system clock get date])
:local company "GALAXY Pvt Ltd"
:local ISP1 "ZAIB Primary Link"
:local ISP1NICK "JZ"

# Number of Ping Count, how many times mikrotik should ping the target device
:local PINGCOUNT "5"
# Ping threshold
:local PINGTS "10"

# GMAIL SMTP DYNAMIC Config Section, Make sure to change these values to match your's / Jz
# Gmail SMTP Address / you can use resolve command too, but i prefere to use manual smtp for some reasons

# Additional Check for GMAIL SMTP Resolving.
# If gmail SMTP failed to resolve, then it should set manual IP for gmail smtp
# So that email should go even if there is a dns failure.
# By ZAIB - 18-Aug-2017

:local GMAILSMTPDNSNAME "smtp.gmail.com"
:global GMAILSMTP ""
:local RESOLVELIST {"$GMAILSMTPDNSNAME"}
:foreach addr in $RESOLVELIST do={
:do {:resolve server=8.8.8.8 $addr} on-error={:set GMAILSMTP "0";}}
:if ($GMAILSMTP = 0) do={
:set GMAILSMTP "64.233.167.108";
} else={
:set GMAILSMTP [:resolve "$GMAILSMTPDNSNAME"];
}

:local adminmail1 ADMIN_MAIL_1@hotmail.com
#below Gmail ID will be used to send alerts / email
:local gmailid "YOUR_GMAIL_ID@gmail.com"
:local gmailuser "YOUR_GMAIL_ID"
:local gmailpass "YOUR_GMAIL_PASS"
:local gmailport 587

:local SUBJECTDOWN "$[/system clock get date] $[/system clock get time] -- GALAXY_ALERT: $ISP1NICK is DOWN."
:local BODYDOWN "$ISP1 Internet Link at GALAXY DATA CENTER not responding, Please check Linkconectivity. \n\n\n\n Auto Failover Script for Mikrotik Designed by \n *** Syed_Jahanzaib ****"

:local SUBJECTUP "$[/system clock get date] $[/system clock get time] -- GALAXY_INFO: $ISP1NICK have restored."
:local BODYUP "$ISP1 Internet Link have been Restored ... \n\n\n\n Auto Failover Script for Mikrotik Designed by \n *** Syed_Jahanzaib ****"

:global ISP1STATUS;
:global ISP1LASTCHANGESTATUS;

# Setting KANNEL INFO and SMS Number for admin
:local KID "KANNEL_ID"
:local KPASS "KANNEL_PASSWORD"
:local KHOST "192.168.0.1:13013"
:local CELL1 "03002767701"

# Setting UP SMS message
:local MSGDOWN "GALAXY+ALERT:+$ISP1NICK+Fiber+is+now+DOWN"
:local MSGUP "GALAXY+INFO:+$ISP1NICK+Fiber+is+now+UP"

# Check 2 hosts via ISP1 GATEWAY for monitoring
# Just make sure you ahve static routes for these routes and additionaly blackhole route as well
:global ISP1HOST1 "193.183.98.154"
:global ISP1HOST2 "84.200.70.40"

# FAKE HOST to test script
#:global ISP1HOST1 1.2.3.4
#:global ISP1HOST2 1.2.3.4

# PING each host $PINGCOUNT times
:for i from=1 to=$PINGCOUNT do={
if ([/ping $ISP1HOST1 count=1]=0) do={:set F ($F + 1)}
if ([/ping $ISP1HOST2 count=1]=0) do={:set F ($F + 1)}
:delay 2;
};

:if (($F=$PINGTS)) do={
:if (($ISP1STATUS="UP")) do={
:set ISP1STATUS "DOWN";

# Also add status in global variables to be used as tracking
:set date [/system clock get date];
:set time [/system clock get time];
:set ISP1LASTCHANGESTATUS ($time . " " . $date);

##################################################
####### FOR DOWN STATUS, CHANGE THE RULES ########
##################################################
# If the link is down, then LOG info and warning in Mikrotik LOG window [Zaib]

:log info "$ISP1NICK Gateway Not Responding. Please Check LinkConnectivity..."
#:log warning "Switching to Backup Link ($ISP2) ..."
#/ip firewall connection remove [find]
:delay 2;

# "Emailing the DOWN status. . . "
/tool e-mail send to="$adminmail1" password=$gmailpass subject="$SUBJECTDOWN" from=$gmailid server=$GMAILSMTP start-tls=yes body="$BODYDOWN"

# SENDING SMS for action DOWN
/tool fetch url="http://$KHOST/cgi-bin/sendsms\?username=$KID&password=$KPASS&to=$CELL1&text=$MSGDOWN"

##################################################
####### FOR UP STATUS, CHANGE THE RULES ########
##################################################

} else={:set ISP1STATUS "DOWN";}
} else={
:if (($ISP1STATUS="DOWN")) do={
:set ISP1STATUS "UP";

# If link is UP, then LOG info and warning in Mikrotik LOG window [Zaib]
:log info "$ISP1NICK Gateway RESTORED ..."
log warning "$ISP1 Restored..."
#/ip firewall connection remove [find]
:delay 2;

# Emailing the UP status. . .
/tool e-mail send to="$adminmail1" password=$gmailpass subject="$SUBJECTUP" from=$gmailid server=$GMAILSMTP start-tls=yes body="$BODYUP"

# SENDING SMS for action UP
/tool fetch url="http://$KHOST/cgi-bin/sendsms\?username=$KID&password=$KPASS&to=$CELL1&text=$MSGUP"

:set date [/system clock get date];
:set time [/system clock get time];
:set ISP1LASTCHANGESTATUS ($time . " " . $date);

} else={:set ISP1STATUS "UP";}
}


Scheduler to run script auto

To add scheduler to run script after every 5 minutes (or as required), use following code


/system scheduler
add disabled=no interval=5m name="Monitor WAN connectivity Scheduler / JZ" on-event=wan1mon policy=ftp,reboot,read,write,policy,test,winbox,password,sniff,sensitive,api start-date=jun/12/2014 start-time=\
00:00:00

Don’t forget to change the script name wan1mon in above scheduler to match the name you set for the script.

Example: on-event=wan1mon


Define Static Routes for Monitoring Host – for Route Changing

If  you are using this script to change internet route to backup link, then you must define static routes for the host you are monitoring. So that your monitored hosts should always (forcefully) go via Primary Link.

# Adding routes for the 2 monitoring host to go via primary lin
/ip route
add comment="Force this HOST via Primary Link" disabled=no distance=1 dst-address=193.183.98.154/32 gateway=192.168.1.1 scope=30 target-scope=10
add comment="Force this HOST via Primary Link" disabled=no distance=1 dst-address=84.200.70.40/32 gateway=192.168.1.1 scope=30 target-scope=10

# FORECEFULY - Adding routes for the 2 monitoring host to go via primary link FORECEFULY
add comment="Force this HOST via Primary Link - Black-Hole" distance=2 dst-address=193.183.98.154/32 type=blackhole
add comment="Force this HOST via Primary Link - Black-Hole" distance=2 dst-address=84.200.70.40/32 type=blackhole

Note: Make sure to change gateway 192.168.1.1 to primary internet link gateway.


BE VERY SURE TO READ FOLLOWING

https://aacable.wordpress.com/2015/09/17/monitoring-multiple-wan-links-in-pcc-using-black-hole-route-approach/


Mail Alert Notification Example: (reference purpose)


TIPS: [Internet hosts list for monitoring]

Following is list for some internet hosts that I usually monitor via the script, usefull if you want to monitor multiple wan links.

4.2.2.1
4.2.2.2
84.200.70.40
193.183.98.154
202.12.27.33
202.142.160.2
209.244.0.4
192.5.5.241
199.7.83.42

Regard’s
Syed Jahanzaib

Advertisements

20 Comments »

  1. A.A Jehanzaib Bhai,

    You have proven that “sharing is caring for others”. In country like Pakistan where no true policies / procedures are there to stop internet “PORN”, it is the responsibility of SysAdmins to start this on their own to educate others and provide these services free of cost. So we need more Articles from you for stopping “PORN” in our home / office and everywhere.

    Kind Regards,

    Mian Asif Riaz

    Like

    Comment by Mian Asif Riaz — June 12, 2014 @ 4:06 PM

  2. sir ji apna email address de do mujhe snat ke baaren main aapse discussion kerna hain

    Like

    Comment by parveen — June 27, 2014 @ 5:50 PM

  3. Aoa ,sir main nay script try kia hai.mujhay aik problem hai is main ,jab main kise aik interface to disable karta hon to ya script kam karta hay,aur agar main check karnay kay liya apnay fiber media converter say fiber nikalta hon to ya route change nae karta aur routes main ip ko reachable he show karta hai.please help me

    Like

    Comment by sohail — July 25, 2014 @ 12:26 AM

  4. Dear, sir
    its pleasure to meet you, i have Question Regarding to Fail Over link. i have two types of client on is Public ip and second is Private ip, can i configure Fail Over link in to my Mikrotik router which works for my both types clients.
    thanks.

    Like

    Comment by Paiman — January 22, 2015 @ 12:37 PM

  5. I have a question. Suppose you have multiple internet lines connected to mikrotik, how do you check each line if there is internet connection with this script? Some of the modems are in routing mode since 2 modems have the same gateway and it will conflict thats why they are set on routing mode. I believe in routing mode, miktorik will always make a particular line UP since its only monitoring the ip address of the modem in routing mode. How do we come by this?

    Like

    Comment by MT — January 29, 2015 @ 1:54 PM

  6. Please i have 2 ISPs connection to a Mikrotik router, one ISP provided a /29 IP address block for private use, routable to their own gateway. can you me with the config for load balancing and auto fail-over with Netwatch for the WAN links including the /29 IP block provided by the second ISP.

    Like

    Comment by Donald — February 17, 2016 @ 5:54 PM

  7. […] WAN1MON = it checks for DSL 1 status and update variable ‘wan1staus’ […]

    Like

    Pingback by Multiple IF statement matching with Mikrotik Script | Syed Jahanzaib Personal Blog to Share Knowledge ! — April 4, 2016 @ 4:08 PM

  8. […] you can run your own script here to make variable after successful or failed ping results # Ref: https://aacable.wordpress.com/2014/06/12/mikrotik-wan-monitoring-script-with-multiple-host-check/ :local DSL1 [/system script environment get [/system script environment find name="DSL1netstatus"] […]

    Like

    Pingback by [For Reference] Quick Script for Mikrotik Daily Info via SMS or Email ! | PakWarez — May 17, 2016 @ 1:05 PM

  9. Thanks for this script. I used it as the starting point for my solution.
    I changed it to consider link down on >= 80% packet loss and link up <= 20%. Outside these ranges the script doesn't make any routing changes.
    Also I used the comment for the main gateway to reflect the down date time stamp rather than your global InternetLastChange.
    So when it goes down i change the "Main Gateway" comment to "Main Gateway – down since ” and when it comes back, i restore the comment back to “Main Gateway”.
    This way i can immediately see from the route list when the switch happened. To do this the find command needs to be changed to use wildcard so it becomes: find comment ~ “Main Gateway”.

    Thanks again.. I have been struggling with a reliable approach after failing on advanced routing scripts and netwatch, this looks like it might work! 🙂

    Like

    Comment by Royce Lithgo — January 11, 2017 @ 3:46 AM

    • I am glad it helped.
      and yes by using scripts, we can acquire out tasks which are generally not possible with standard workout. what we refer to ‘out of the box’ solution 🙂

      Like

      Comment by Syed Jahanzaib / Pinochio~:) — January 11, 2017 @ 8:24 AM

  10. Can internet(link) downtime recorded and accumulated in any way in mikrotik, in minutes/hours… during 30 days period, or do we need too use other monitoring tools?

    Regards,

    Like

    Comment by Beni — February 6, 2017 @ 6:33 PM

  11. Your script is just what I need, but I don’t know what to put here:

    ## ADD YOUR RULES HERE, LIKE ROUTE CHANGE OR WHAT EVER IS REQUIRED, Example is below …
    ## /ip route set [find comment=”Default Route”] distance=3
    ## /ip firewall nat disable [find comment=”Your Rules, Example”]

    In my case when the link goes down I need to do a GET from an address on the LAN. The address is to a power relay that cycles the power for the modem.
    Can you tell me how I can have the script do this GET? http://192.168.88.247/state.xml?relay1State=2&pulseTime1=5
    I don’t car about the response, the simple of requesting the URL causes the power to cycle.

    Like

    Comment by Dave Covert — July 9, 2017 @ 9:27 PM

    • You can use following Example: (its just an example how you can use mikrotik command to fetch the required URL)

      /tool fetch url="http://KANNEL_GW_IP:13013/cgi-bin/sendsms\?username=kannel&password=KANNELPASSWORD&to=03333021909&text=ALERT:+INTERNET+Link+DOWN+at+$date+$time+[YOURCOMPANY+Pvt+Ltd]"

      make sure to wrap all the ? symbols

      Like

      Comment by Syed Jahanzaib / Pinochio~:) — July 12, 2017 @ 4:30 PM


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: