Professional Documents
Culture Documents
Manual:Scriptingexamples
FromMikroTikWiki
Contents
1CMDScriptingexamples
1.1Createafile
1.2CheckifIPoninterfacehavechanged
1.3Stripnetmask
1.4Resolvehostname
1.5Writesimplequeuestatsinmultiplefiles
1.6Generatebackupandsenditbyemail
1.7Usestringasfunction
1.8Checkbandwidthandaddlimitations
1.9Blockaccesstospecificwebsites
1.10Parsefiletoaddpppsecrets
1.11Detectnewlogentry
1.12Allowuseofntp.orgpoolserviceforNTP
1.13Autoupgradescript
1.14Otherscriptsknowntoworkwithlatestv3.x
2LUAScriptingexamples
2.1Printfunction
2.2Readandwritelargefiles
2.3Includecustomfunctioninanotherscript
2.4Seealso
CMDScriptingexamples
Thissectioncontainssomeusefulscriptsandshowsallavailablescriptingfeatures.Scriptexamplesusedinthis
sectionweretestedwiththelatest3.xversion.
Createafile
Inv3.xitisnotpossibletocreatefiledirectly,howeverthereisaworkaround
/fileprintfile=myFile
/filesetmyFile.txtcontents=""
CheckifIPoninterfacehavechanged
SometimesprovidergivesdynamicIPaddresses.ThisscriptwillcompareifdynamicIPaddressischanged.
http://wiki.mikrotik.com/wiki/Manual:Scriptingexamples#Block_access_to_specific_websites 1/10
1/30/2017 Manual:ScriptingexamplesMikroTikWiki
:globalcurrentIP;
:localnewIP[/ipaddressget[findinterface="ether1"]address];
:if($newIP!=$currentIP)do={
:put"ipaddress$currentIPchangedto$newIP";
:setcurrentIP$newIP;
}
Stripnetmask
Thisscriptisusefulifyouneedipaddresswithoutnetmask(forexampletouseitinfirewall),but"/ipaddress
get[id]address"returnsipaddressandnetmask.
Code:
:globalipaddress10.1.101.1/24
:forifrom=([:len$ipaddress]1)to=0do={
:if([:pick$ipaddress$i]="/")do={
:put[:pick$ipaddress0$i]
}
}
Anothermuchmoresimpleway:
:globalipaddress10.1.101.1/24
:put[:pick$ipaddress0[:find$ipaddress"/"]]
Resolvehostname
ManyusersareaskingfeaturetousednsnamesinsteadofIPaddressforradiusservers,firewallrules,etc.
SohereisanexamplehowtoresolveRADIUSserver'sIP.
Letssaywehaveradiusserverconfigured:
/radius
addaddress=3.4.5.6comment=myRad
Andhereisascriptthatwillresolveipaddress,compareresolvedipwithconfiguredoneandreplaceifnotequal:
/systemscriptaddname="resolver"source={
:localresolvedIP[:resolve"server.example.com"];
:localradiusID[/radiusfindcomment="myRad"];
:localcurrentIP[/radiusget$radiusIDaddress];
:if($resolvedIP!=$currentIP)do={
/radiusset$radiusIDaddress=$resolvedIP;
http://wiki.mikrotik.com/wiki/Manual:Scriptingexamples#Block_access_to_specific_websites 2/10
1/30/2017 Manual:ScriptingexamplesMikroTikWiki
/loginfo"radiusipupdated";
}
Addthisscripttoschedulertorunforexampleevery5minutes
/systemscheduleraddname=resolveRadiusIPonevent="resolver"interval=5m
Writesimplequeuestatsinmultiplefiles
Letsconsiderqueuenamingsare"sometext.1"sowecansearchqueuesbylastnumberrightafterthedot.
:localentriesPerFile10;
:localcurrentQueue0;
:localqueuesInFile0;
:localfileContent"";
#determineneededfilecount
:localnumQueues[/queuesimpleprintcountonly];
:localfileCount($numQueues/$entriesPerFile);
:if(($fileCount*$entriesPerFile)!=$numQueues)do={
:setfileCount($fileCount+1);
}
#removeoldfiles
/fileremove[findname~"stats"];
:put"fileCount=$fileCount";
:forifrom=1to=$fileCountdo={
#createfile
/fileprintfile="stats$i.txt";
#clearcontent
/fileset[findname="stats$i.txt"]contents="";
:while($queuesInFile<$entriesPerFile)do={
:if($currentQueue<$numQueues)do={
:setcurrentQueue($currentQueue+1);
:put$currentQueue;
/queuesimple
:localinternalID[findname~"\\.$currentQueue\$"];
:put"internalID=$internalID";
:setfileContent($fileContent.[get$internalIDtargetaddress].\
"".[get$internalIDtotalbytes]."\r\n");
}
:setqueuesInFile($queuesInFile+1);
}
/fileset"stats$i.txt"contents=$fileContent;
:setfileContent"";
:setqueuesInFile0;
Generatebackupandsenditbyemail
Thisscriptgeneratesbackupfileandsendsittospecifiedemailaddress.Mailsubjectcontainsrouter'sname,
currentdateandtime.
http://wiki.mikrotik.com/wiki/Manual:Scriptingexamples#Block_access_to_specific_websites 3/10
1/30/2017 Manual:ScriptingexamplesMikroTikWiki
Notethatsmtpservermustbeconfiguredbeforethisscriptcanbeused.See/toolemailforconfiguration
options.
Script:
/systembackupsavename=email_backup
/toolemailsendfile=email_backup.backupto="me@test.com"body="Seeattachedfile"\
subject="$[/systemidentitygetname]$[/systemclockgettime]$[/systemclockgetdate]Backup")
Note:backupfilecontainssensitiveinformationlikepasswords.Sotogetaccesstogeneratedbackupfile,script
orschedulermusthave'sensitive'policy.
Usestringasfunction
Code:
:globalprintA[:parse":localA;:put\$A;"];
$printA
Checkbandwidthandaddlimitations
Thisscriptchecksifdownloadoninterfaceismorethan512kbps,iftruethenqueueisaddedtolimitspeedto
256kbps.
Code:
:foreachiin=[/interfacefind]do={
/interfacemonitortraffic$ioncedo={
:if($"receivedbitspersecond">0)do={
:localtmpIP[/ipaddressget[/ipaddressfindinterface=$i]address];
#:logwarning$tmpIP;
:forjfrom=([:len$tmpIP]1)to=0do={
:if([:pick$tmpIP$j]="/")do={
/queuesimpleaddname=$imaxlimit=256000/256000dstaddress=[:pick$tmpIP0$j];
}
}
}
}
}
Blockaccesstospecificwebsites
Thisscriptisusefulifyouwanttoblockcertainwebsitesbutyoudon'twanttousewebproxy.
http://wiki.mikrotik.com/wiki/Manual:Scriptingexamples#Block_access_to_specific_websites 4/10
1/30/2017 Manual:ScriptingexamplesMikroTikWiki
Thisexamplelooksentries"rapidshare"and"youtube"indnscacheandaddsIPstoaddresslistnamed"restricted".
Beforeyoubegin,youmustsetuproutertocatchalldnsrequests:
/ipfirewallnat
addaction=redirectchain=dstnatcomment=DNSdstport=53protocol=tcptoports=53
addaction=redirectchain=dstnatdstport=53protocol=udptoports=53
andaddfirewall
/ipfirewallfilter
addchain=forwarddstaddresslist=restrictedaction=drop
Nowwecanwriteascriptandscheduleittorun,letssay,every30seconds.
ScriptCode:
:foreachiin=[/ipdnscachefind]do={
:localbNew"true";
:localcacheName[/ipdnscacheallget$iname];
#:put$cacheName;
:if(([:find$cacheName"rapidshare"]!=0)||([:find$cacheName"youtube"]!=0))do={
:localtmpAddress[/ipdnscacheget$iaddress];
# :put$tmpAddress;
#ifaddresslistisemptydonotcheck
:if([/ipfirewalladdresslistfindlist="restricted"]="")do={
:loginfo("addedentry:$[/ipdnscacheget$iname]IP$tmpAddress");
/ipfirewalladdresslistaddaddress=$tmpAddresslist=restrictedcomment=$cacheName;
}else={
:foreachjin=[/ipfirewalladdresslistfindlist="restricted"]do={
:if([/ipfirewalladdresslistget$jaddress]=$tmpAddress)do={
:setbNew"false";
}
}
:if($bNew="true")do={
:loginfo("addedentry:$[/ipdnscacheget$iname]IP$tmpAddress");
/ipfirewalladdresslistaddaddress=$tmpAddresslist=restrictedcomment=$cacheName;
}
}
}
}
Parsefiletoaddpppsecrets
Thisscriptrequiresthatentriesinsidethefileisinfollowingformat:
username,password,local_address,remote_address,profile,service
Forexample:
janis,123,1.1.1.1,2.2.2.1,ppp_profile,myService
juris,456,1.1.1.1,2.2.2.2,ppp_profile,myService
aija,678,1.1.1.1,2.2.2.3,ppp_profile,myService
Code:
http://wiki.mikrotik.com/wiki/Manual:Scriptingexamples#Block_access_to_specific_websites 5/10
1/30/2017 Manual:ScriptingexamplesMikroTikWiki
:globalcontent[/fileget[/filefindname=test.txt]contents];
:globalcontentLen[:len$content];
:globallineEnd0;
:globalline"";
:globallastEnd0;
:do{
:setlineEnd[:find$content"\r\n"$lastEnd];
:setline[:pick$content$lastEnd$lineEnd];
:setlastEnd($lineEnd+2);
:localtmpArray[:toarray$line];
:if([:pick$tmpArray0]!="")do={
:put$tmpArray;
/pppsecretaddname=[:pick$tmpArray0]password=[:pick$tmpArray1]\
localaddress=[:pick$tmpArray2]remoteaddress=[:pick$tmpArray3]\
profile=[:pick$tmpArray4]service=[:pick$tmpArray5];
}
}while($lineEnd<$contentLen)
Detectnewlogentry
Thisscriptischeckingifnewlogentryisaddedtoparticularbuffer.
Inthisexamplewewillusepppoelogs:
/systemloggingaction
addname="pppoe"
/systemlogging
addaction=pppoetopics=pppoe,info,!ppp,!debug
Logbufferwilllooksimilartothisone:
[admin@mainGW]>/logprintwherebuffer=pppoe
13:11:08pppoe,infoPPPoEconnectionestablishedfrom00:0C:42:04:4C:EE
Nowwecanwriteascripttodetectifnewentryisadded.
Code:
:globallastTime;
:globalcurrentBuf[:toarray[/logfindbuffer=pppoe]];
:globalcurrentLineCount[:len$currentBuf];
:globalcurrentTime[:totime[/logget[:pick$currentBuf($currentLineCount1)]time]];
:globalmessage"";
:if($lastTime="")do={
:setlastTime$currentTime;
:setmessage[/logget[:pick$currentBuf($currentLineCount1)]message];
}else={
:if($lastTime<$currentTime)do={
:setlastTime$currentTime;
:setmessage[/logget[:pick$currentBuf($currentLineCount1)]message];
http://wiki.mikrotik.com/wiki/Manual:Scriptingexamples#Block_access_to_specific_websites 6/10
1/30/2017 Manual:ScriptingexamplesMikroTikWiki
}
}
Afternewentryisdetected,itissavedin"message"variable,whichyoucanuselatertoparselogmessage,for
example,togetpppoeclientsmacaddress.
Allowuseofntp.orgpoolserviceforNTP
ThisscriptresolvesthehostnamesoftwoNTPservers,comparestheresultwiththecurrentNTPsettingsand
changestheaddressesifthey'redifferent.ThisscriptisrequiredasRouterOSdoesnotallowhostnamestobeused
intheNTPconfiguration.Twoscriptsareused.Thefirstdefinessomesystemvariableswhichareusedinother
scriptsandtheseconddoesthegruntwork:
#Systemconfigurationscript"GlobalVars"
:put"Settingsystemglobals";
#Systemname
:globalSYSname[/systemidentitygetname];
#Emailaddresstosendnotificationsto
:globalSYSsendemail"mail@my.address";
#Emailaddresstosendnotificationsfrom
:globalSYSmyemail"routeros@my.address";
#Mailservertouse
:globalSYSemailserver"1.2.3.4";
#NTPpoolstouse(checkwww.pool.ntp.org)
:globalSYSntpa"0.uk.pool.ntp.org";
:globalSYSntpb"1.uk.pool.ntp.org";
#CheckandsetNTPservers"setntppool"
#Weneedtousethefollowingglobalswhichmustbedefinedhereeven
#thoughtheyarealsodefinedinthescriptwecalltosetthem.
:globalSYSname;
:globalSYSsendemail;
:globalSYSmyemail;
:globalSYSmyname;
:globalSYSemailserver;
:globalSYSntpa;
:globalSYSntpb;
#Loadtheglobalvariableswiththesystemdefaults
/systemscriptrunGlobalVars
#Resolvethetwontppoolhostnames
:localntpipa[:resolve$SYSntpa];
:localntpipb[:resolve$SYSntpb];
#Getthecurrentsettings
:localntpcura[/systemntpclientgetprimaryntp];
:localntpcurb[/systemntpclientgetsecondaryntp];
#Defineavariablesoweknowifanything'schanged.
:localchangea0;
:localchangeb0;
#Debugoutput
:put("Old:".$ntpcura."New:".$ntpipa);
:put("Old:".$ntpcurb."New:".$ntpipb);
http://wiki.mikrotik.com/wiki/Manual:Scriptingexamples#Block_access_to_specific_websites 7/10
1/30/2017 Manual:ScriptingexamplesMikroTikWiki
#Changeprimaryifrequired
:if($ntpipa!=$ntpcura)do={
:put"ChangingprimaryNTP";
/systemntpclientsetprimaryntp="$ntpipa";
:setchangea1;
}
#Changesecondaryifrequired
:if($ntpipb!=$ntpcurb)do={
:put"ChangingsecondaryNTP";
/systemntpclientsetsecondaryntp="$ntpipb";
:setchangeb1;
}
#Ifwe'vemadeachange,sendanemailtosayso.
:if(($changea=1)||($changeb=1))do={
:put"Sendingemail.";
/toolemailsend\
to=$SYSsendemail\
subject=($SYSname."NTPchange")\
from=$SYSmyemail\
server=$SYSemailserver\
body=("YourNTPservershavejustbeenchanged:\n\nPrimary:\nOld:".$ntpcura."\nNew:"\
.$ntpipa."\n\nSecondary\nOld:".$ntpcurb."\nNew:".$ntpipb);
}
Schedulerentry:
/systemscheduleradd\
comment="CheckandsetNTPservers"\
disabled=no\
interval=12h\
name=CheckNTPServers\
onevent=setntppool\
policy=read,write,test\
startdate=jan/01/1970\
starttime=16:00:00
Autoupgradescript
Auto_upgrade_script_V3.x
Otherscriptsknowntoworkwithlatestv3.x
Dynamic_DNS_Update_Script_for_EveryDNS
Dynamic_DNS_Update_Script_for_ChangeIP.com
UPSScript
LUAScriptingexamples
NOTE!
AfterRouterOSv4.0beta4,Luasupportisremoveduntilfurthernotice
Inv4.0beta3Luascriptinglanguageisintegratedinconsole.Thisintegrationallowsuserstocreatetheirown
functionsandbypassseveralcommandlinescriptinglimitations.
AllexamplesbelowrequireatleastbasicknowledgeofLuascriptinglanguage.Goodtutorialscanbefoundhere
(http://luausers.org/wiki/TutorialDirectory)asastartingpoint.
http://wiki.mikrotik.com/wiki/Manual:Scriptingexamples#Block_access_to_specific_websites 8/10
1/30/2017 Manual:ScriptingexamplesMikroTikWiki
Printfunction
AsstatedinLuadocumentation,'print'commandisnotavailableinRouterOScomparedtostandardLuarelease.
Thisexamplewillshowyouhowtogetback'print'command
Printfunction
functionprint(...)
localstrPrintResult=""
if...then
localtargs={...}
fori,vinipairs(targs)do
strPrintResult=strPrintResult..tostring(v)..""
end
strPrintResult=strPrintResult.."\r\n"
io.write(strPrintResult)
end
end
Nowyoucanincludethiscustomfunctiontootherscriptsandusethiscoolcustomprintfunction:)
YoucanalsomodifythisfunctiontowritemessagesinRouterOSlog.
Readandwritelargefiles
Manyusersrequestedabilitytoworkwithfiles.Nowyoucandoitwithoutlimitations.
Createandwritetofile:
:globalnewContent"newfilecontent\r\nanotherline\r\n";
[/lua"localf=assert(io.open('/test.txt','w+'));f:write(newContent);f:close()"];
Readfilecontenttovariable:
:globalcnt""
[/lua"localf=assert(io.open('/test.txt','r'));cnt=f:read('*all');f:close()"];
:put$cnt
Includecustomfunctioninanotherscript
Thisexamplewillshowwheretostoreandhowtoincludeyourcoolcustomcreatedfunctionsintoanotherscripts
Inrouter'sfilerootdirectorycreatesubdirectorynamed'lua'
OnyourPCcreatenewfilenamedcustomprint.luaandwritethisfunctioninit.
Uploadnewlycreatedfileinrouter's'lua'directorythatwemadeinfirststep
Nowyoucantestyourcustomluafunction
[:lua"require'customprint'\nprint('hellofromcustomprintfunction')"]
Seealso
http://wiki.mikrotik.com/wiki/Manual:Scriptingexamples#Block_access_to_specific_websites 9/10
1/30/2017 Manual:ScriptingexamplesMikroTikWiki
TheoryofScripting
UsersubmittedScripts
[Top|BacktoContent]
Retrievedfrom"http://wiki.mikrotik.com/index.php?title=Manual:Scriptingexamples&oldid=28114"
Thispagewaslastmodifiedon2February2016,at14:48.
Thispagehasbeenaccessed460,986times.
http://wiki.mikrotik.com/wiki/Manual:Scriptingexamples#Block_access_to_specific_websites 10/10