100% found this document useful (1 vote)
614 views

Manual - Scripting Examples MikroTik

Manual de Scripts Sistema RouterOS Mikrotik
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
100% found this document useful (1 vote)
614 views

Manual - Scripting Examples MikroTik

Manual de Scripts Sistema RouterOS Mikrotik
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 10
Manual:Scripting-examples From MikroTik Wiki Contents = 1 CMD Scripting examples = 1.1 Create a file 1.2 Check if IP on interface have changed 1.3 Strip netmask 1.4 Resolve host-name 1.5 Write simple queue stats in multiple files 1,6 Generate backup and send it by e-mail 1.7 Use string as function 1.8 Check bandwidth and add limitations 1.9 Block access to specific websites 1.10 Parse file to add ppp secrets 1.11 Detect new log entry 1.12 Allow use of ntp.org pool service for NTP 1.13 Auto upgrade script 1.14 Other scripts known to work with latest v3.x = 2. LUA Scripting examples = 2.1 Print function = 2.2 Read and write large files = 2.3 Include custom function in another script = 2.4 See also CMD Scripting examples Create a file In v3.x it is not possible to create file directly, however there is a workaround file print file-nyFile file set ayFile.txt contents= Cheek if IP on interface have changed Sometimes provider gives dynamic IP addresses. This script will compare if dynamic IP address is changed. global currentIP; slocal newiP [/ip address get [Find interface="ether1"] address]; HAF (SnewIP I= $currentIP) do={ jt “ip address ScurrentIP changed to $newIP"; st currentIP $newrP; Strip netmask This script is useful if you need ip address without netmask (for example to use it in firewall), but "/ip address get [id] address" returns ip address and netmask Code: jlobal ipaddress 19.1.101.1/24 ‘for 4 from=( [:len $ipaddress] - 1) if ( [:pick Sipaddress $1] put [:pick $ipaddress @ $1] > Another much more simple way: global ipaddress 10,1,101.1/24 put [:pick $ipaddress © [:Find Sipaddress “/*]] Resolve host-name Many users are asking feature to use dns names instead of IP address for radius servers, firewall rules, etc. So here is an example how to resolve RADIUS server's IP. Lets say we have radius server configured radius add address=3.4.5.6 conment-eyRad And here is a script that will resolve ip address, compare resolved ip with configured one and replace if not equal: esolver" sources ( system script add nam ‘local resolvedIP [:resolve “server.exanple.con"]; local radiusiD [/radius find conment="nyRad"]; local currentIP [/radius get $raciusi0 address]; Lif (SresolvedIP I= $curnentIP) do={ {radius set $radiustD address-$resolvecrP; ‘Nog info "radius ip updated"; D D Adi this script to scheduler to run for example every § minutes system scheduler add nane-resolveRadiusIP on-event="resolver” interval=Sm Write simple queue stats in multiple files Lets consider queue namings are "some text.1" so we can search queues by last number right after the dot. Jocal entriesPerFile 10; Jocal currentQueve @3 Jocal quevesinFile @; local Filecontent * Haetermine needed File count ‘local nungueues [/queue simple print count-only] ; ocal Filecount (SnunQueves / SentriesPerFile) ; HAF ( (S#ileCount * SentriesPerFile) I= Srumueues) do-{ rset FileCount ($Filecount + 1); D lirerove old files file renove [Find name~"stats"]; sput “fileCount$¢ilecount"; for & froma t create file [file print files"stats$i-txt"; ftelear conten [file set (Find nam falecount do={ tats$i.txt”] contentse""; while ($queuesinFile < $entriesPerFile) 4: if (SeurrentQueue < $nunQueves) do={ rset currentQueve (ScurrentQueue +1); put $currentqueue ; Jqueue sinple jocal_internalID [Find nase ut "internalTD=$internal 0" ; jet filecontent (ffileContent . [get $internalTD target-address] . \ "©. [get $internalID total-bytes] . "\r\n' \\.Scurrentqueue\$"]; y set quevesinFile ($queuestnFile +1); y Pile set "statssi.tx rset filecontent “5 contents-$filecontent; Generate backup and send it by e-mail This script generates backup file and sends it to specified e-mail address. Mail subject contains router's name, current date and time. Note that smtp server must be configured before this script can be used. See /tool e-mail for configuration options, Script: system backup save nane-enaii_backup (/tool e-mail send file=enail_backup.backup to="neftest.con” body="See attached file” \ subject="${/systen identity get nare] $[/system clock get tine] $[/systen clock get date] Backup") Note: backup file contains sensitive information like passwords. So to get access to generated backup file, script or scheduler must have ‘sensitive! policy, Use string as function Code: global printA [:parse ":local A; :put \S4;" 15 Sprinta Check bandwidth and add limitations This script checks if download on interface is more than 512kbps, if true then queue is added to limit speed to 256kbps. Code: ‘foreach i ins[/interface find] do-( Vinterface monitor-traffic $1 once do={ Af (Sreceived-bits-per-second” > @ ) dos{ cal tmpIP [/ip address got [/ip address find interface-$i] address] ; ” log warning $tepIP ; Hfor J from=( [:len $tmpIP] - 1) tome dom( Lf ([:pick StmpIP $3] = "/7) doo /queve simple add nane=$i max-Linit=256000/256000 dst-address=[:pick StmpIP @ $4] 5 Block access to specific websites This script is useful if you want to block certain web sites but you don't want to use web proxy. This example looks entries "rapidshare" and "youtube" in dns cache and adds IPs to address list named "restricted", Before you begin, you must set up router to catch all dns requests: Jip Firewall nat ladd actionsredirect chain-dstnat conment-0Ns dst-port-53 protocol=tep to-ports=53, fadd actionsredirect chain-dstnat dst-port=53 protocol and add firewall ip Firewall #11ter {add chain=forward dst-address-list=restricted action=drop ‘Now we can write a script and schedule it to run, lets say, every 30 seconds. Script Code: foreach i ine[/ip das cache Find) dot local bNew “true”; local cacheNane (/ip dns cache all get $i name] ; # —:put $cacheNanes if (([:find $cacheNane “rapidshare”] != 0) || ([:Find $cacheNane “youtube™] != @)) do={ ‘local tmpAddress [/ip dns cache get $i address] ; * put Stmpaddress; |b SF address List is empty do not check Af ( [/ip firewall] address-List find ) do: Flog info ("added entry: $[/ip éns cache get $i nane] IP $tnpAdcress"); /ip Firewall address-list add address=Stepaddress list=restricted conment=$cacheNane; ip firewall address-List Find ] do={ Af ( [/ip firewall address-List get $) address] = $tapaddress ) d rset buew "False" > HF ( $bNew = “true” ) do={ ‘log info ("added entry: $[/ip dns cache get $1 nane] IP StmpAddress"); Jip firewall address-List add addresssStmptddress Listerestricted comnentsScacheNane; Parse file to add ppp secrets This script requires that entries inside the file is in following form: username,password,local_address,remote_address,profile,service For example: Janis, 123,1.1.1.1,2.2.2.1, ppp_profile,myService Suris, 456, 1.1.1.1,2.2.2.2,ppp_profilesmyService ‘aija,678,1.1.1.1,2.2.2.3,ppp_profile,ryService Code: global content [/File get [/File find nane=test.txt] contents] 5 global contentlen [ :len $content ] 3 global LineEnd global Line"; global lastend 0; do { ind $content “\r\n" $lasténd ] 5 ‘sot Line [:pick $content $lasténd $Lineénd] ; set lasténd ( $1ineEnd +2) 5 local tmparray [:toarray $line] ; Af ( [:pick Stmparray 8) I=" ) dont put Stmparray; Jppp secret add nanes[:pick $tmpArray 0] password=[:pick Stmparray 1] \ local-address=[=pick $tmpArray 2] renote-address=[:pick $tmpirray 3] \ profiles(:pick $tmpAray 4] service=[:pick Stnparray 5); » } while ($1ineEné < $contentLen) Detect new log entry This script is checking if new log entry is added to particular buffer. In this example we will use pppoe logs: system logging action add nane="pppoe system 1o fadd action=pppee topics=pppee, info, !ppp, !debug Log buffer will look similar to this one: [adningnainGw] > /og print where bufFer=pppoe 13:11:08 pppoe, info PP20e connection established from @0:0C:42:04:4C:EE Now we can write a script to detect if new entry is added. Code: global lastTime; global currentauf [ stoarray [ /log find buffer-pppoe ] ] 5 global currentLineCount [ :len ScurrentBuf ] 5 global currentTine [ :totine [/log get [ :pick Scurre Buf (ScurrentLinecount -1) ] tire] J; global nessage *; Af ( $lastTine = ° ) do! set lastTize $currentTime 5 set message (/log get [ :pick ScurrentBuf ($currentLineCount-1) } message]; } else=( Af ( $lastTine < $currentTine ) co=( set lastTine $currentTine 3 set message [/log get [ :pick $currentBuf ($currentLinecount-1) } message]; After new entry is detected, itis saved in "message" variable, which you can use later to parse log message, for example, to get pppoe clients mac address Allow use of ntp.org pool service for NTP This script resolves the hostnames of two NTP servers, compares the result with the current NTP settings and changes the addresses if they're different. This script is required as RouterOS does not allow hostnames to be used in the NTP configuration, Two scripts are used. The first defines some system variables which are used in other scripts and the second does the grunt work: # system configuration script - "GlobalVars' sput “Setting systes globals"s 1 system nare global SVSnane [/system identity get name]; |» E-mail address to send notifications to ‘global sySsendenail "nai lay. address 4 E-mail address to send notifications fron global SVSeyemail “[email protected]"; 4s Mail server to use global SYSenailserver "1.2. NTP pools to use (check waw.pool.ntp.org) global SYSntpa “®.uk.p001.ntp.org"; JlobalSvSntpb "1.uk.p0o1.ntp.org” Check and set NIP servers - "setntppool |# We need to use the following globals which eust be defined here even 4s though they are also defined in the script we call to set then svSnane; SvSsendenail; svSeyemail; sYSeynane S¥Senailservers svsntpa svSntpb; 4 Load the global variables with the system defaults system script run Globalvars | Resolve the two ntp pool hostnanes local ntpipa [:resolve $5¥Sntpa]; local ntpipb [:resolve $5¥Sntpb]; 4 Get the current settings local ntpcura [/system ntp client get prinary-ntp]; local ntpcurb [/system ntp client get secondary-ntp] # Define a variable so we know if anything's changed ‘local changea 0; “local changeb 0; # debug output ut ("01 “put ("old: $ntpeura . 7 New: Srtpeurd | * New: + $otpipa)s + $ntpipb); 8 Change primary 1f required Af (Sntpipa I= $ntpcura) dot Eput “Changing primary NTP*; Jsysten ntp client set prinary-ntp set changea 1; y *sntpip: 8 Change secondary if required Af (Sntpipb I= $ntpcurb) don{ put “Changing secondary NTP"; /systes ntp client set secondary-ntp="$ntpipb"; set changeb 1; » # If we've made a change, send an e-nail to say so, Af ((Sehangea = 1) [| (Schanged = 1)) do={ put “Sending e-nail."; Fool e-mail send \ to=$svSsendenail \ NTP change") \ "Your NIP servers have just b = $ntpipa . "\n\nSecondary\nolé: * . $ntpcurd . "\nNew: $acpipb); Scheduler entry: system schedules add \ conments"Check and set NTP servers™ \, disabled=no \ interval=12h \ hame=CheckNTPServers \ \nold: " . $ntpcura . "\aNew: on-event=setntppool \ policy-read,write,test \ Auto upgrade script = Auto_upgrade_seript_V3.x Other scripts known to work with latest v3.x. = Dynamic DNS_Update_Script_for EveryDNS = Dynamic DNS Update Script_for_ChangelP.com = UPS Script LUA Scripting examples NOTE! After RouterOS v4.0betad, Lua support is removed until further notice In v4.0beta3 Lua scripting language is integrated in console. This integration allows users to create their own functions and bypass several command line scripting limitations. All examples below require at least basic knowledge of Lua scripting language. Good tutorials ean be found here (http://lua-users.org/wiki/TutorialDirectory) as a starting point, Print function As stated in Lua documentation, ‘print’ command is not available in RouterOS compared to standard Lua release. This example will show you how to get back ‘print’ command Function pri local strerintResult Af... then local tangs = (2.3 for i,v in ipairs(targs) do strPnintResult = strPrintResult .. tostring(y) .. "7 end StrPrintResult = strPrintResult .. *\r\n" io.write(strPrintResult) end lend Now you can include this custom function to other scripts and use this cool custom print funetion :) You can also modify this function to write messages in RouterOS log. Read and write large files Many users requested ability to work with files. Now you can do it without limitations. Create and write to file: global newcontent “new ile content\r\nanother Line\r\n"; [/lua "Local feassert(io.open(*/test.txt', ‘we')); fiwrite(newContent); ficlose()" 1; Read file content to variable global ent [/lua "local feassert(io.open(*/test.txt', ‘r')); ent=frread(**all'); F:close()" 15 put Sent Include custom function in another script This example will show where to store and how to include your cool custom created functions into another scripts In router's file root directory create subdirectory named ‘lua’ On your PC create new file named customprint.lua and write this funetion in it. Upload newly created file in router's ‘lua’ directory that we made in first step Now you can test your custom lua function [s1ua "require ‘custonprint"\n print(‘hello from custom print function’)"] See also = Theory of Scripting = User submitted Scripts [ Top | Back to Content | Retrieved from "http://wiki.mikrotik.com/index.php’title-Manual:Scripting-examplesSoldid=25690" Categories: Manual | System | Console | Examples = This page was last modified on 22 August 2013, at 13:42. = This page has been accessed 308,036 times.

You might also like