Вы находитесь на странице: 1из 11

29/02/12 Manual:Scripting - MikroTik Wiki

1/11 iki.mikrotik.com/iki/Manual:Scripting#Global_commands
AppIies to
RouterOS:v3,
v4
Manual:Scripting
Contents
1Scriptinglanguagemanual
1.1Linestructure
1.1.1Commandline
1.1.2PhysicalLine
1.1.3Comments
1.1.3.1Example
1.1.4Linejoining
1.1.4.1Example
1.1.5Whitespacebetweentokens
1.1.6Scopes
1.1.6.1Globalscope
1.1.6.2Localscope
1.2Keywords
1.3Delimiters
1.4Datatypes
1.4.1ConstantEscapeSequences
1.4.1.1Example
1.5Operators
1.5.1ArithmeticOperators
1.5.2RelationalOperators
1.5.3LogicalOperators
1.5.4BitwiseOperators
1.5.5ConcatenationOperators
1.5.6OtherOperators
1.6Variables
1.7Commands
1.7.1Globalcommands
1.7.2Menuspecificcommands
1.7.2.1Commoncommands
1.7.2.2import
1.7.2.3printparameters
1.8Loopsandconditionalstatements
1.8.1Loops
1.8.2Conditionalstatement
2Scriptrepository
2.1Environment
2.2Job
3Seealso
Scriptinglanguagemanual
ThismanualprovidesintroductiontoRouterOSbuiltinpowerfulscriptinglanguage.
Scriptinghostprovidesawaytoautomatesomeroutermaintenancetasksbymeansofexecutinguserdefinedscriptsboundedtosomeevent
occurrence.
ScriptscanbestoredinScriptrepositoryorcanbewrittendirectlytoconsole.Theeventsusedtotriggerscriptexecutioninclude,butarenot
limitedtotheSystemScheduler,theTrafficMonitoringTool,andtheNetwatchToolgeneratedevents.
Line structure
RouterOSscriptisdividedintonumberofcommandlines.Commandlinesareexecutedonebyoneuntiltheendofscriptoruntilruntimeerror
occur.
Command Iine
29/02/12 Manual:Scripting - MikroTik Wiki
2/11 iki.mikrotik.com/iki/Manual:Scripting#Global_commands
RouterOSconsoleusesfollowingcommandsyntax:
[prefix][path]command[uparam][param=[value]]..[param=[value]]
[prefix]":"or"/"characterwhichindicatesifcommandisICEorpath.Mayormaynotberequired.
[path]relativepathtothedesiredmenulevel.Mayormaynotberequired.
commandoneofthecommandsavailableatthespecifiedmenulevel.
[uparam]unnamedparameter,mustbespecifiedifcommandrequiresit.
[params]sequenceofnamedparametersfollowedbyrespectivevalues
TheendofcommandlineisrepresentedbythetokenorNEWLINE.SometimesorNEWLINEisnotrequiredtoendthecommandline.
Singlecommandinside(),[]or{}doesnotrequireanyendofcommandcharacter.Endofcommandisdeterminedbycontentofwhole
script
:if(true)do={:put"lala"}
Eachcommandlineinsideanothercommandlinestartsandendswithsquarebrackets"[]"(commandconcatenation).
:put[/iprouteget[findgateway=1.1.1.1]]
Noticethatcodeabovecontainsthreecommandlines:
:put
/iprouteget
findgateway=1.1.1.1
Commandlinecanbeconstructedfrommorethanonephysicallinebyfollowinglinejoiningrules.
PhysicaI Line
Aphysicallineisasequenceofcharactersterminatedbyanendofline(EOL)sequence.Anyofthestandardplatformlinetermination
sequencescanbeused:
unixASCIILF
windowsASCIICRLF
macASCIICR
StandardCconventionsfornewlinecharacterscanbeused(the\ncharacter).
Comments
Acommentstartswithahashcharacter(#)andendsattheendofthephysicalline.Whitespaceoranyothersymbolsarenotallowedbefore
hashsymbol.Commentsareignoredbysyntax.If(#)characterappearinsidestringitisnotconsideredacomment.
ExampIe
#thisisacomment
#badcomment
:globala#badcomment
:globalmyStr"lala#thisisnotacomment"
Line joining
Twoormorephysicallinesmaybejoinedintologicallinesusingbackslashcharacter(\).Alineendinginabackslashcannotcarrya
comment.Abackslashdoesnotcontinueacomment.Abackslashdoesnotcontinueatokenexceptforstringliterals.Abackslashisillegal
elsewhereonalineoutsideastringliteral.
29/02/12 Manual:Scripting - MikroTik Wiki
3/11 iki.mikrotik.com/iki/Manual:Scripting#Global_commands
elsewhereonalineoutsideastringliteral.
ExampIe
:if($a=true\
and$b=false)do={:put$a$b}
:if($a=true\#badcomment
and$b=false)do={:put$a$b}
#comment\
continuedinvalid(syntaxerror)
Whitespace between tokens
Whitespacecanbeusedtoseparatetokens.Whitespaceisnecessarybetweentwotokensonlyiftheirconcatenationcouldbeinterpretedas
adifferenttoken.Example:
{
:localatrue:localbfalse
#whitespaceisnotrequired
:put(a&&b)
#whitespaceisrequired
:put(aandb)
}
Whitespacearenotallowed
between'<parameter>='
between'from=''to=''step=''in=''do=''else='
Example:
#incorrect:
:forifrom=1to=2do={:put$i}
#correctsyntax:
:forifrom=1to=2do={:put$i}
:forifrom=1to=2do={:put$i}
#incorrect
/iprouteaddgateway=3.3.3.3
#correct
/iprouteaddgateway=3.3.3.3
Scopes
Variablescanbeusedonlyincertainregionsofthescript.Theseregionsarecalledscopes.Scopedeterminesvisibilityofthevariable.There
aretwotypesofscopesglobalandlocal.Avariabledeclaredwithinablockisaccessibleonlywithinthatblockandblocksenclosedbyit,
andonlyafterthepointofdeclaration.
GIobaI scope
Globalscopeorrootscopeisdefaultscopeofthescript.Itiscreatedautomaticallyandcannotbeturnedoff.
LocaI scope
Usercandefineitsowngroupstoblockaccesstocertainvariables,thesescopesarecalledlocalscopes.Eachlocalscopeisenclosedin
curlybraces("{}").
{
:locala3
{
:localb4
:put($a+$b)
}
#linebelowwillgenerateerror
:put($a+$b)
}
29/02/12 Manual:Scripting - MikroTik Wiki
4/11 iki.mikrotik.com/iki/Manual:Scripting#Global_commands
}
Incodeabovevariablebhaslocalscopeandwillnotbeaccessibleafterclosedcurlybrace.
Note:Eachlinewritteninterminalistreatedaslocalscope
Soforexample,definedlocalvariablewillnotbevisibleinnextcommandlineandwillgeneratesyntaxerror
[admin@MikroTik]>:localmyVara
[admin@MikroTik]>:put$myVar
syntaxerror(line1column7)
Warning:Do not define gIobaI variabIes inside IocaI scopes.
Notethatevenvariablecanbedefinedasglobal,itwillbeavailableonlyfromitsscopeunlessitisnotalreadydefined.
{
:locala3
{
:globalb4
}
:put($a+$b)
}
Codeabovewillgenerateanerror.
Keywords
Thefollowingwordsarekeywordsandcannotbeusedasvariableandfunctionnames:
andornotin
DeIimiters
Thefollowingtokensserveasdelimitersinthegrammar:
()[]{}:$/
Data types
RouterOSscriptinglanguagehasfollowingdatatypes:
Type Description
number 64bitsignedinteger,possiblehexadecimalinput
boolean valuescanbeetrueorfalse
string charactersequence
IP IPaddress
internalID hexadecimalvalueprefixedby'*'sign.EachmenuitemhasassigneduniquenumberinternalID
time dateandtimevalue
array sequenceofvaluesorganizedinanarray
nil defaultvariabletypeifnovalueisassigned
29/02/12 Manual:Scripting - MikroTik Wiki
5/11 iki.mikrotik.com/iki/Manual:Scripting#Global_commands
nil defaultvariabletypeifnovalueisassigned
Constant Escape Sequences
Followingescapesequencescanbeusedtodefinecertainspecialcharacterwithinstring:
\" Insertdoublequote
\\ Insertbackslash
\n Insertnewline
\r Insertcarriagereturn
\t Inserthorizontaltab
\$ Output$character.Otherwise$isusedtolinkvariable.
\? Output?character.Otherwise?isusedtoprint"help"inconsole.
\_ space
\a BEL(0x07)
\b backspace(0x08)
\f formfeed(0xFF)
\v Insertverticaltab
\xx Printcharacterfromhexvalue.Hexnumbershouldusecapitalletters.
ExampIe
:put"\48\45\4C\4C\4F\r\nThis\r\nis\r\na\r\ntest"
whichwillshowondisplay
HELLO
This
is
a
test
Operators
Arithmetic Operators
UsualarithmeticoperatorsaresupportedinRouterOSscriptinglanguage
Opearator Description ExampIe
"+" binaryaddition :put(3+4)
"" binarysubtraction :put(16)
"*" binarymultiplication :put(4*5)
"/" binarydivision :put(10/2)
"" unarynegation {:locala1:put(a)}
ReIationaI Operators
Opearator Description ExampIe
"<" less :put(3<4)
">" greater :put(3>4)
"=" equal :put(2=2)
"<=" lessorequal
">=" greaterorequal
29/02/12 Manual:Scripting - MikroTik Wiki
6/11 iki.mikrotik.com/iki/Manual:Scripting#Global_commands
">=" greaterorequal
"!=" notequal
LogicaI Operators
Opearator Description ExampIe
!,not logicalNOT :put(!true)
&&,and logicalAND :put(true&&true)
||,or logicalOR :put(true||false)
in :put(1.1.1.1/32in1.0.0.0/8)
Bitwise Operators
Bitwiseoperatorsareworkingonnumberandipaddressdatatypes.
Opearator Description ExampIe
~ bitinversion :put(~0.0.0.0)
| bitwiseOR.PerformslogicalORoperationoneach
pairofcorrespondingbits.Ineachpairtheresultis
1ifoneofbitsorbothbitsare1,otherwisethe
resultis0.
^ bitwiseXOR.ThesameasOR,buttheresultineach
positionis1iftwobitsarenotequal,and0ifbits
areequal.
& bitwiseAND.Ineachpairtheresultis1iffirstand
secondbitis1.Otherwisetheresultis0.
<< leftshiftbygivenamountofbits
>> rightshiftbygivenamountofbits
Concatenation Operators
Opearator Description ExampIe
. concatenatestwostrings :put(concatenate..string)
, concatenatestwoarraysoraddselementtoarray :put({123},5)
Itispossibletoaddvariablevaluestostringswithoutconcatenationoperator:
:globalmyVar"world"
:put("Hello".$myVar)
#nextlinedoesthesameasabove
:put"Hello$myVar"
Byusing$[]and$()instringitispossibletoaddexpressionsinsidestrings:
:locala5
:localb6
:put"5x6=$($a*$b)"
:put"Wehave$[:len[/iproutefind]]routes"
Other Operators
Opearator Description ExampIe
[] commandsubstitution.Cancontainonlysingle
commandline
:put[:len"myteststring"]
() subexpressionorgroupingoperator :put("valueis".(4+5))
29/02/12 Manual:Scripting - MikroTik Wiki
7/11 iki.mikrotik.com/iki/Manual:Scripting#Global_commands
() subexpressionorgroupingoperator :put("valueis".(4+5))
$ substitutionoperator :globala5:put$a
~ binaryoperatorthatmatchesvalueagainstPOSIX
extendedregularexpression
Printallrouteswhichgatewayendswith202
/iprouteprintwheregateway~"^[09\\.]*202"
VariabIes
Scriptinglanguagehastwotypesofvariables:
globalaccessiblefromallcurrentusersscripts,definedbyglobalkeyword
localaccessibleonlywithinthecurrentscope,definedbylocalkeyword.
Everyvariable,exceptforbuiltinRouterOSvariables,mustbedeclaredbeforeusagebylocalorglobalkeywords.Undefinedvariableswillbe
markedasundefinedandwillresultincompilationerror.Example:
#followingcodewillresultincompilationerror,becausemyVarisusedwithoutdeclaration
:setmyVar"myvalue"
:put$myVar
Correctcode:
:localmyVar
:setmyVar"myvalue"
:put$myVar
Validcharactersinvariablenamesarelettersanddigits.Ifvariablenamecontainsanyothercharacter,thenvariablenameshouldbeputin
doublequotes.Example:
#validvariablename
:localmyVar
#invalidvariablename
:localmyvar
#validbecausedoublequoted
:global"myvar"
Ifvariableisinitiallydefinedwithoutvaluethenvariabledatatypeissettonil,otherwisedatatypeisdeterminedautomaticallybyscripting
engine.Sometimesconversionfromonedatatypetoanotherisrequired.Itcanbeachievedusingdataconversioncommands.Example:
#convertstringtoarray
:localmyStr"1,2,3,4,5"
:put[:typeof$myStr]
:localmyArr[:toarray$myStr]
:put[:typeof$myArr]
Variablenamesarecasesensitive.
:localmyVar"hello"
#followinglinewillgenerateerror,becausevariablemyVArisnotdefined
:put$myVAr
#correctcode
:put$myVar
Commands
GIobaI commands
Everyglobalcommandshouldstartwith":"token,otherwiseitwillbetreatedasvariable.
Command Syntax Description ExampIe
/ gotorootmenu
.. gobackbyonemenulevel
? listallavailablemenucommandsandbrief
descriptions
29/02/12 Manual:Scripting - MikroTik Wiki
8/11 iki.mikrotik.com/iki/Manual:Scripting#Global_commands
global :global<var>[<value>] defineglobalvariable :globalmyVar
"something":put$myVar
local :local<var>[<value>] definelocalvariable {:localmyLocalVar"Iam
local":put$myVar}
beep :beep<freq><length> beepbuiltinspeaker
delay :delay<time> donothingforagivenperiodoftime
put :put<expression> putsuppliedargumenttoconsole
len :len<expression> returnstringlengthorarrayelementcount :put[:len"length=8"]
typeof :typeof<var> returndatatypeofvariable :put[:typeof4]
pick :pick<var><start>[<end>] returnrangeofelementsorsubstring.Ifend
positionisnotspecified,willreturnonlyone
elementfromanarray.
:put[:pick"abcde"13]
log :log<topic><message> writemessagetosystemlog.Available
topicsare"debug,error,infoand
warning"
:loginfo"Hellofrom
script"
time :time<expression> returnintervaloftimeneededtoexecute
command
:put[:time{:forifrom=1
to=10do={:delay100ms}}]
set :set<var>[<value>] assignvaluetodeclaredvariable.Jaset
bezveertiibastadtypofir'nil'vajadzetubut
nothing.
:globala:setatrue
find :find<arg><arg><start> returnpositionofsubstringorarrayelement :put[:find"abc""a"1]
environment :environmentprint<start> printinitializedvariableinformation :globalmyVar
true:environmentprint
terminal terminalrelatedcommands
error :error<output> Generateconsoleerrorandstopexecuting
thescript
parse :parse<expression> parsestringandreturnparsedconsole
commands.Canbeusedasfunction.
:globalmyFunc[:parse":put
hello!"]
$myFunc
resolve :resolve<arg> returnIPaddressofgivenDNSname :put[:resolve
"www.mikrotik.com"]
toarray :toarray<var> convertvariabletoarray
tobool :tobool<var> convertvariabletoboolean
toid :toid<var> convertvariabletointernalID
toip :toip<var> convertvariabletoIPaddress
toip6 :toip6<var> convertvariabletoIPv6address
tonum :tonum<var> convertvariabletointeger
tostr :tostr<var> convertvariabletostring
totime :totime<var> convertvariabletotime
Menu specific commands
Common commands
Followingcommandsavailablefrommostsubmenus:
Command Syntax Description
add add<param>=<value>..<param>=<value> addnewitem
remove remove<id> removeselecteditem
29/02/12 Manual:Scripting - MikroTik Wiki
9/11 iki.mikrotik.com/iki/Manual:Scripting#Global_commands
enable enable<id> enableselecteditem
disable disable<id> disableselecteditem
set set<id><param>=<value>..<param>=<value> changeselecteditemsparameter,morethanoneparametercanbe
specifiedatthetime
get get<id><param>=<value> getselecteditemsparametervalue
print print<param><param>=[<value>] printmenuitems.Outputdependsonprintparametersspecified.Most
commonprintparametersaredescribedhere
export export[file=<value>] exportconfigurationfromcurrentmenuanditssubmenus(ifpresent).If
fileparameterisspecifiedoutputwillbewrittentofilewithextension
'.rsc',otherwiseoutputwillbeprintedtoconsole.Exportedcommands
canbeimportedbyimportcommand
edit edit<id><param> editselecteditemspropertyinbuiltintexteditor
find find<expression> finditemsbygivenexpression.
import
Importcommandisavailablefromrootmenuandisusedtoimportconfigurationfromfilescreatedbyexportcommandorwrittenmanuallyby
hand.
print parameters
Severalparametersareavailableforprintcommand:
Parameter Description ExampIe
append
asvalue printoutputasarrayofparametersanditsvalues :put[/ipaddressprintasvalue]
brief printbriefdescription
detail printdetaileddescription,outputisnotasreadableasbriefoutput,but
maybeusefultoviewallparameters
countonly printonlycountofmenuitems
file printoutputtofile
follow printallcurrententriesandtracknewentriesuntilctrlcispressed,very
usefulwhenviewinglogentries
/logprintfollow
followonly printandtrackonlynewentriesuntilctrlcispressed,veryusefulwhen
viewinglogentries
/logprintfollowonly
from printparametersonlyfromspecifieditem /userprintfrom=admin
interval continuouslyprintoutputinselectedtimeinterval,usefultotrackdown
changeswherefollowisnotacceptable
/interfaceprintinterval=2
terse showdetailsincompactandmachinefriendlyformat
valuelist showvaluesoneperline(goodforparsingpurposes)
withoutpaging Ifoutputdonotfitinconsolescreenthendonotstop,printall
informationinonepiece
where expressionsfollowedbywhereparametercanbeusedtofilterout
matchedentries
/iprouteprintwhere
interface="ether1"
Morethanoneparametercanbespecifiedatatime,forexample,/iprouteprintcountonlyinterval=1where
interface="ether1"
Loops and conditionaI statements
Loops
29/02/12 Manual:Scripting - MikroTik Wiki
10/11 iki.mikrotik.com/iki/Manual:Scripting#Global_commands
Command Syntax Description
do..while :do{<commands>}while=(<conditions>
):while(<conditions>)do={
<commands>}
executecommandsuntilgivenconditionismet.
for :for<var>from=<int>to=<int>step=<int>
do={<commands>}
executecommandsoveragivennumberofiterations
foreach :foreach<var>in=<array>do={<commands>
}
executecommandsforeachelementsinlist
ConditionaI statement
Command Syntax Description
if :if(<condition>)do={<commands>}else=
{<commands>}<expression>
Ifagivenconditionistruethenexecutecommandsinthedoblock,
otherwiseexecutecommandsintheelseblockifspecified.
Example:
{
:localmyBooltrue
:if($myBool=false)do={:put"valueisfalse"}else={:put"valueistrue"}
}
Scriptrepository
Sub-menu IeveI:/systemscript
Containsallusercreatedscripts.Scriptscanbeexecutedinseveraldifferentways:
on eventscriptsareexecutedautomaticallyonsomefacilityevents(scheduler,netwatch,VRRP)
by another scriptrunningscriptwithinscriptisallowed
manuaIIyfromconsoleexecutingruncommandorinwinbox
Property Description
name(stringDefault:"Script[num]") nameofthescript
policy(stringDefault:) listofapplicablepolicies:
ftpusercanlogonremotelyviaftpandsendandretrievefilesfrom
therouter
IocaIusercanlogonlocallyviaconsole
poIicymanageuserpolicies,addandremoveuser
readusercanretrievetheconfiguration
rebootusercanreboottherouter
sshusercanlogonremotelyviasecureshell
teInetusercanlogonremotelyviatelnet
testusercanrunping,traceroute,bandwidthtest
webusercanlogonremotelyviahttp
writeusercanretrieveandchangetheconfiguration
source(string) Scriptsourcecode
Readonlystatusproperties:
Property Description
laststarted(date) Dateandtimewhenthescriptwaslastinvoked.
owner(string) Userwhocreatedthescript
29/02/12 Manual:Scripting - MikroTik Wiki
11/11 iki.mikrotik.com/iki/Manual:Scripting#Global_commands
owner(string) Userwhocreatedthescript
runcount(integer) Counterthatcountshowmanytimesscripthasbeenexecuted
Menuspecificcommands
Command Description
run(run[id|name]) ExecutespecifiedscriptbyIDorname
Environment
Sub-menu IeveI:
/systemscriptenvironment
/environment
Containsalluserdefinedvariablesandtheirassignedvalues.
[admin@MikroTik]>:globalexample
[admin@MikroTik]>:setexample123
[admin@MikroTik]>/environmentprint
"example"=123
Readonlystatusproperties:
Property Description
name(string) Variablename
user(string) Userwhodefinedvariable
value() Valueassignedtovariable
Job
Sub-menu IeveI:/systemscriptjob
Containslistofallcurrentlyrunningscripts.
Readonlystatusproperties:
Property Description
owner(string) Userwhoisrunningscript
policy(array) Listofallpoliciesappliedtoscript
started(date) Localdateandtimewhenscriptwasstarted
Seealso
ScriptingExamples
UsersubmittedScripts
[Top|BacktoContent]
Categories:Manual|System|Console|CaseStudies