Syed Jahanzaib Personal Blog to Share Knowledge !

May 24, 2016

Mikrotik: Using Firewall Filters to Acquire Wan Data Usage via Email

Filed under: Mikrotik Related — Tags: , , , — Syed Jahanzaib / Pinochio~:) @ 11:32 AM

monitoring_report


Scenario:

An Operator [from Amsterdam] wanted to receive email on daily basis for the Daily usage of WAN link on the Mikrotik. Something like Mikrotik should send simple reporting email on daily basis like ‘XXX MB were downloaded Yesterday via WAN link’.


Solution:

Use following Script. All sections are well explained in comments sections. Make sure you read it carefully line by line, and modify items required.

In this example I used FILTER rules approach to collect the bytes. Surely there are more elegant ways to fetch the data like … Linux base MRTG, NMS like DUDE, above all SNMP  and many others. I just used this method. You may select other as it suites you. This one worked neatly for me 🙂

You can customize it as per your requirements, like multi wan report, monthly report etc.


Requirements:

Mikrotik 6.40.1

  1. Schedule this script to run after 5 (or xx) minutes. When DATE change occurs, it will reset the counter file and filter rules counters.
  2. Create two FILTER rules in Mikrotik as following. SFP1 is the wan interface, so do change it accordingly.
/ip firewall filter
add action=passthrough chain=forward comment=WAN_1_IN in-interface=sfp1
add action=passthrough chain=forward comment=WAN_1_OUT out-interface=sfp1

the Script !

# Script to collect WAN DATA USAGE using Firewall FILTER rules, and send data to admin by Email Daily.
# And reset the counters on daily basis in night. it will preserve the data in a file even if the router reboots.
# Syed Jahanzaib / aacable @ hotmail . com
# https://aacable.wordpress.com
# 1st Made : Year 2015
# Revision : 24-AUG-2017 / Adjusted for ROS 6.40.1

# Make sure you add two firewall rules as showed below so that script can take bytes from it and reset it when date changes.
# Change the interface name accordingly, and make sure to enter the matching comments too.
# /ip firewall filter
#add action=passthrough chain=forward comment=WAN_1_IN in-interface=sfp1
#add action=passthrough chain=forward comment=WAN_1_OUT out-interface=sfp1

# Set comments for firewall filter rules, change them as required
:global 1strun
# Set interface name, just for recognition only
:local INT "ether6"
:local WAN1INCOMMENT
:local WAN1OUTCOMMENT
:local WAN1INCOMMENT "WAN_1_IN"
:local WAN1OUTCOMMENT "WAN_1_OUT"

# Get bytes IN/OUT via filter rule
:local BYTESOUT [/ip firewall filter get [/ip firewall filter find comment="$WAN1INCOMMENT"] bytes]
:local BYTESIN [/ip firewall filter get [/ip firewall filter find comment="$WAN1OUTCOMMENT"] bytes]

# SET GMAIL for sending email, make sure you have configured /TOOLS,EMAIL option of mikrotik. and test it before using following.
:global gmailsmtp
:set gmailsmtp [:resolve "smtp.gmail.com"];
# Set your GMAIL Account Password
:local gmailpass
:set gmailpass GMAIL_PASSWD
# Set your email where you want to receive the alert
:local mailsendto
:set mailsendto SEND_TO_@MAIL.COM

# set DATE TIME
:local date
:local time
:set date [/system clock get date];
:set time [/system clock get time];

# If script is run for 1st time, then create the necessary files with some delay so router can create them
:if ([:len [/file find where name=counterslastupdate.txt ]] < 1 ) do={
/file print file=counterslastupdate.txt where name=counterslastupdate.txt
:set 1strun "1";
/delay delay-time=2;
/file set counterslastupdate.txt contents="0";
/delay delay-time=2;
} else={
:set 1strun "0";
}

# Create file (if file is not already there.) to store last update date time in normal format to be showed in email.
:if ([:len [/file find where name=counterslastupdatenormalformat.txt ]] < 1 ) do={
/file print file=counterslastupdatenormalformat where name=counterslastupdatenormalformat.txt
/delay delay-time=2;
/file set counterslastupdatenormalformat contents="0";
/delay delay-time=2;
};

# Setting different variables
:local curDate [/system clock get date]
:local curYear [:pick $curDate 7 13]
:local curMon [ :pick $curDate 0 3 ]
:local curDay [:pick $curDate 4 6]
:local COMPANY "JZ"
:local CURRENTDATE "$curDay$curYear"
:local LASTUPDATEDATE value=[/file get counterslastupdate.txt contents]
:local LASTUPDATEDATENORMAL value=[/file get counterslastupdatenormalformat.txt contents]

