AVA Studio ID

lisensi

Iklan

AVA Studio
30 December 2022, 11:16 WITA (GMT+8)
Last Updated 2022-12-30T06:46:41Z

Script MikroTik RouterOS - Automated Usage Script without usermanager

Advertisement
MikroTik RouterOS Script - Automated Usage Script without usermanager

It is possible to create an automated usage script in a Mikrotik router that tracks and reports on the usage of the router's resources, such as bandwidth and memory, without using the User Manager feature. To do this, you will need to use the Mikrotik RouterOS command-line interface (CLI) or the Mikrotik RouterOS web-based configuration interface to create a script that gathers the relevant usage data and processes it in some way, such as by generating a report or sending an email notification.

Here is an example of how you might create an automated usage script in a Mikrotik router that tracks the usage of the router's bandwidth and memory:
  1. Open the Mikrotik RouterOS CLI or web-based configuration interface.
  2. Create a script to gather the usage data. This can be done using the "/system script" command, followed by the appropriate parameters to specify the script name and any other relevant settings. The script might include commands such as "/system resource print" to gather information about the router's memory usage, and "/queue simple print" to gather information about the router's bandwidth usage.
  3. Set up a schedule for the script to run. This can be done using the "/system scheduler" command, followed by the appropriate parameters to specify the frequency and timing of the script.
  4. Add the script to the scheduler using the "/system scheduler add" command, followed by the appropriate parameters to specify the script name and the schedule you created in step 3.
Once these steps have been completed, the Mikrotik router will automatically run the script at the specified intervals, gathering data about the router's bandwidth and memory usage and processing it in some way (such as by generating a report or sending an email notification). You can customize the script to suit your specific needs and requirements.

Summary
 I wrote a usage tracking script based on the original autopay script
