Bandwidth-based load-balancing with failover. This presentation also covers Mangle.
This was presented at the MUM (MikroTik User Meeting) in New Orelans, USA.
Tomas Kirnak - YouTube: https://www.youtube.com/watch?v=67Dna_ffCvc&t=1s
http://mum.mikrotik.com/presentations/US12/tomas.pdf
Thanks for the link
Seems what the presentation covers is not what is being discussed here.
Here the topic is to limit volumes on an interface based on quota for that interface (typical scenario being LTE monthly volume).
The presentation speaks about load-balanced WAN, based on bandwidth; ie: switch to ISP2 when x Volume is consumed on ISP1.
Not really on point, especially when considering that in the discussion above, the LTE could be the failover.
But thanks
Hi,
Sorry for your trouble. I’m new to mikrotik. I manage to add in firewall filter and the Nat to routerOs. I’m currently stuck with the wan2DisableNatOnVolumeExcess script. Where should I paste the command? or should I save it to a text file and run from some command in routeros? Any guide is much appreciated. Btw, I’m using mikrotik rb3011…
Dear all,
I’m new to Mikrotik, this forum was of great help. Thanks to the community.
Happy to contribute by sharing below my implementation to avoid getting overpriced LTE invoices.How this works?
1- the counting of the LTE traffic is made via a firewall filter. Main reason here is to avoid file read/write, hence SSD wear + even if firewall counter doesnt survive a reboot. This firewall filter is expected to be the first in the chain, so it really counts all matching traffic. Observe that this firewall filter purposefully excludes the traffic that only goes to the internal IP of the LTE router (or its subnet): the counter hence only includes the traffic that goes through the LTE router and to the internet
2- when the volume is exceeded, the interface is not shut down, instead it’s the NAT which gets disabled. This enables the router to still have service
3- the script runs every minute (via scheduler) and reset the firewall counter at midnight, on the 1st of each month. The script logs the NAT disable/enable action, and logs the counter-resetting
The script uniquely identifies the firewall filter and the nat via their comment
Below is the content
Firewall filter (to count traffic)add action=passthrough chain=forward comment="Count traffic going to internet through WAN2 (LTE)" dst-address=!172.16.5.0/24 log-prefix="FW fwd passthrough WAN2" out-interface="WAN2" add action=passthrough chain=forward comment="Count traffic coming from internet through WAN2 (LTE)" dst-address=!172.16.5.0/24 log-prefix="FW fwd passthrough WAN2" in-interface="WAN2"NAT (this is what gets enabled/disabled on volume excess)
add action=masquerade chain=srcnat comment="NAT to WAN2" ipsec-policy=out,none out-interface="WAN2"Script wan2DisableNatOnVolumeExcess
# /system script run wan2DisableNatOnVolumeExcess ## Script config :local firewallFilterOUTComment "Count traffic going to internet through WAN2 (LTE)"; :local firewallFilterINComment "Count traffic coming from internet through WAN2 (LTE)"; :local wan2NatComment "NAT to WAN2"; :local maxVolumeMB 2000 ## Script program below ## Function: flip wan2 nat disable state :local flipWan2NatDisableStatus do={ # get WAN2 nat status :local wan2NatDisabledStatus value=[:tostr [/ip firewall nat get value-name=disabled [find comment="$wan2NatComment"]]]; :local outputLogMessage # invert the disabled state :local wan2NatDisabledSwitch; :local wan2NatDisabledSwitchRequired false; :if (($wan2NatDisabledStatus=true) && ($maxVolumeThresholdExceeded=false)) do={ :set wan2NatDisabledSwitchRequired true; :set wan2NatDisabledSwitch "no"; :set outputLogMessage "WAN2 interface volume threshold not exceeded (<$maxVolumeMB MB), enabling NAT"; } :if (($wan2NatDisabledStatus=false) && ($maxVolumeThresholdExceeded=true)) do={ :set wan2NatDisabledSwitchRequired true; :set wan2NatDisabledSwitch "yes"; :set outputLogMessage "WAN2 interface volume threshold exceeded (>$maxVolumeMB MB), disabling NAT"; } if ($wan2NatDisabledSwitchRequired=true) do={ /ip firewall nat set disabled=[$wan2NatDisabledSwitch] [find comment="$wan2NatComment"]; :log warning $outputLogMessage } } # reset filter counter, on the 1st of each month at 00:00 :if (([/system clock get date]~"^[a-zA-Z][a-zA-Z][a-zA-Z]/01/[0-9][0-9][0-9][0-9]") && ([/system clock get time]~"^00:00:[0-9][0-9]")) do={ /ip firewall filter reset-counters [find comment="$firewallFilterOUTComment"]; /ip firewall filter reset-counters [find comment="$firewallFilterINComment"]; :log info "WAN2 firewall filter counter has been reset" }; # get the counter of traffic gone through WAN2 to internet :local maxVolumeB value=[:tonum ($maxVolumeMB*1024*1024)] :local maxVolumeThresholdExceeded :local firewallFilterOUTVolume value=[:tostr [/ip firewall filter get value-name=bytes [find comment="$firewallFilterOUTComment"]]]; :local firewallFilterINVolume value=[:tostr [/ip firewall filter get value-name=bytes [find comment="$firewallFilterINComment"]]]; :local filrewallFilterTotalVolume ($firewallFilterOUTVolume + $firewallFilterINVolume); :if ($filrewallFilterTotalVolume > $maxVolumeB) do={ :set maxVolumeThresholdExceeded true } else={ :set maxVolumeThresholdExceeded false } ## enable/disable nat of WAN2 when traffic below/exceeds threshold $flipWan2NatDisableStatus wan2NatComment=$wan2NatComment maxVolumeThresholdExceeded=$maxVolumeThresholdExceeded maxVolumeMB=$maxVolumeMB
Hi,
Well the content of the script should be pasted into a blank script into System> Scripts
You’ll need to give this script a name a suggestion would be wan2DisableNatOnVolumeExcess
Once you have saved your script under its name (for example wan2DisableNatOnVolumeExcess); then you’ll need to run it:
- either manually via the command line
- or automatically via the scheduler (system > scheduler)
Either way, the script is invoked with:
/system script run wan2DisableNatOnVolumeExcess
Also, please ensure you have adjusted the firewall rules to your environment: both for the interface name AND the subnet.
Hope this helps
Cheers
Hi Eguun,
Thanks a lot for the clarification. Appreciate your assistance. Will try tonight. ![]()
Hi,
Well the content of the script should be pasted into a blank script into System> Scripts
You’ll need to give this script a name a suggestion would be wan2DisableNatOnVolumeExcessOnce you have saved your script under its name (for example wan2DisableNatOnVolumeExcess); then you’ll need to run it:
- either manually via the command line
- or automatically via the scheduler (system > scheduler)
Either way, the script is invoked with:
/system script run wan2DisableNatOnVolumeExcessAlso, please ensure you have adjusted the firewall rules to your environment: both for the interface name AND the subnet.
Hope this helps
Cheers
Hi Eguun,
I manage to add script as per your advice. It manage to run but the logs don’t show the comments in the script. I’m not sure what I’m doing wrong.
Anyway, below are my router environment.
ether1 : wan connection
ether2 : hotspot connection
ether3 : hotspot connection
ether4 : lan connection
Basically, what I want to achieve to block all internet traffic once it reach 50GB a month and the quota is reset every 1st of the month. I’m trying to modify your script to suit my requirements but failed. Hope that you could assist me on this. Any guidance is much appreciated.
Hi Eguun,
Thanks a lot for the clarification. Appreciate your assistance. Will try tonight.Hi,
Well the content of the script should be pasted into a blank script into System> Scripts
You’ll need to give this script a name a suggestion would be wan2DisableNatOnVolumeExcessOnce you have saved your script under its name (for example wan2DisableNatOnVolumeExcess); then you’ll need to run it:
- either manually via the command line
- or automatically via the scheduler (system > scheduler)
Either way, the script is invoked with:
/system script run wan2DisableNatOnVolumeExcessAlso, please ensure you have adjusted the firewall rules to your environment: both for the interface name AND the subnet.
Hope this helps
Cheers
Okay,
at this stage, it’s worth you ensuring the Nat & Firewall rules are aligned with your interface: ie that you didn’t simply copy/pasted my text without changing interface names.
Once done, you can add debug lines in the code to output some info in the logs or the console so you can follow-up how the script behave.
I would recommend you to invest serious time & effort into it: I can provide some high level guidance but won’t be able to dedicate hand-helding level of support.
Thanks
Hi Eguun,
Manage to debug the script. Mistake was with the names. Btw, this script does not save the counter value to file right? If the router is rebooted, the counters will be back to zero. Any idea how to resolve this?
Thanks for you advice.
Okay,
at this stage, it’s worth you ensuring the Nat & Firewall rules are aligned with your interface: ie that you didn’t simply copy/pasted my text without changing interface names.
Once done, you can add debug lines in the code to output some info in the logs or the console so you can follow-up how the script behave.
I would recommend you to invest serious time & effort into it: I can provide some high level guidance but won’t be able to dedicate hand-helding level of support.
Thanks
Hi,
I’ve tested this script and it is working as what I needed. But I would to make some amendments to it. How do I only allow winbox (port 8291) to passthrough instead for disabling the whole interface? The reason for this is I want to remotely connect to it if the remote site decided to topup the quota. Any help is much appreciated.
After trying one of the final version of this script, I made some modification to avoid couple of things from the original idea: resetting the router to reset the interface’s counters and writing to file to keep variable values. When using ethernet interface in order to reset the traffic counter you have to reboot the router, as disable/enable does not reset those counters.
In this version I’m using someone’s else idea to keep all variables in the firewall Layer7 protocol section; those values are retained also after router reboot (original post To retain variable's values after reboot).
Then I decided to add a new variable for the offset for when the new month kicks in and I don’t reboot the router and therefore the ethernet counters are still with values.
I have tested it with the latest ROS 6.46 and it seem working fine, even trying to simulate router reboot, new month and so on.
If someone is interested here is the final code, starting from the one on this post; this version is used on ethernet interface, so if you want to use it for LTE then you need to change the /interface command to reflect that.Cheers,
Armando:global persistVar do={ :local varName $1; :local varValue $2; :local varID [/ip firewall layer7-protocol find name="$varName"]; :if ([:typeof $varValue] = "nothing") do={ :if ($varID != "") do={ :set $varValue [/ip firewall layer7-protocol get $varID value-name=regexp]; } } else={ :if ($varID = "") do={ /ip firewall layer7-protocol add name="$varName" regexp="$varValue" } else={ /ip firewall layer7-protocol set $varID regexp="$varValue" } } return $varValue } :do { #################################################################################################### # User config #Set limit in MB :local limit 350000; #Set day to reset limit :local dayresetlimit "01"; #Set interface :local interf "ether1-WAN1"; #Set auto bring up interface :local autointon true; #################################################################################################### :local day ([:pick [/system clock get date] 4 6]); :local newdata; :local result; :local ref; :local status; :local tx [/interface get $interf tx-byte]; :local rx [/interface get $interf rx-byte]; :set $newdata (($rx + $tx) / 1024 / 1024); :if ([:len [$persistVar wan_counter]] < 1 ) do={ $persistVar wan_counter 0; } :if ([:len [$persistVar wan_rebootblock]] < 1 ) do={ $persistVar wan_rebootblock 1; } :if ([:len [$persistVar wan_offset]] < 1 ) do={ $persistVar wan_offset 0; } :if ([:len [$persistVar wan_refdata]] < 1 ) do={ $persistVar wan_refdata 0; } :local rebootblocker ([$persistVar wan_rebootblock]); :if ( $day = $dayresetlimit and $rebootblocker = 0) do={ $persistVar wan_counter 0; $persistVar wan_offset $newdata; $persistVar wan_refdata 0; /interface ethernet set $interf disabled=no $persistVar wan_rebootblock 1; :log info "Limit reset, int $interf bring up"; } :if ( $day != $dayresetlimit ) do={ $persistVar wan_rebootblock 0; } :local before [$persistVar wan_counter]; :local offset [$persistVar wan_offset]; :if ( $newdata < $before ) do={ $persistVar wan_offset 0; :set $ref [$persistVar wan_refdata]; :if ( $newdata < $ref ) do={ set $ref (0) } :set $result ($before + $newdata - $ref); $persistVar wan_refdata $newdata; $persistVar wan_counter $result; } else={ :set $result ($newdata - $offset); $persistVar wan_counter $result; } :local traffic ([$persistVar wan_counter]); :local percent ($traffic*100 / $limit); :log warning "Limit: $limit MB Traffic: $traffic MB Used: $percent%"; :if ($percent >= 100) do={ /interface ethernet set $interf disabled=yes } :if ($percent < 100 and $autointon = true) do={ :set $status [/interface get $interf value-name=disabled]; :if ($status = true) do={ /interface ethernet set $interf disabled=no } } } on-error={ :log error "Error WAN1_Limiter "};
Hi,
First let me congratulate you on your success, your efforts paid off ![]()
If the router is rebooted, the counters will be back to zero. Any idea how to resolve this?
On your counter-reset question: there is no way to alter this, it’s a “feature” of mikrotik: all what isn’t saved on flash drive is lost on reboot. It also includes these firewall-filter counters.
A workaround would be to have another script to regularly read these values and save them on the flash drive (ie: run via a scheduler).
And if the script realizes that the value it has saved is larger than the one reported by the firewall filter, then a reboot occurred
On my usage, this isn’t a route I explored: I only keep the router up.
I’ve tested this script and it is working as what I needed. But I would to make some amendments to it. How do I only allow winbox (port 8291) to passthrough instead for disabling the whole interface? The reason for this is I want to remotely connect to it if the remote site decided to topup the quota. Any help is much appreciated.
On this topic, I would suppose the script works already as you would like:
when the quota is exceeded, it’s only the nat that is disabled (ie what nat the lan to wan), not the wan/LTE interface. So as such, the router still keep its reachability on LTE/4G.
However, I observed that LTE/4G providers does not distribute public IP, but instead private IP.
As such, remote management via LTE hasn’t been possible - at least for me for my LTE provider.
Anyway, it should work as you want straight out of the box, if I understand you well.
You can test this easily by setting a low quota that is easily exceeded and see if you can access your router before and after the nat is disabled.
Cheers
Hello everyone,
i’m new from this forum, but i’m intereseted at this topic. Now i try to explain my problem. I bought a SXRT Antenna from mikrotik. inside i put two SIM and a modem R11e-LTE. Now i want, if is possible, make a script that when the traffic on SIM “a” will be finish(on 50GB of limit) change a modem, and a APN. I have on SIM “a”, 70Gb of traffic, and the APN is 1, otherhand i have on SIM “b”, 50Gb of traffic limit and APN is 2. This iis needed to count a mounth reset. because each month i have a renew offer. Thanks a lot of help me!!
Pante90
i want, if is possible, make a script that when the traffic on SIM “a” will be finish(on 50GB of limit) change a modem, and a APN. I have on SIM “a”, 70Gb of traffic, and the APN is 1, otherhand i have on SIM “b”, 50Gb of traffic limit and APN is 2.
You have counting scripts in this post. Use it. You can create other way… like check if internet is offline - if true then run script who replace sim slots and do change APN etc.
e.g. Change SIM Slot
Would you be able/willing to explain what the 3 other L7 variables do?
I tried to understand from your script, but can’t get their meaning…:
- wan-offset ?
- wan-rebootlock ?
- wan-refdata ?
Again, thank you very much for your script
Sorry for the long delay, but actually I have never received notification about this post being growing.
Basically about those variables, wan-rebootblock it’s used to avoid that on the “reset-day”, where you will reset the counters to 0 (because your monthly plan has reset), this reset will happen on every cycle for that day.
So let’s say you reset at midnight on 01 of each month, only the first time wan-rebootblock is 0; then once the limits are reset, such variable gets to 1 and does not allow the code to enter into that reset anymore for that day. From day 02 the reset function is not triggered anymore because of the different day.
wan-offset it’s used when the router is not rebooted between the month change. So, let’s say your router’s uptime is high and the interface has counted progressively by increasing its value all time, when the day 01 reaches, the script will store the previous counted value into offset, so that from now on the new data (which is reset to 0) is considering the previous ending value to be matched with the continuously increasing value assigned to your interface traffic. So this allows the counter from making a delta between the interface traffic accumulated and the current consumed value.
wan-refdata is when your router was reboot. In that case you loose the traffic counter for the interface, therefore you are not in the normal condition where you will use the offset. In this case you are recovering where you were with this reference data and then adds-up the traffic accumulated (after reboot) again in your interface counter.
Hope this makes sense too you.
Hello all,
I’m just posting the current version of the script for ethernet’s based traffic limiter which I’m currently using, where I added also some notification via Telegram Bot.
For this reason there is a global variable “notifyCount” to limit the number of Telegram notification that you’d like to receive.
Most of the script is the same, few changes to some part of the logic.
The main function to store data into firewall-L7 “data storage” is now part of a general global variable and the script is not run in a loop, but through a scheduler.
:global persistVar
:global notifyCount
:do {
####################################################################################################
# User config
#Set limit in MB
:local limit 390000
#Set day to reset limit
:local dayresetlimit "01"
#Set interface
:local interf "ether1-WAN"
#Set auto bring up interface
:local autointon true
#Delta startup value
:local startValue 0
####################################################################################################
:local notifyLimit 1
:local botId "your_bot_id"
:local chatId "your_chat_id"
:local site [/system identity get value-name=name]
:local day ([:pick [/system clock get date] 4 6])
:local mon ([:pick [/system clock get date] 0 3])
:local year ([:pick [/system clock get date] 7 11])
:local date "$day-$mon-$year"
:local time (:put [/system clock get time])
:local newdata
:local result
:local ref
:local status
:local tx [/interface get $interf tx-byte]
:local rx [/interface get $interf rx-byte]
:set $newdata (($rx + $tx) / 1024 / 1024)
:if ([:len [$persistVar wan1_counter]] < 1 ) do={
$persistVar wan1_counter 0
}
:if ([:len [$persistVar wan1_rebootblock]] < 1 ) do={
$persistVar wan1_rebootblock 1
}
:if ([:len [$persistVar wan1_offset]] < 1 ) do={
$persistVar wan1_offset 0
}
:if ([:len [$persistVar wan1_refdata]] < 1 ) do={
$persistVar wan1_refdata 0
}
:local rebootblocker ([$persistVar wan1_rebootblock])
:if ( $day = $dayresetlimit and $rebootblocker = 0) do={
$persistVar wan1_counter 0
$persistVar wan1_offset $newdata
$persistVar wan1_refdata 0
/interface ethernet set $interf disabled=no
$persistVar wan1_rebootblock 1
:set notifyCount 0
:log warning "Resetting limits, int $interf bring up"
}
:if ( $day != $dayresetlimit ) do={
$persistVar wan1_rebootblock 0
}
:local before [$persistVar wan1_counter]
:local offset [$persistVar wan1_offset]
:if ( $newdata < $before ) do={
$persistVar wan1_offset 0
:set $ref [$persistVar wan1_refdata]
:if ( $newdata < $ref ) do={
:set $ref (0)
}
:set $result ($before + $newdata - $ref + $startValue)
$persistVar wan1_refdata $newdata
$persistVar wan1_counter $result
} else={
:set $result ($newdata - $offset + $startValue)
$persistVar wan1_counter $result
}
:local traffic ([$persistVar wan1_counter])
:local percent ($traffic*100 / $limit)
:if ($percent >= 100) do={
:if ($notifyCount <= $notifyLimit) do={
/tool fetch url="https://api.telegram.org/bot$botId/sendMessage?chat_id=$chatId&text=MikroTik $site info:%0A[$date $time]%0AWAN1 disabled for exceeding bandwidth limit $limit MB" keep-result=no
:log warning "$interf disabled for exceeding bandwidth limit $limit MB"
:set $notifyCount ($notifyCount + 1)
:delay 3
}
/interface ethernet set $interf disabled=yes
}
:if ($percent < 100 and $autointon = true) do={
:set $status [/interface get $interf value-name=disabled]
:if ($status = true) do={
/interface ethernet set $interf disabled=no
}
}
} on-error={ :log error "Error WAN1_Limiter "}
Armando
Hello
For LTE:
# /$$ /$$$$$$$$/$$$$$$$$ /$$ /$$ /$$ /$$ # | $$ |__ $$__/ $$_____/| $$ |__/ |__/ | $$ # | $$ | $$ | $$ | $$ /$$ /$$$$$$/$$$$ /$$ /$$$$$$ /$$$$$$ /$$$$$$ # | $$ | $$ | $$$$$ | $$ | $$| $$_ $$_ $$| $$|_ $$_/ /$$__ $$ /$$__ $$ # | $$ | $$ | $$__/ | $$ | $$| $$ \ $$ \ $$| $$ | $$ | $$$$$$$$| $$ \__/ # | $$ | $$ | $$ | $$ | $$| $$ | $$ | $$| $$ | $$ /$$| $$_____/| $$ # | $$$$$$$$| $$ | $$$$$$$$| $$$$$$$$| $$| $$ | $$ | $$| $$ | $$$$/| $$$$$$$| $$ # |________/|__/ |________/|________/|__/|__/ |__/ |__/|__/ \___/ \_______/|__/ # # Using: Set all var in User config section. Add scripts to schedule with onstart and interval 30 sek :do { ####################################################################################################### # User config #Set limit in MB :local limit 12288 #Set day to reset limit :local dayresetlimit 1 #Set interface :local interf "lte1" #Set auto bring up interface :local autointon true ####################################################################################################### :local filename "counter.txt" :local filewarn "warning.txt" :local fileref "refcount.txt" :local reblock "reblock.txt" :local status :if ([:len [/file find where name=$filewarn]] < 1 ) do={ /file print file=$filewarn where name=$filewarn /delay delay-time=2 /file set $filewarn contents=$percent }; :if ([:len [/file find where name=$filename]] < 1 ) do={ /file print file=$filename where name=$filename /delay delay-time=2; /file set $filename contents=0 } :if ([:len [/file find where name=$reblock]] < 1 ) do={ /file print file=$reblock where name=$reblock /delay delay-time=2; /file set $reblock contents=1 } :if ([:len [/file find where name=$fileref]] < 1 ) do={ /file print file=$fileref where name=$fileref /delay delay-time=2; /file set $fileref contents=0 } :local reblocker ([/file get $reblock contents]) :local curdate [/system clock get date] :local day [ :pick $curdate 4 6 ] :if ( $day = $dayresetlimit and $reblocker = 0) do={ /file set $filename contents=0 /file set $filewarn contents=0 /file set $fileref contents=0 /interface lte set $interf disabled=no /file set $reblock contents=1 :log info "Limit reset, int $interf bring up" /delay delay-time=5; :log info "Clear int counters - reboot" #TODO find another method for interf clear counters /system reboot } :if ( $day != $dayresetlimit ) do={ /file set $reblock contents=0 } :local before :local correct :local ref :local newdata :local tx [/interface get $interf tx-byte] :local rx [/interface get $interf rx-byte] :set $newdata (( $rx + $tx ) / 1024 / 1024 ) :set $before [/file get $filename contents] :if ( $newdata < $before ) do={ :set $ref [/file get $fileref contents] :set $correct ( $before + $newdata - $ref ) /file set $fileref contents=$newdata /file set $filename contents=$correct } :if ( $newdata >= $before ) do={ /file set $filename contents=$newdata } :local traffic ([/file get $filename contents]) :log warning "Limit: $limit MB" :local percent ($traffic*100 / $limit) :log warning "Use: $percent%" /file set $filewarn contents=$percent :if ($percent >= 100) do={ /file set $filewarn contents=$percent /interface lte set $interf disabled=yes } :if ($percent < 100 and $autointon = true) do={ :set $status [/interface get $interf value-name=disabled] :if ($status = true) do={ /interface lte set $interf disabled=no } } } on-error={ :log error "Error LTELimiter "};
for PPP-Client
# /$$ /$$$$$$$$/$$$$$$$$ /$$ /$$ /$$ /$$ # | $$ |__ $$__/ $$_____/| $$ |__/ |__/ | $$ # | $$ | $$ | $$ | $$ /$$ /$$$$$$/$$$$ /$$ /$$$$$$ /$$$$$$ /$$$$$$ # | $$ | $$ | $$$$$ | $$ | $$| $$_ $$_ $$| $$|_ $$_/ /$$__ $$ /$$__ $$ # | $$ | $$ | $$__/ | $$ | $$| $$ \ $$ \ $$| $$ | $$ | $$$$$$$$| $$ \__/ # | $$ | $$ | $$ | $$ | $$| $$ | $$ | $$| $$ | $$ /$$| $$_____/| $$ # | $$$$$$$$| $$ | $$$$$$$$| $$$$$$$$| $$| $$ | $$ | $$| $$ | $$$$/| $$$$$$$| $$ # |________/|__/ |________/|________/|__/|__/ |__/ |__/|__/ \___/ \_______/|__/ # # Using: Set all var in User config section. Add scripts to schedule with onstart and interval 30 sek :do { ####################################################################################################### # User config #Set limit in MB :local limit 12288 #Set day to reset limit :local dayresetlimit 1 #Set interface :local interf "ppp-out1" #Set auto bring up interface :local autointon true ####################################################################################################### :local filename "counter.txt" :local filewarn "warning.txt" :local fileref "refcount.txt" :local reblock "reblock.txt" :local status :if ([:len [/file find where name=$filewarn]] < 1 ) do={ /file print file=$filewarn where name=$filewarn /delay delay-time=2 /file set $filewarn contents=$percent }; :if ([:len [/file find where name=$filename]] < 1 ) do={ /file print file=$filename where name=$filename /delay delay-time=2; /file set $filename contents=0 } :if ([:len [/file find where name=$reblock]] < 1 ) do={ /file print file=$reblock where name=$reblock /delay delay-time=2; /file set $reblock contents=1 } :if ([:len [/file find where name=$fileref]] < 1 ) do={ /file print file=$fileref where name=$fileref /delay delay-time=2; /file set $fileref contents=0 } :local reblocker ([/file get $reblock contents]) :local curdate [/system clock get date] :local day [ :pick $curdate 4 6 ] :if ( $day = $dayresetlimit and $reblocker = 0) do={ /file set $filename contents=0 /file set $filewarn contents=0 /file set $fileref contents=0 /interface ppp-client set $interf disabled=no /file set $reblock contents=1 :log info "Limit reset, int $interf bring up" /delay delay-time=5; :log info "Clear int counters - reboot" #TODO find another method for interf clear counters /system reboot } :if ( $day != $dayresetlimit ) do={ /file set $reblock contents=0 } :local before :local correct :local ref :local newdata :local tx [/interface get $interf tx-byte] :local rx [/interface get $interf rx-byte] :set $newdata (( $rx + $tx ) / 1024 / 1024 ) :set $before [/file get $filename contents] :if ( $newdata < $before ) do={ :set $ref [/file get $fileref contents] :set $correct ( $before + $newdata - $ref ) /file set $fileref contents=$newdata /file set $filename contents=$correct } :if ( $newdata >= $before ) do={ /file set $filename contents=$newdata } :local traffic ([/file get $filename contents]) :log warning "Limit: $limit MB" :local percent ($traffic*100 / $limit) :log warning "Use: $percent%" /file set $filewarn contents=$percent :if ($percent >= 100) do={ /file set $filewarn contents=$percent /interface ppp-client set $interf disabled=yes } :if ($percent < 100 and $autointon = true) do={ :set $status [/interface get $interf value-name=disabled] :if ($status = true) do={ /interface ppp-client set $interf disabled=no } } } on-error={ :log error "Error ppp-clientLimiter "};
I use this script I’m fine, but I wanted to understand how I can insert a method in the script to send me an email after the traffic has passed? I tried to insert it myself but the passed mb sends me e-mails all the time. I wish you would just send me an email. Thanks in advance
Hello all,
I’m just posting the current version of the script for ethernet’s based traffic limiter which I’m currently using, where I added also some notification via Telegram Bot.
For this reason there is a global variable “notifyCount” to limit the number of Telegram notification that you’d like to receive.
Most of the script is the same, few changes to some part of the logic.
The main function to store data into firewall-L7 “data storage” is now part of a general global variable and the script is not run in a loop, but through a scheduler.
Armando
Ciao Armando, could you explain the usage of firewall-L7 “data storage”? It’s not really clear to me from your script code, or I’m missing another script to define $persistVar?
This script is fantastic!! Thank you so much for taking the time to make it. I have it running on my RB5009 running 7.1rc6, and everything is still working perfectly.
Hello. Please how i can modify LTE script for data quota reset every midnight (daily)?
I am running script every 1 hours and i want reset limit every day.
Hello
For LTE:
# /$$ /$$$$$$$$/$$$$$$$$ /$$ /$$ /$$ /$$ # | $$ |__ $$__/ $$_____/| $$ |__/ |__/ | $$ # | $$ | $$ | $$ | $$ /$$ /$$$$$$/$$$$ /$$ /$$$$$$ /$$$$$$ /$$$$$$ # | $$ | $$ | $$$$$ | $$ | $$| $$_ $$_ $$| $$|_ $$_/ /$$__ $$ /$$__ $$ # | $$ | $$ | $$__/ | $$ | $$| $$ \ $$ \ $$| $$ | $$ | $$$$$$$$| $$ \__/ # | $$ | $$ | $$ | $$ | $$| $$ | $$ | $$| $$ | $$ /$$| $$_____/| $$ # | $$$$$$$$| $$ | $$$$$$$$| $$$$$$$$| $$| $$ | $$ | $$| $$ | $$$$/| $$$$$$$| $$ # |________/|__/ |________/|________/|__/|__/ |__/ |__/|__/ \___/ \_______/|__/ # # Using: Set all var in User config section. Add scripts to schedule with onstart and interval 30 sek :do { ####################################################################################################### # User config #Set limit in MB :local limit 12288 #Set day to reset limit :local dayresetlimit 1 #Set interface :local interf "lte1" #Set auto bring up interface :local autointon true ####################################################################################################### :local filename "counter.txt" :local filewarn "warning.txt" :local fileref "refcount.txt" :local reblock "reblock.txt" :local status :if ([:len [/file find where name=$filewarn]] < 1 ) do={ /file print file=$filewarn where name=$filewarn /delay delay-time=2 /file set $filewarn contents=$percent }; :if ([:len [/file find where name=$filename]] < 1 ) do={ /file print file=$filename where name=$filename /delay delay-time=2; /file set $filename contents=0 } :if ([:len [/file find where name=$reblock]] < 1 ) do={ /file print file=$reblock where name=$reblock /delay delay-time=2; /file set $reblock contents=1 } :if ([:len [/file find where name=$fileref]] < 1 ) do={ /file print file=$fileref where name=$fileref /delay delay-time=2; /file set $fileref contents=0 } :local reblocker ([/file get $reblock contents]) :local curdate [/system clock get date] :local day [ :pick $curdate 4 6 ] :if ( $day = $dayresetlimit and $reblocker = 0) do={ /file set $filename contents=0 /file set $filewarn contents=0 /file set $fileref contents=0 /interface lte set $interf disabled=no /file set $reblock contents=1 :log info "Limit reset, int $interf bring up" /delay delay-time=5; :log info "Clear int counters - reboot" #TODO find another method for interf clear counters /system reboot } :if ( $day != $dayresetlimit ) do={ /file set $reblock contents=0 } :local before :local correct :local ref :local newdata :local tx [/interface get $interf tx-byte] :local rx [/interface get $interf rx-byte] :set $newdata (( $rx + $tx ) / 1024 / 1024 ) :set $before [/file get $filename contents] :if ( $newdata < $before ) do={ :set $ref [/file get $fileref contents] :set $correct ( $before + $newdata - $ref ) /file set $fileref contents=$newdata /file set $filename contents=$correct } :if ( $newdata >= $before ) do={ /file set $filename contents=$newdata } :local traffic ([/file get $filename contents]) :log warning "Limit: $limit MB" :local percent ($traffic*100 / $limit) :log warning "Use: $percent%" /file set $filewarn contents=$percent :if ($percent >= 100) do={ /file set $filewarn contents=$percent /interface lte set $interf disabled=yes } :if ($percent < 100 and $autointon = true) do={ :set $status [/interface get $interf value-name=disabled] :if ($status = true) do={ /interface lte set $interf disabled=no } } } on-error={ :log error "Error LTELimiter "};
for PPP-Client
# /$$ /$$$$$$$$/$$$$$$$$ /$$ /$$ /$$ /$$ # | $$ |__ $$__/ $$_____/| $$ |__/ |__/ | $$ # | $$ | $$ | $$ | $$ /$$ /$$$$$$/$$$$ /$$ /$$$$$$ /$$$$$$ /$$$$$$ # | $$ | $$ | $$$$$ | $$ | $$| $$_ $$_ $$| $$|_ $$_/ /$$__ $$ /$$__ $$ # | $$ | $$ | $$__/ | $$ | $$| $$ \ $$ \ $$| $$ | $$ | $$$$$$$$| $$ \__/ # | $$ | $$ | $$ | $$ | $$| $$ | $$ | $$| $$ | $$ /$$| $$_____/| $$ # | $$$$$$$$| $$ | $$$$$$$$| $$$$$$$$| $$| $$ | $$ | $$| $$ | $$$$/| $$$$$$$| $$ # |________/|__/ |________/|________/|__/|__/ |__/ |__/|__/ \___/ \_______/|__/ # # Using: Set all var in User config section. Add scripts to schedule with onstart and interval 30 sek :do { ####################################################################################################### # User config #Set limit in MB :local limit 12288 #Set day to reset limit :local dayresetlimit 1 #Set interface :local interf "ppp-out1" #Set auto bring up interface :local autointon true ####################################################################################################### :local filename "counter.txt" :local filewarn "warning.txt" :local fileref "refcount.txt" :local reblock "reblock.txt" :local status :if ([:len [/file find where name=$filewarn]] < 1 ) do={ /file print file=$filewarn where name=$filewarn /delay delay-time=2 /file set $filewarn contents=$percent }; :if ([:len [/file find where name=$filename]] < 1 ) do={ /file print file=$filename where name=$filename /delay delay-time=2; /file set $filename contents=0 } :if ([:len [/file find where name=$reblock]] < 1 ) do={ /file print file=$reblock where name=$reblock /delay delay-time=2; /file set $reblock contents=1 } :if ([:len [/file find where name=$fileref]] < 1 ) do={ /file print file=$fileref where name=$fileref /delay delay-time=2; /file set $fileref contents=0 } :local reblocker ([/file get $reblock contents]) :local curdate [/system clock get date] :local day [ :pick $curdate 4 6 ] :if ( $day = $dayresetlimit and $reblocker = 0) do={ /file set $filename contents=0 /file set $filewarn contents=0 /file set $fileref contents=0 /interface ppp-client set $interf disabled=no /file set $reblock contents=1 :log info "Limit reset, int $interf bring up" /delay delay-time=5; :log info "Clear int counters - reboot" #TODO find another method for interf clear counters /system reboot } :if ( $day != $dayresetlimit ) do={ /file set $reblock contents=0 } :local before :local correct :local ref :local newdata :local tx [/interface get $interf tx-byte] :local rx [/interface get $interf rx-byte] :set $newdata (( $rx + $tx ) / 1024 / 1024 ) :set $before [/file get $filename contents] :if ( $newdata < $before ) do={ :set $ref [/file get $fileref contents] :set $correct ( $before + $newdata - $ref ) /file set $fileref contents=$newdata /file set $filename contents=$correct } :if ( $newdata >= $before ) do={ /file set $filename contents=$newdata } :local traffic ([/file get $filename contents]) :log warning "Limit: $limit MB" :local percent ($traffic*100 / $limit) :log warning "Use: $percent%" /file set $filewarn contents=$percent :if ($percent >= 100) do={ /file set $filewarn contents=$percent /interface ppp-client set $interf disabled=yes } :if ($percent < 100 and $autointon = true) do={ :set $status [/interface get $interf value-name=disabled] :if ($status = true) do={ /interface ppp-client set $interf disabled=no } } } on-error={ :log error "Error ppp-clientLimiter "};
Check hour instead of day, for the reset decision.
BTW, there is no need for a reboot, to reset the LTE counters. Toggle off/on will do the trick as well.
http://forum.mikrotik.com/t/interface-data-quota/79514/38
Hello all,
I’m just posting the current version of the script for ethernet’s based traffic limiter which I’m currently using, where I added also some notification via Telegram Bot.
For this reason there is a global variable “notifyCount” to limit the number of Telegram notification that you’d like to receive.
Most of the script is the same, few changes to some part of the logic.
The main function to store data into firewall-L7 “data storage” is now part of a general global variable and the script is not run in a loop, but through a scheduler.:global persistVar :global notifyCount :do { #################################################################################################### # User config #Set limit in MB :local limit 390000 #Set day to reset limit :local dayresetlimit "01" #Set interface :local interf "ether1-WAN" #Set auto bring up interface :local autointon true #Delta startup value :local startValue 0 #################################################################################################### :local notifyLimit 1 :local botId "your_bot_id" :local chatId "your_chat_id" :local site [/system identity get value-name=name] :local day ([:pick [/system clock get date] 4 6]) :local mon ([:pick [/system clock get date] 0 3]) :local year ([:pick [/system clock get date] 7 11]) :local date "$day-$mon-$year" :local time (:put [/system clock get time]) :local newdata :local result :local ref :local status :local tx [/interface get $interf tx-byte] :local rx [/interface get $interf rx-byte] :set $newdata (($rx + $tx) / 1024 / 1024) :if ([:len [$persistVar wan1_counter]] < 1 ) do={ $persistVar wan1_counter 0 } :if ([:len [$persistVar wan1_rebootblock]] < 1 ) do={ $persistVar wan1_rebootblock 1 } :if ([:len [$persistVar wan1_offset]] < 1 ) do={ $persistVar wan1_offset 0 } :if ([:len [$persistVar wan1_refdata]] < 1 ) do={ $persistVar wan1_refdata 0 } :local rebootblocker ([$persistVar wan1_rebootblock]) :if ( $day = $dayresetlimit and $rebootblocker = 0) do={ $persistVar wan1_counter 0 $persistVar wan1_offset $newdata $persistVar wan1_refdata 0 /interface ethernet set $interf disabled=no $persistVar wan1_rebootblock 1 :set notifyCount 0 :log warning "Resetting limits, int $interf bring up" } :if ( $day != $dayresetlimit ) do={ $persistVar wan1_rebootblock 0 } :local before [$persistVar wan1_counter] :local offset [$persistVar wan1_offset] :if ( $newdata < $before ) do={ $persistVar wan1_offset 0 :set $ref [$persistVar wan1_refdata] :if ( $newdata < $ref ) do={ :set $ref (0) } :set $result ($before + $newdata - $ref + $startValue) $persistVar wan1_refdata $newdata $persistVar wan1_counter $result } else={ :set $result ($newdata - $offset + $startValue) $persistVar wan1_counter $result } :local traffic ([$persistVar wan1_counter]) :local percent ($traffic*100 / $limit) :if ($percent >= 100) do={ :if ($notifyCount <= $notifyLimit) do={ /tool fetch url="https://api.telegram.org/bot$botId/sendMessage?chat_id=$chatId&text=MikroTik $site info:%0A[$date $time]%0AWAN1 disabled for exceeding bandwidth limit $limit MB" keep-result=no :log warning "$interf disabled for exceeding bandwidth limit $limit MB" :set $notifyCount ($notifyCount + 1) :delay 3 } /interface ethernet set $interf disabled=yes } :if ($percent < 100 and $autointon = true) do={ :set $status [/interface get $interf value-name=disabled] :if ($status = true) do={ /interface ethernet set $interf disabled=no } } } on-error={ :log error "Error WAN1_Limiter "}Armando
Hi,
Thank you for your script. I have few questions/suggestions.
1st i had problem with dates, so i fixed it:
[user@Tik_Vikendica] > :put [/system/clock/get date]
2024-05-15
[user@Tik_Vikendica] > :put ([:pick [/system clock get date] 8 11])
15
[user@Tik_Vikendica] > :put ([:pick [/system clock get date] 5 7])
05
[user@Tik_Vikendica] > :put ([:pick [/system clock get date] 0 4])
2024
2nd, correct me if i’m wrong, but I think you have error in calculations.
variable limit should store data in MB (200GB is 204800MB)
variable $newdata (($rx + $tx) / 1024 / 1024) store data in GB instead of MB
variable traffic ([$persistVar wan1_counter]) forward you data in GB
thus
variable percent ($traffic*100 / $limit) provide me wrong readings.
Example:
telegegram script return the following:
&text=MikroTik $site info:%0A[$date $time]%0AInterface $interf exeeded usage of $traffic of limit $limit MB%0ANewData $newdata (($rx + $tx)%0APercent is: $percent%0A"
and output is
Interface lte1 exeeded usage of 0 of limit 204800 MB
NewData 70 ((35474921 38074072)
Percent is: 0
wan1_counter is 70 which corespond actual usage of 70GB.
If i change limit variable to 200, i got correct reading
Interface lte1 exeeded usage of 70 of limit 200 MB
NewData 70 ((35474921 38074072)
Percent is: 35
BR,