Quantcast
Channel: MikroTik
Viewing all articles
Browse latest Browse all 15482

Scripting • LTE script collection

$
0
0
Hi everyone,
this is my first official post and want to share with you some script that I've been using for nearly a year (and improving them in the process), many (if not all) were previously written by other guys (which I thank a lot and quote if I found the original forum link) but I made some additions and changes because some of them had (minor) issues with newer routerOS versions, like different date structures or else that broke the script.
Everything was tested and still running on my Chateau 5g ax.

The first one is a data counter, I made a monthly and daily one which are intercompatible (I'm running both at the same time beacuse my ISP have both a daily and monthly cap), I use them just to be notified of traffic usage but you can also block the data automatically if you need.
This one has to be scheduled to acquire data each time is executed, right now I'm running them (both the daily and monthly) every 10 or 20 seconds but on an external usb drive (just add usb1/ before) on every call to the files on the ROM, I do this to reduce internal ROM wearout, before using the usb drive I scheduled them every 20 minutes and it was fine, unfortunately if you have a really fast connection you can reach your cap without even notice in this case.
To notify the user in this script I'm using sms so you just have to set your number (multiple times and with country code, I wanted to optimise it with a single one but never did it) near the end of the script or change it with a telegram notification.
The monthly script is set to send a notification at 25/50/80/100% data while the daily one at 50/75/90/100% but you can easily customise them.
You can set the data limit and the day or hour reset at the beginning, as well as the interface
Monthly:
Code:
#   /$$    /$$$$$$$$/$$$$$$$$ /$$       /$$               /$$   /$$                        #  | $$   |__  $$__/ $$_____/| $$      |__/              |__/  | $$                        #  | $$      | $$  | $$      | $$       /$$ /$$$$$$/$$$$  /$$ /$$$$$$    /$$$$$$   /$$$$$$ #  | $$      | $$  | $$$$$   | $$      | $$| $$_  $$_  $$| $$|_  $$_/   /$$__  $$ /$$__  $$#  | $$      | $$  | $$__/   | $$      | $$| $$ \ $$ \ $$| $$  | $$    | $$$$$$$$| $$  \__/#  | $$      | $$  | $$      | $$      | $$| $$ | $$ | $$| $$  | $$ /$$| $$_____/| $$      #  | $$$$$$$$| $$  | $$$$$$$$| $$$$$$$$| $$| $$ | $$ | $$| $$  |  $$$$/|  $$$$$$$| $$      #  |________/|__/  |________/|________/|__/|__/ |__/ |__/|__/   \___/   \_______/|__/      #  #  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 480000 #Set day to reset limit:local dayresetlimit 20#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 lmonth "lastmonth.txt":local sms "sms.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}:if ([:len [/file find where name=$lmonth]] < 1 ) do={/file print file=$lmonth where name=$lmonth/delay delay-time=2;/file set $lmonth contents=0}:if ([:len [/file find where name=$sms]] < 1 ) do={/file print file=$sms where name=$sms/delay delay-time=2;/file set $sms contents=0}:local reblocker ([/file get $reblock contents]):local traffic ([/file get $filename contents]):local curdate [/system clock get date]:local day [ :pick $curdate 8 10 ]:if ( $day = $dayresetlimit and $reblocker = 0) do={                     /file set $lmonth contents=$traffic/file set $filename contents=0/file set $filewarn contents=0/file set $fileref contents=0                     /file set $sms 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"/interface/reset-counters [find name=lte1]} :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]                                           # BPWL by counter reset then zero out old ref value                                           :if ( $newdata < $ref ) do={                                           set $ref (0)                                            }:set $correct ( $before + $newdata - $ref ) /file set $fileref contents=$newdata/file set $filename contents=$correct} :if ( $newdata >= $before ) do={/file set $filename contents=$newdata}:log warning "Limit: $limit MB":local traffic ([/file get $filename contents]):local percent ($traffic*100 / $limit):log warning "Use: $percent% / $traffic MB"/file set $filewarn contents=$percent:local smsr ([/file get $sms contents]):if ($percent >= 25 and $smsr=0) do={/file set $sms contents=1                     /tool sms send lte1 "YOURNUMBERHERE" \ message="Dati Mensili 25%"  }:if ($percent >= 50 and $smsr <=1) do={/file set $sms contents=2                     /tool sms send lte1 "YOURNUMBERHERE" \ message="Dati Mensili 50%"  }:if ($percent >= 80 and $smsr <= 2) do={/file set $sms contents=3                     /tool sms send lte1 "YOURNUMBERHERE" \ message="Dati Mensili 80%"  }:if ($percent >= 100 and $smsr <= 3) do={/file set $filewarn contents=$percent                     /file set $sms contents=4                     /tool sms send lte1 "YOURNUMBERHERE" \ message="Raggiunta soglia dati mensili" #/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 "};
Daily
Code:
#   /$$    /$$$$$$$$/$$$$$$$$ /$$       /$$               /$$   /$$                        #  | $$   |__  $$__/ $$_____/| $$      |__/              |__/  | $$                        #  | $$      | $$  | $$      | $$       /$$ /$$$$$$/$$$$  /$$ /$$$$$$    /$$$$$$   /$$$$$$ #  | $$      | $$  | $$$$$   | $$      | $$| $$_  $$_  $$| $$|_  $$_/   /$$__  $$ /$$__  $$#  | $$      | $$  | $$__/   | $$      | $$| $$ \ $$ \ $$| $$  | $$    | $$$$$$$$| $$  \__/#  | $$      | $$  | $$      | $$      | $$| $$ | $$ | $$| $$  | $$ /$$| $$_____/| $$      #  | $$$$$$$$| $$  | $$$$$$$$| $$$$$$$$| $$| $$ | $$ | $$| $$  |  $$$$/|  $$$$$$$| $$      #  |________/|__/  |________/|________/|__/|__/ |__/ |__/|__/   \___/   \_______/|__/      #  #  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 100000 #Set hour to reset limit:local hourresetlimit "00"#Set interface:local interf "lte1"#Set auto bring up interface :local autointon true#######################################################################################################:local filename "dcounter.txt":local filewarn "dwarning.txt":local fileref "drefcount.txt":local reblock "dreblock.txt":local sms "dsms.txt":local ld1 "lastday1.txt":local ld2 "lastday2.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}:if ([:len [/file find where name=$sms]] < 1 ) do={/file print file=$sms where name=$sms/delay delay-time=2;/file set $sms contents=0}:if ([:len [/file find where name=$ld1]] < 1 ) do={/file print file=$ld1 where name=$ld1/delay delay-time=2;/file set $ld1 contents=0}:if ([:len [/file find where name=$ld2]] < 1 ) do={/file print file=$ld2 where name=$ld2/delay delay-time=2;/file set $ld2 contents=0}:local reblocker ([/file get $reblock contents]):local traffic ([/file get $filename contents]):local rld1 ([/file get $ld1 contents]):local curdate [/system clock get time]:local time [ :pick $curdate 0 2 ]:if ( $time = $hourresetlimit and $reblocker = 0) do={                     /file set $ld2 contents=$rld1                     /file set $ld1 contents=$traffic/file set $filename contents=0/file set $filewarn contents=0/file set $fileref contents=0                     /file set $sms contents=0                     /file set $reblock contents=1/interface lte set $interf disabled=no:log info "Limit reset, int $interf bring up" /delay delay-time=5;:log info "Clear int counters"/interface/reset-counters [find name=lte1]} :if ( $time != $hourresetlimit ) 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]                                           # BPWL by counter reset then zero out old ref value                                           :if ( $newdata < $ref ) do={                                           set $ref (0)                                            }:set $correct ( $before + $newdata - $ref ) /file set $fileref contents=$newdata/file set $filename contents=$correct} :if ( $newdata >= $before ) do={/file set $filename contents=$newdata}:log warning "Limit: $limit MB":local traffic ([/file get $filename contents]):local percent ($traffic*100 / $limit):log warning "Use: $percent% / $traffic MB"/file set $filewarn contents=$percent:local smsr ([/file get $sms contents]):if ($percent >= 50 and $smsr=0) do={/file set $sms contents=1                     /tool sms send lte1 "YOURNUMBERHERE" \ message="Daily data 50%"  }:if ($percent >= 75 and $smsr <=1) do={/file set $sms contents=2                     /tool sms send lte1 "YOURNUMBERHERE" \ message="Daily data 75%"  }:if ($percent >= 90 and $smsr <= 2) do={/file set $sms contents=3                     /tool sms send lte1 "YOURNUMBERHERE" \ message="Daily data 90%"  }:if ($percent >= 100 and $smsr <= 3) do={/file set $filewarn contents=$percent                     /file set $sms contents=4                     /tool sms send lte1 "YOURNUMBERHERE" \ message="Daily data 100%" #/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 "};
Original script from viewtopic.php?t=87565

The second one is probably the most useful and brilliant, I did made some changes to the original. It's basically a netwatch to restore connection in case something goes wrong. It starts by rebooting the lte interface after netwatch is down for a minutes, then it take out any cell lock or band lock after two minutes and finally, after 3 minutes it reboot the system and also send a notification when the system goes back online and what it did to get back.
Start by creating a netwatch:
Code:
/tool netwatch add host=1.1.1.1 interval=10s timeout=500ms disabled=no comment=InternetWatchDog
On UP add this:
Just like on the data counter you can change the sms notification with telegram one, remember to insert you phone number on the script
Code:
/system scheduler remove [find where name~"SiBexInternetWatchDog_"];/log warning "RESET Netwatch scheduled DOWN-script... ISP WORKS";:local nws "smsnw.txt":local nwsr ([/file get $nws contents]):if ($nwsr=1) do={/file set $nws contents=0                     /tool sms send lte1 "YOURPHONEHERE" \ message="Network down v1, Connection restored :-)" #                     :delay 2#                     /system script run sms }:if ($nwsr=2) do={/file set $nws contents=0                     /tool sms send lte1 "YOURPHONEHERE" \ message="Network down v2, Connection restored :-)"  #                    :delay 2 #                   /system script run sms }:if ($nwsr=3) do={/file set $nws contents=0                     /tool sms send lte1 "YOURPHONEHERE" \ message="Network down v3, Connection restored :-)"#                     :delay 2 #                     /system script run sms }:if ($nwsr=4) do={/file set $nws contents=0                     /tool sms send lte1 "YOURPHONEHERE" \ message="Minor down, connection up again" #                     :delay 2#                     /system script run sms }
And on down this one:
The script must be created next in the script section, otherwise with the newer routeros version it doesn't get all the aurization to perform all the actions we need by executing it on netwatch
Code:
/system script run Nwdown
Finally we need to create in the script section a script called Nwdown also toggling on all the policy options and pasting this inside:
Code:
log error "start Netwatch DOWN-script...";# ################ MAIN PROGRAM BELOW, NOT HERE ############### ################ DEFINE FUNCTION SOLVING Crossing Midnight ############################ Fix Crossing 24:00:00=00:00:00/local SiBFixDateTime do={/local SiBTimeToChange "23:45:00";/local SiBTimeToChange $2;/local SiBTimeDiffToAdd "60m2s"; # diff time < 24h/local SiBTimeDiffToAdd $3; # diff time < 24h#/local SiBDate "dec/31/2020"/local SiBDate $1/local SiBDateCorrected;#log warning ("Source: ".$SiBDate." ".$SiBTimeToChange." + ".$SiBTimeDiffToAdd);#put ("Source: ".$SiBDate." ".$SiBTimeToChange." + ".$SiBTimeDiffToAdd);# Add diff time <=24h/local SiBTimeAndDiffTime ($SiBTimeToChange + $SiBTimeDiffToAdd );/if ([/len $SiBTimeAndDiffTime]=8) do={/set $SiBDateCorrected ($SiBDate." ".$SiBTimeAndDiffTime); };/if ([/len $SiBTimeAndDiffTime]>8) do={  /set $SiBTimeAndDiffTime ($SiBTimeAndDiffTime-1d);  ## Add 24h to date, copy time if exist.  set $SiBDateCorrected ($SiBDate." ".$SiBTimeAndDiffTime);  # Days: 01-27  local SiBDayToChange [/pick $SiBDateCorrected 4 6;];  if ($SiBDayToChange<=27) do={      set $SiBDayToChange ($SiBDayToChange+1);      if ([/len $SiBDayToChange]=1) do={set $SiBDayToChange ("0".$SiBDayToChange)}      set $SiBDateCorrected ( [/pick $SiBDateCorrected 0 4].$SiBDayToChange.[/pick $SiBDateCorrected 6 20] );    } else={      if ($SiBDayToChange!=31) do={          # Days: 28..30; Main magic do internal scheduler.          /system scheduler remove [find name=SiBTempScheduler2qw34er5v78bn90m];          /system scheduler add name=SiBTempScheduler2qw34er5v78bn90m on-event={nothing } start-time=00:00:01 start-date=( [/pick $SiBDateCorrected 0 4].($SiBDayToChange+1).[/pick $SiBDateCorrected 6 11 ] );          set $SiBDateCorrected ([system scheduler get [find name=SiBTempScheduler2qw34er5v78bn90m] start-date].[/pick $SiBDateCorrected 11 20 ]);          /system scheduler remove [find name=SiBTempScheduler2qw34er5v78bn90m];        } else={          # Day 31 for Jan..Nov          /local SiBMonths ("jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec");          /local SiBMounthToChange [/pick $SiBDateCorrected 0 3];          for x from=0 to=10 do={if ([/pick $SiBMonths $x]=$SiBMounthToChange) do={ set $SiBDateCorrected ([pick $SiBMonths ($x+1)]."/01".[/pick $SiBDateCorrected 6 20 ]) }}          # Day 31 for Dec          if ($SiBMounthToChange="dec") do={ set $SiBDateCorrected ("jan/01/".([/pick $SiBDateCorrected 7 11]+1).[/pick $SiBDateCorrected 11 20] )}      };    };};#log warning ("New date time: ".$SiBDateCorrected);#put ("New date time: ".$SiBDateCorrected);:return $SiBDateCorrected};# ################ MAIN PROGRAM ############################ Select a proper Netwatchlocal LocNetWatchHost 1.1.1.1;local LocNetWatchHostComment "InternetWatchDog";# Still is status down?local LocStatus [/tool netwatch get [find host=$LocNetWatchHost comment=$LocNetWatchHostComment ] status];if ($LocStatus != "down") do={/quit;}# Convert the Netwatch SINCE to separate date and time of current down-time.local LocSince  [/tool netwatch get [find host=$LocNetWatchHost comment=$LocNetWatchHostComment status=down ] since];local LocSinceDate ([/pick $LocSince 0 11]);local LocSinceTime ([/pick $LocSince 11 20]);# Add action to future via scheduler/system scheduler remove [find where name~"SiBexInternetWatchDog_v"];#create sms file and set first nwdown value:local nws "smsnw.txt"; :if ([:len [/file find where name=$nws]] < 1 ) do={/file print file=$nws where name=$nws;};:delay 1/file set $nws contents=4;# Try MAIN ACTION 1 - LTE ReEnable after 1mlocal SiBCrossMid [$SiBFixDateTime $LocSinceDate $LocSinceTime 1m ];local SiBStartDate [pick $SiBCrossMid 0 11];local SiBStartTime [pick $SiBCrossMid 11 20];/system scheduler add name=SiBexInternetWatchDog_v1 on-event={:log info message="Network down v1 script";  /interface lte set 0 band=""; :local nws "smsnw.txt"; /file set $nws contents=1;/interface/lte/disable [find name=lte1]; :delay 5; /interface/lte/enable [find name=lte1];} policy=reboot,read,write,policy,test,password,sniff,sensitive,romon,ftp start-date=$SiBStartDate start-time=$SiBStartTime;# Try MAIN ACTION 2 - Reboot after 2mlocal SiBCrossMid [$SiBFixDateTime $LocSinceDate $LocSinceTime 2m ];local SiBStartDate [pick $SiBCrossMid 0 11];local SiBStartTime [pick $SiBCrossMid 11 20];/system scheduler add name=SiBexInternetWatchDog_v2 on-event={:log info message="Network down v2 script"; /interface lte at-chat lte1 input="at+qnwlock=\"common/4g\",0"; :delay 5; /interface lte set 0 band=""; :local nws "smsnw.txt"; /file set $nws contents=2;} policy=reboot,read,write,policy,test,password,sniff,sensitive,romon,ftp start-date=$SiBStartDate start-time=$SiBStartTime;# Try MAIN ACTION 3 - Reboot after 3mlocal SiBCrossMid [$SiBFixDateTime $LocSinceDate $LocSinceTime 3m ];local SiBStartDate [pick $SiBCrossMid 0 11];local SiBStartTime [pick $SiBCrossMid 11 20];/system scheduler add name=SiBexInternetWatchDog_2 on-event={:log info message="Network down v1 script"; :local nws "smsnw.txt"; /file set $nws contents=3; :delay 2; /system reboot;} policy=reboot,read,write,policy,test,password,sniff,sensitive,romon,ftp start-date=$SiBStartDate start-time=$SiBStartTime;log error "stop Netwatch DOWN-script, Future action are scheduled";heduled";
Original code from viewtopic.php?t=151492

The last useful one just forward the sms received on the router simcard on your phone with sms or telegram notification, I paste here the code in case the original website goes down but I haven't changed anything. Schedule it with:
Code:
/system scheduler add interval=5s name=sch.sms-forward-telegram on-event=sms-forward-telegram
And create a script called sms-forward-telegram with this inside:
Code:
:local smsPhone;:local smsMessage;:local smsContent;:local smsContent1;:foreach i in=[/tool sms inbox find message=""] do={/tool sms inbox remove $i}:foreach i in=[/tool sms inbox find] do={:log info "SMS to Telegram script started";:set smsPhone [/tool sms inbox get $i phone];:set smsMessage [/tool sms inbox get $i message];:for i from=0 to=([:len $smsMessage] - 1) do={   :local char [:pick $smsMessage $i]   :if ($char = "\n") do={    :set $char "%0A";  }  :if ($char = " ") do={    :set $char "%20";  }  :if ($char = "-") do={    :set $char "%2D";  }  :if ($char = "\?") do={    :set $char "%3F";  }  :if ($char = "!") do={    :set $char "%21";  }  :if ($char = "+") do={    :set $char "%2B";  }  :if ($char = "%") do={    :set $char "%22";  }  :if ($char = "'") do={    :set $char "%27";  }  :if ($char = "(") do={    :set $char "%28";  }  :if ($char = ")") do={    :set $char "%29";  }  :if ($char = ",") do={    :set $char "%2C";  }  :if ($char = ".") do={    :set $char "%2E";  }  :if ($char = ":") do={    :set $char "%3A";  }  :if ($char = ";") do={    :set $char "%3B";  }    :if ($char = "=") do={    :set $char "%3D";  }  :if ($char = "&") do={    :set $char "%26";  }  :if ($char = "*") do={    :set $char "%2A";  }  :if ($char = "/") do={    :set $char "%2F";  } :set smsContent ($smsContent . $char);}:set smsContent1 "$smsPhone $smsContent";/tool fetch url="https://api.telegram.org/botNNNNNNNNN:CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC/sendMessage?chat_id=_CHATID_&text=$smsContent1";#/tool sms send lte1 "YOURNUMBERHERE" \ message="$smsContent1";/tool sms inbox remove $i:log info "SMS to Telegram script complete";}
Original code from http://blog.redax.hu/2021/02/mikrotik-s ... rding.html

Lastly, this one is all mine and just reports many different net info like primary lte band, CA bands, uptime etc. with an sms, I did included it on the netwatch connection restore up script, you can use it like that (by toggling the comment and naming the script sms) or standalone:
As always remember to insert you phone number. This one as it is only works with sms for some reasons, not telegram.
Code:
/tool sms send lte1 "YOURNUMBERHERE" \ message=("Main:".(put ([/interface/lte/monitor lte1 once as-value ]->"primary-band")),"\nCA:".(put([/interface/lte/monitor lte1 once as-value ]->"ca-band")),"\nCellID:".(put([/interface/lte/monitor lte1 once as-value ]->"current-cellid")),"\nUpTime:".(put([/interface/lte/monitor lte1 once as-value ]->"session-uptime")))
You can also set it to also report data usage if you're using that script:
Code:
:local filename "counter.txt":local traffic ([/file get $filename contents])/tool sms send lte1 "YOURNUMBERHERE" \ message=("Main:".(put ([/interface/lte/monitor lte1 once as-value ]->"primary-band")),"\nCA:".(put([/interface/lte/monitor lte1 once as-value ]->"ca-band")),"\nCellID:".(put([/interface/lte/monitor lte1 once as-value ]->"current-cellid")),"\nUpTime:".(put([/interface/lte/monitor lte1 once as-value ]->"session-uptime"))"\nDati:$traffic MB")
I just wanted to share these script with you given how much time I spent searching and modifying them
Just hope you like them
And also hope to have deleted my personal data and not screwed the script in the process, if so just write me.
Luca

Statistics: Posted by jfirex — Wed Jan 17, 2024 8:58 pm



Viewing all articles
Browse latest Browse all 15482

Trending Articles