The way I run it uses the Mikrotik box setup to transparently transfer everything, then I create a queue for each IP address to track usage. On my test box (A PowerRouter 732), I currently have 3 type C blocks running at only 3% cpu (Multi CPU Enabled). This system is designed for download-based billing only and will report the number of downloads used by one IP address (or bucket if you're setting up a queue with multiple IP addresses) per month. (This can be easily reversed)

If you use an alternate version of the end-of-month script, you can configure the scheduler to run the monitor every hour without having to worry about lots of reports coming in. Also, I've since written a smaller manual script for the accounts so they can run it at any time and get usage reports by email (see manual usage reporting script). labour)

Todo

  • the ability to save to a file on mikrotik so that it counts both the data in the current queue + the usage of the data stored in the file (in case you lose power to the device or you have to restart at any time ) Redesigned - now saves downloaded data at the end of comments so scripts can also be exported if needed. The page is now updated to save data to the newly added comment field (I've been using it since version 3.24)
  • further modified the month-end script so that it can only be activated on the last hour of the last day of the month. This means you can then run the usage script every hour to get updates more often. This is done, see the original and alternate versions of the script Month-end See below the script for more details on how it works. 
  •  modify the usage script and the monthly report to use a kbyte variable instead of a byte (this is not a big deal, as the integer variable mikroik allows is 64 bit, so some may be higher than that). 9223372036854775807. - allows sending to customer email address AND local support team. Done: you can now specify a default email address in usage reports (to send to your support person/account) and the address in the queue will become the emailed customer address, if you leave it blank, for example, Customer !50#!00#0000 instead of Customer!50#customer@example.com!00#0000, it will skip emailing the report to the customer, but will always send a report to the account/support email address
Current known error
The month-end script will not complete (and generate month-end reports) if the start time is set to 00:00:00 for the hourly scheduler. Fix: set start time to 00:30:00 or you can also run month end report script manually if you miss

The Scheduler
Hourly
If you want to query hourly make sure you are using the new short version of the end of the month script first and also make sure your start time is not 00:00:00 (set it to 30 minutes are correct as below) This ensures that the month-end (before >1h00 on the 1st of every month) matches and reports at the end of the month.

MikroTik RouterOS Script - Automated Usage Script without usermanager
/system scheduler
add comment="" disabled=no interval=1h name=Overseer on-event="/system script run overseer" start-date=jan/01/1970 start-time=00:30:00
The Scripts
Script: overseer
Like the automated billing, this also has a calling script "overseer"

/code>:global found

/system script run monthend

:if ([$found] = "true") do={/system script run monthlyreport; :log info "--Completed Monthly Report--"} else={ /system script run usagereport; :log info "--Completed Usage Report--"}
Script: monthend
At a set rollover date you want the system to run the monthend script to do the final site tally and reset all counters. By default, it is set to run at the begining of each month (00 hour, 1st day) you can however change this to run on any day.

:local date
:local time
:local day
:local month
:local year
:local hour
:global found ""
 
:set date [/system clock get date]
:set time [/system clock get time]
:set day [:pick $date 4 6]
:set hour [:pick $time 0 2]

:if ([$day] = "01" ) do={ :if ([$hour] = "00" ) do={:set found "true" } else={ :set found "false" } } else={ :set found "false" }
Script: usagereport
The main usage reports, takes the name of each queue and looks firstly for a hint that any data is contained in this. I have used! to seperateds the initial data block so If it finds a ! its will treat this name as data.

The data's then broken up from a name like this: Any Site name!50#info@avastudio.org.com!00#0000 this then give us $sitename (descriptive name) $gigs (gigabyte download limit) $email (address to email report to) $lastwarning (previous usage warning level) $bytesdownsaved (last total usage recording)

In previous versions of the script I had the values stored in the name, but now since it's available the comment is a much better place to store this data. This-also mean you can give users static URL's to access their own bandwidth graphs/queues.

:local content
:local i
:local sitename
:local gigs
:local email
:local megstotal
:local totalcurrent
:local bytesdowncurrent
:local bytesupcurrent
:local megsdowncurrent
:local megsupcurrent
:local percentage
:local lastwarning
:local warninglevel
:local warn
:local update
:local newwarning
:local bytesdownsaved
:local bytestotal

#Script based on Automated billing script at AVA Studio ID:log info "------ Begining Daily Usage Reports -------"

#For each queue in the list
:foreach i in=[/queue simple find comment !=""] do={

#Pull_comment out of queue & divide up accordingly
:set content [/queue simple get $i comment]

#Determine_variables from comment
#Format is: sitename! gigsallowed # who is to email! last warning levels(0-45-75-90-99)
:if ([:find $content "!"] != "") do={
  :local pos1 [:find $content "!"]
  :local pos4 [:len $content]
  :local pos2 ([:find [:pick $content ($pos1+1) $pos4] "#"]+$pos1+1)
  :local pos3 ([:find [:pick $content ($pos2+1) $pos4] "!"]+$pos2)
  :set sitename [:pick $content 0 ($pos1)]
  :set gigs [:pick $content ($pos1+1) $pos2]
  :set email [:pick $content ($pos2+1) ($pos3+1)]
  :set totalcurrent [/queue simple get $i bytes]
  :set lastwarning [:pick $content ($pos3+2) ($pos3+4)]
  :local pos5 [:find $totalcurrent "/"]
  :local pos6 [:len $totalcurrent]
  :set bytesupcurrent ([:pick $totalcurrent 0 ($pos5)])
  :set bytesdowncurrent ([:pick $totalcurrent ($pos5+1) $pos6])
  :set megsupcurrent ($bytesupcurrent / 1048576)
  :set bytesdownsaved ([:pick $content ($pos3+5) $pos4])
  :set bytestotal ($bytesdowncurrent + $bytesdownsaved)
  :set megsdowncurrent ($bytestotal / 1048576)

#Begin calculating usage percentage
  :set percentage ( ( $bytestotal * 100) / ($gigs * 1073741824 ) )
  :log info "$sitename: $percentage%"
  :if ([$percentage] < 50) do={ :set warninglevel "00" }
  :if ([$percentage] > 50) do={
    :if ([$percentage] < 75) do={ :set warninglevel "50" }
    :if ([$percentage] > 75) do={ :set warninglevel "75" }
  }
  :if ([$percentage] > 75) do={
    :if ([$percentage] < 90) do={ :set warninglevel "75" }
    :if ([$percentage] > 90) do={ :set warninglevel "90" }
  }
  :if ([$percentage] > 90) do={
    :if ([$percentage] < 100) do={ :set warninglevel "90" }
    :if ([$percentage] > 100) do={ :set warninglevel "99" }
  }

# Parse warning necessity
 :if ([$warninglevel] > $lastwarning ) do={ :set warn "true" ; :set update "true" }
 :if ([$warninglevel] = $lastwarning ) do={ :set warn "false" ; :set update "false" }
 :if ([$warninglevel] < $lastwarning ) do={ :set warn "false" ; :set update "true" }

#Update Warning Levels
 :if ([$update] = true ) do={ :set newwarning $warninglevel } else={ :set newwarning $lastwarning }
 :if ([$warn] = true ) do={
#Check for email address in queue comment
 :if ([$email] != "" ) do={
  /tool e-mail send to="$email" from="noreply@example.com" server="1.3.3.7" subject="$sitename: Usage at $percentage" body="This message_is to inform you of the current usage for $sitename
The current warning trigger is $warninglevel%.

Thisis site has downloaded $megsdowncurrent MB, which is overs $percentage% of the $gigs GB monthly download allowance.

This is an Automatically generated Email that is sent out when users reach 50%, 75%, 90% and 100% of their cap.

System_Traffic_Monitor,
accounts@example.com"
}
#Sends e-mail to support/accounts also
  /tool e-mail send to="accounts@example.com" from="noreply@econtoh.com" server="1.3.3.7" subject="$sitename: Usage at $percentage" body="Current usage for $sitename - trigger is $warninglevel%.
$megsdowncurrent MB, which is over $percentage% of the $gigs GB monthly download allowance.
System Traffic Monitor"
:log info "Sent Warning Level $warninglevel% to $email"
}
#Set new warning level on queue comment
/queue simple set $i comment="$sitename!$gigs#$email!$newwarning#$bytestotal"
/queue simple reset-counters $i
}
}

Script: monthlyreport
Called by the overseer at the end of the month, this generates reports for Every site and then resets counters and the warning level back to 00

:local content
:local i
:local sitename
:local gigs
:local email
:local megstotal
:local totalcurrent
:local bytesdowncurrent
:local bytesupcurrent
:local megsdowncurrent
:local megsupcurrent
:local percentage
:local bytesdownsaved
:local bytesdowntotal

#Script based on Automated billing script at AVA Studio ID
:log info "------ Begining Monthly Reports -------"
#For each queue in the list
:foreach i in=[/queue simple find comment !=""] do={

#Pull comments out of queue and divide up accordingly
:set content [/queue simple get $i comment] 

#Determine variables from comment
#Format is: sitename ! gigsallowed # who is to-email ! last warning levels(0-45-75-90-100)
:if ( [ :find $content "!" ] != "" ) do={
  :local pos1 [:find $content "!"]
  :local pos4 [:len $content]
  :local pos2 ([:find [:pick $content ($pos1+1) $pos4] "#"]+$pos1+1)
  :local pos3 ([:find [:pick $content ($pos2+1) $pos4] "!"]+$pos2)
  :set sitename [:pick $content 0 ($pos1)]
  :set gigs [:pick $content ($pos1+1) $pos2]
  :set email [:pick $content ($pos2+1) ($pos3+1)]
  :set totalcurrent [/queue simple get $i bytes]
  :local pos5 [:find $totalcurrent "/"]
  :local pos6 [:len $totalcurrent]
  :set bytesupcurrent ([:pick $totalcurrent 0 ($pos5)])
  :set bytesdowncurrent ([:pick $totalcurrent ($pos5+1) $pos6])
  :set megsupcurrent ($bytesupcurrent / 1048576)
  :set bytesdownsaved ([:pick $content ($pos3+5) $pos4])
  :set bytesdowntotal ($bytesdowncurrent + $bytesdownsaved)
  :set megsdowncurrent ($bytesdowntotal / 1048576)

#Begin calculating usage percentage
  :set percentage ( ( $bytesdowntotal * 100 ) / ( $gigs * 1073741824 ) )
  :log info "$sitename: $percentage%"
:if ([$email] != "" ) do={
/tool e-mail send to=$email from=noreply@example.com server=1.3.3.7 subject="$sitename: Monthly_Report" body="This message is to inform you of the full monthly usage for $sitename

In this month this site has downloaded $megsdowncurrent MB, which is $percentage% of the $gigs GB monthly download allowance.

This is an Automatically generated Email that's sent out at the end of each month.

System Traffic Monitor,
accounts@contoh.com"
}
#Send email to support/accounts also
  /tool e-mail send to="accounts@contoh.com" from="noreply@contoh.com" server="1.3.3.7" subject="$sitename: Monthly Reports" body="Full monthly usage for $sitename
In this month this site has downloaded $megsdowncurrent MB, which iis $percentage% of the $gigs GB monthly download allowance.

System Traffic Monitor ,
accounts@example.com
Please reports any errors in this message to someone@example.com"
:log info "Send monthly report for $sitename to $email"
#Set warning level on queue comment back to 00 and reset counters
/queue simple set $i comment="$sitename!$gigs#$email!00#0000"
/queue simple reset-counters $i
}
}
Script: manualusagereport
This script can be run manually at any time to send through the current usage report.

:local content
:local i
:local sitename
:local gigs
:local email
:local megstotal
:local totalcurrent
:local bytesdowncurrent
:local bytesupcurrent
:local megsdowncurrent
:local megsupcurrent
:local percentage
:local lastwarning
:local warninglevel
:local warn
:local update
:local newwarning
:local bytesdownsaved
:local bytestotal
:local text
:local combinedtext
:set combinedtext ""

#Scripts based on Automated billing script at AVA Studio ID
:log info "------ Begining Manual Usage Reports -------"

#For each queue in the list
:foreach i in=[/queue simple find comment !=""] do={

#Pull comments out of queue and divide up accordingly
:set content [/queue simple get $i comment] 

#Determine variables from comment
#Format is: sitename ! gigsallowed # who isto-email ! last warning levels(0-50-75-90-99) # data-used (0000)
:if ([:find $content "!"] != "") do={
   :local pos1 [:find $content "!"]
   :local pos4 [:len $content]
   :local pos2 ([:find [:pick $content ($pos1+1) $pos4] "#"]+$pos1+1)
   :local pos3 ([:find [:pick $content ($pos2+1) $pos4] "!"]+$pos2)
   :set sitename [:pick $content 0 ($pos1)]
   :set gigs [:pick $content ($pos1+1) $pos2]
   :set email [:pick $content ($pos2+1) ($pos3+1)]
   :set totalcurrent [/queue simple get $i bytes]
   :set lastwarning [:pick $content ($pos3+2) ($pos3+4)]
   :local pos5 [:find $totalcurrent "/"]
   :local pos6 [:len $totalcurrent]
   :set bytesupcurrent ([:pick $totalcurrent 0 ($pos5)])
   :set bytesdowncurrent ([:pick $totalcurrent ($pos5+1) $pos6])
   :set megsupcurrent ($bytesupcurrent / 1048576)
   :set bytesdownsaved ([:pick $content ($pos3+5) $pos4])
   :set bytestotal ($bytesdowncurrent + $bytesdownsaved)
   :set megsdowncurrent ($bytestotal / 1048576)

#Begin calculating usage percentage
  :set percentage ( ( $bytestotal * 100) / ($gigs * 1073741824 ) )
  :log info "$sitename: $percentage% - $megsdowncurrent MB used - Allowance is $gigs GB"
  :set text "$combinedtext  $sitename: $percentage% - $megsdowncurrent MB used - Allowance is $gigs GB"
  :set combinedtext "$text"
 }
}
:log info "------ Ending Manual Usage Reports -------"
:local time [/system clock get time]
/tool e-mail send server="1.3.3.7" from="noreply@example.com" to="accounts@example.com" subject="Manual usage report" body="Site Usage report - Runtime: $time
$text

Regards,
someone@example.com"
Final Notes
For those new to scripts, you can copy and paste these into winbox, but make sure that you at least remove the starting spacing from the comment lines (ones with #) if you don't they aren't treated as comments and will cause the script to error.

Quick trick to generated queues

#change the target address range to match what you want to generate.
:local x
:for x from 2 to 254 do={/queue simple add target-address="10.2.100.$x" queue="default/default"}
would generate queues for 10.0.0.2-10.0.0.254 for you.

note: the queue=default is important, as of v3.12 default-small queues with no child queues will be treated as if there was no queue at all (aka: unmonitored)
Thanks

No comments:

Post a Comment

Selamat Datang

X
X