# Update counters last update with current date time
/file set counterslastupdate.txt contents=$CURRENTDATE

# Calculate data in MB to be displayed in LOG and email
:local TOTAL
:set $TOTAL ($BYTESOUT+$BYTESIN)
:local TOTALMB
:local TOTALGB
:set $TOTALMB ($TOTAL / 1024 / 1024)
:set $TOTALGB ($TOTAL / 1024 / 1024 /1024)
#:log warning ( "Traffic out = " . $BYTESOUT . " bytes" )
#:log warning ( "Traffic in = " . $BYTESIN . " bytes" )
#:log warning ( "TOTAL TRAFFIC = " . $TOTAL. " bytes" )

# YOU CAN DISABLE LOG DISPLAY to avoid flooding LOG Window, if scheduled to run every X mnts
:log warning "$TOTALMB MB (or Total $TOTALGB GB)Downloaded via $INT WAN link on $curDate"
:put "$TOTALMB MB (or Total $TOTALGB GB)Downloaded via $INT WAN link on $curDate";

# Create file (if file is not already there.) to update download bytes
:if ([:len [/file find where name=counter.txt]] < 1 ) do={
/file print file=counter.txt where name=counter.txt;
/delay delay-time=2;
/file set counter.txt contents="0";
};

# If current value is bigger then older, then update the counters,
# Helpfule to save counters, when router reboots.

# Get value from stored data for matching
:local before value=[/file get counter.txt contents]
:if ($TOTAL > $before) do={
/file set counter.txt contents=$TOTAL
} else= {
# Else update both values in the file
#:put "Step-5.1"
:set $TOTAL ($TOTAL+$before)
/file set counter.txt contents=$TOTAL
};

# Update Date time stamp in both files / zaib
/file set counterslastupdate.txt contents=$CURRENTDATE
/file set counterslastupdatenormalformat.txt contents=$curDate

# 1st run
# If date is changed (usually in night) , then send email using GMAIL , with the Data
#:if (($dsl1 = "DOWN") && ($dsl2 = "DOWN")) do={
:if ($1strun = "0") do={
:if ($CURRENTDATE = $LASTUPDATEDATE) do={
#:log warning "No need to send email as No date have changed since last run ..."
} else {
:log warning "DATE changed, sending email for last day data usage and also resetting the Firewall Counters ..."
# Reset the firewall counters and counter files if date change is detected / zaib
/ip firewall filter reset-counters [find comment=$WAN1INCOMMENT]
/ip firewall filter reset-counters [find comment=$WAN1OUTCOMMENT]
/file set counter.txt contents="0";
# Set Email Subject
:local es "$[/system identity get name] $[/system clock get date] $[/system clock get time] $COMPANY MIKROTIK / $TOTALMB MB were downloaded via $INT WAN link on $LASTUPDATEDATENORMAL"
# Set Email Body
:local eb "$[/system identity get name] $[/system clock get date] $[/system clock get time] $COMPANY MIKROTIK / $TOTALMB MB were downloaded via $INT WAN link on $LASTUPDATEDATENORMAL"
# Finally send email
/tool e-mail send to=$mailsendto subject=$es body=$eb start-tls=yes
:set $1strun "0";
}
};

# Regard's
# Syed Jahanzaib

End Results !

downlaoded

 

 

Advertisements

4 Comments »

  1. I am using scripts to collect data usage on daily basics but i won’t used counter to reset after 24H

    date = may/23/2016
    Time =  17:41:13
    Uptime = 6d00:00:49
    CPU Load = 7
    WAN 1 = 0   GB WAN 1 RX= 0 MB WAN 1 TX= 0 MB
    WAN 2 = 58   GB WAN 2 RX= 52321 MB WAN 2 TX= 7882 MB
    WAN 3 = 0   GB WAN 3 RX= 0 MB WAN 4 TX= 0 MB
    WAN 4 = 20   GB WAN 4 RX= 18417 MB WAN 4 TX= 2643 MB
    Total RX+TX= 78 GB

    Like

    Comment by UmmarHussain — May 24, 2016 @ 11:51 AM

  2. for multiwan?

    Like

    Comment by antonio — May 24, 2016 @ 12:10 PM

  3. How did you run script? with scheduler ? which interval ? 24 hours ?

    Like

    Comment by Damir — May 24, 2016 @ 2:43 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: