Manual:Scripting: Difference between revisions

From MikroTik Wiki
Jump to navigation Jump to search
No edit summary
(129 intermediate revisions by 8 users not shown)
Line 1: Line 1:
<div class=manual>
{{Versions| any}}


<h2>Scripting language manual</h2>
==Scripting language manual==
lala
 
<h3>Line structure</h3>
This manual provides introduction to RouterOS built-in powerful scripting language.
<p>RouterOS script is divided into number of command lines.</p>
 
Scripting host provides a way to automate some router maintenance tasks by means of executing user-defined scripts bounded to some event occurrence.
 
Scripts can be stored in [[#Script_repository|Script repository]] or can be written directly to [[M:Console|console]].
The events used to trigger script execution include, but are not limited to the [[M:System/Scheduler | System Scheduler]], the [[Manual:Tools/Traffic_Monitor | Traffic Monitoring Tool]], and the [[M:Tools/Netwatch | Netwatch Tool]] generated events.
 
 
===Line structure===
 
RouterOS script is divided into number of command lines. Command lines are executed one by one until the end of script or until runtime error occur.
 
 
====Command line====
 
RouterOS console uses following command syntax:


<h4>Command line</h4>
<p>
RouterOS console uses following command syntax:<br />
<code>[prefix] [path] command [uparam] [param=[value]] .. [param=[value]]</code>
<code>[prefix] [path] command [uparam] [param=[value]] .. [param=[value]]</code>
<ul>
<ul class="bullets">
<li>[prefix] - ":" or "/" character which indicates if command is [[#Commands|ICE]] or path. May or may not be required.
<li>[prefix] - ":" or "/" character which indicates if command is [[#Commands|ICE]] or path. May or may not be required.
<li>[path] - relative path to the desired menu level. May or may not be required.
<li>[path] - relative path to the desired menu level. May or may not be required.
<li>command - one of the [[#Commands|commands]] available at the specified menu level.
<li>command - one of the [[#Commands|commands]] available at the specified menu level.
<li>[uparam] - must be specified if command requires it.
<li>[uparam] - unnamed parameter, must be specified if command requires it.
<li>[params] - sequence of parameter names followed by respective values
<li>[params] - sequence of named parameters followed by respective values
</ul>
</ul>
The end of command line is represented by the token <i>“;”</i> or <i>NEWLINE</i>. Sometimes <i>“;”</i> or <i>NEWLINE</i> is not required to end the command line. <br />
 
The end of command line is represented by the token <i>“;”</i> or <i>NEWLINE</i>. Sometimes <i>“;”</i> or <i>NEWLINE</i> is not required to end the command line.  


Single command inside <code>(), [] or {}</code> does not require any end of command character. End of command is determined by content of whole script
Single command inside <code>(), [] or {}</code> does not require any end of command character. End of command is determined by content of whole script
Line 27: Line 39:
:put [/ip route get [find gateway=1.1.1.1]];   
:put [/ip route get [find gateway=1.1.1.1]];   
</pre>
</pre>
Notice that code above contains three command lines:<ul>
Notice that code above contains three command lines:
<ul class="bullets">
<li>:put  
<li>:put  
<li>/ip route get
<li>/ip route get
Line 34: Line 47:


Command line can be constructed from more than one physical line by following [[#Line_joining|line joining rules]].
Command line can be constructed from more than one physical line by following [[#Line_joining|line joining rules]].
</p>


<h4>Physical Line</h4>
 
<p>A physical line is a sequence of characters terminated by an end-of-line (EOL) sequence. Any of the standard platform line termination sequences can be used:<ul>
====Physical Line====
  <li><b><var>unix</var></b> – ASCII LF;
<p>A physical line is a sequence of characters terminated by an end-of-line (EOL) sequence. Any of the standard platform line termination sequences can be used:
  <li><b><var>windows</var></b> – ASCII CR LF;
<ul class="bullets">
  <li><b><var>mac</var></b> – ASCII CR;
<li><b><var>unix</var></b> – ASCII LF;
<li><b><var>windows</var></b> – ASCII CR LF;
<li><b><var>mac</var></b> – ASCII CR;
</ul>
</ul>
Standard C conventions for new line characters can be used ( the \n character).
Standard C conventions for new line characters can be used ( the \n character).
</p>
</p>


<h4>Comments</h4>
====Comments====
<p>A comment starts with a hash character (#) and ends at the end of the physical line. Whitespace or any other symbols are not allowed before hash symbol. Comments are ignored by syntax. If (#) character appear inside string it is not considered a comment.
<p>A comment starts with a hash character (#) and ends at the end of the physical line. Whitespace or any other symbols are not allowed before hash symbol. Comments are ignored by syntax. If (#) character appear inside string it is not considered a comment.
<h5>Example</h5>
<h5>Example</h5>
Line 58: Line 72:




<h4>Line joining</h4>
====Line joining====
<p>Two or more physical lines may be joined into logical lines using backslash character (\). A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals. A backslash is illegal elsewhere on a line outside a string literal.  
<p>Two or more physical lines may be joined into logical lines using backslash character (\). A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals. A backslash is illegal elsewhere on a line outside a string literal.  


Line 76: Line 90:




<h4>Whitespace between tokens</h4>
====Whitespace between tokens====
<p>
<p>
Whitespace can be used to separate tokens. Whitespace is necessary between two tokens  only if their concatenation could be interpreted as a different token.
Whitespace can be used to separate tokens. Whitespace is necessary between two tokens  only if their concatenation could be interpreted as a different token.
Line 90: Line 104:
}
}
</nowiki></pre>
</nowiki></pre>
Whitespace are not allowed<ul>
Whitespace are not allowed
<ul class="bullets">
<li>between '<nowiki><parameter></nowiki>='
<li>between '<nowiki><parameter></nowiki>='
<li>between 'from=' 'to=' 'step=' 'in=' 'do=' 'else='
<li>between 'from=' 'to=' 'step=' 'in=' 'do=' 'else='
Line 111: Line 126:
</p>
</p>


<h4>Scopes</h4>
====Scopes====
<p>
<p>
something about scopes { lalala }
Variables can be used only in certain regions of the script. These regions are called scopes. Scope determines visibility of the variable. There are two types of scopes - <var>global</var> and <var>local</var>.
A variable declared within a block is accessible only within that block and blocks enclosed by it, and only after the point of declaration.
</p>
</p>


<h3>Keywords</h3>
=====Global scope=====
 
Global scope or root scope is default scope of the script. It is created automatically and can not be turned off.
 
 
=====Local scope=====
<p>
User can define its own groups to block access to certain variables, these scopes are called local scopes. Each local scope is enclosed in curly braces ("{ }").
<pre>
{
  :local a 3;
  {
      :local b 4;
      :put ($a+$b);
  }
#line below will show variable b in light red color since it is not defined in scope
  :put ($a+$b);
}
</pre>
 
In code above variable <var>b</var> has local scope and will not be accessible after closed curly brace. <br />
</p>
 
{{Note | Each line written in terminal is treated as local scope }}
So for example, defined local variable will not be visible in next command line and will generate syntax error
<pre>
[admin@MikroTik] > :local myVar a;
[admin@MikroTik] > :put $myVar
syntax error (line 1 column 7)
</pre>
{{ Warning | <b>Do not define global variables inside local scopes.</b><br /> }}
<p>
 
Note that even variable can be defined as global, it will be available only from its scope unless it is not already defined.<br />
<pre>
{
  :local a 3;
  {
      :global b 4;
  }
  :put ($a+$b);
}
</pre>
Code above will generate an error.<br />
 
</p>
 
===Keywords===
<p>
<p>


The following words are keywords and cannot be used as variable and function names:
The following words are keywords and cannot be used as variable and function names:
<pre><nowiki>
<pre><nowiki>
and      or       not       in
and      or      in
</nowiki></pre>
</nowiki></pre>
<!--
<!--
and      or        not       break
and      or        not
continue  do        for      foreach
do        for      foreach
in        from      to        while
in        from      to        while
global    local    if        else
global    local    if        else
Line 132: Line 195:


<!-- ---------------------------------------------------------------------- -->
<!-- ---------------------------------------------------------------------- -->
<h3>Delimiters</h3>
===Delimiters===
<p>
<p>
The following tokens serve as delimiters in the grammar:
The following tokens serve as delimiters in the grammar:
Line 141: Line 204:




<h3>Data types</h3>
===Data types===
<p>
<p>
RouterOS scripting language has following data types:
RouterOS scripting language has following data types:
Line 150: Line 213:
</tr>
</tr>
<tr>
<tr>
   <td ><b><var>number</var></b></td>
   <td ><b><var>num (number)</var></b></td>
   <td >- 64bit signed integer, possible hexadecimal input;</td>
   <td >- 64bit signed integer, possible hexadecimal input;</td>
</tr>
</tr>
<tr>
<tr>
   <td ><b><var>boolean</var></b></td>
   <td ><b><var>bool (boolean)</var></b></td>
   <td >- values can bee <code>true</code> or <code>false</code>;</td>
   <td >- values can bee <code>true</code> or <code>false</code>;</td>
</tr>
</tr>
<tr>
<tr>
   <td ><b><var>string</var></b></td>
   <td ><b><var>str (string)</var></b></td>
   <td >- character sequence;</td>
   <td >- character sequence;</td>
</tr>
</tr>
<tr>
<tr>
   <td ><b><var>IP</var></b></td>
   <td ><b><var>ip</var></b></td>
   <td >- IP address;</td>
   <td >- IP address;</td>
</tr>
</tr>
<tr>
<tr>
   <td ><b><var>internal ID</var></b></td>
   <td ><b><var>ip-prefix</var></b></td>
  <td >- IP prefix;</td>
</tr>
<tr>
  <td ><b><var>ip6-prefix</var></b></td>
  <td >- IPv6 prefix</td>
</tr>
<tr>
  <td ><b><var>id (internal ID)</var></b></td>
   <td >- hexadecimal value prefixed by '*' sign. Each menu item has assigned unique number - internal ID;</td>
   <td >- hexadecimal value prefixed by '*' sign. Each menu item has assigned unique number - internal ID;</td>
</tr>
</tr>
Line 185: Line 256:
</p>
</p>


<h4>Constant Escape Sequences</h4>
====Constant Escape Sequences====
<p>
<p>
Following escape sequences can be used to define certain special character within string:
Following escape sequences can be used to define certain special character within string:
Line 191: Line 262:
<tr>
<tr>
   <td ><b>\"</b></td>
   <td ><b>\"</b></td>
   <td > - double quote</td>
   <td >Insert double quote</td>
</tr>
</tr>
<tr>
<tr>
   <td ><b>\\</b></td>
   <td ><b>\\</b></td>
   <td > - backslash</td>
   <td >Insert backslash</td>
</tr>
</tr>
<tr>
<tr>
   <td ><b>\n</b></td>
   <td ><b>\n</b></td>
   <td > - newline</td>
   <td >Insert newline</td>
</tr>
</tr>
<tr>
<tr>
   <td ><b>\r</b></td>
   <td ><b>\r</b></td>
   <td > - carriage return</td>
   <td >Insert carriage return</td>
</tr>
</tr>
<tr>
<tr>
   <td ><b>\t</b></td>
   <td ><b>\t</b></td>
   <td > - horizontal tab</td>
   <td >Insert horizontal tab</td>
</tr>
</tr>
<tr>
<tr>
   <td ><b>\$</b></td>
   <td ><b>\$</b></td>
   <td ></td>
   <td >Output $ character. Otherwise $ is used to link variable.</td>
</tr>
</tr>
<tr>
<tr>
   <td ><b>\?</b></td>
   <td ><b>\?</b></td>
   <td ></td>
   <td >Output ? character. Otherwise ? is used to print "help" in console.</td>
</tr>
</tr>
<tr>
<tr>
Line 226: Line 297:
</tr>
</tr>
<tr>
<tr>
   <td ><b>\a</b></td>
   <td ><b>\b</b></td>
   <td > - backspace (0x08)</td>
   <td > - backspace (0x08)</td>
</tr>
</tr>
Line 235: Line 306:
<tr>
<tr>
   <td ><b>\v</b></td>
   <td ><b>\v</b></td>
   <td > - vertical tab</td>
   <td >Insert vertical tab</td>
</tr>
</tr>
<tr>
<tr>
   <td ><b>\xx</b></td>
   <td ><b>\xx</b></td>
   <td > - hex value</td>
   <td >Print character from hex value. Hex number should use capital letters.</td>
</tr>
</tr>
</table>
</table>
Line 258: Line 329:
</p>
</p>


 
===Operators===
<h3>Operators</h3>
<p>
<p>
lala
</p>
</p>


<h4>Arithmetic Operators</h4>
====Arithmetic Operators====
<p>
<p>
Usual arithmetic operators are supported in RouterOS scripting language<br />
Usual arithmetic operators are supported in RouterOS scripting language<br />
Line 270: Line 339:
<table class="styled_table">
<table class="styled_table">
<tr>
<tr>
   <th width="100">Opearator</th>
   <th width="100">Operator</th>
   <th width="300">Description</th>
   <th width="300">Description</th>
   <th >Example</th>
   <th >Example</th>
Line 292: Line 361:
   <td><b><var>"/"</var></b></td>
   <td><b><var>"/"</var></b></td>
   <td>binary division</td>
   <td>binary division</td>
   <td><code>:put (10/2);</code></td>
   <td><code>:put (10 / 2); :put ((10)/2)</code></td>
</tr>
<tr>
  <td><b><var>"%"</var></b></td>
  <td>modulo operation</td>
  <td><code>:put (5 % 3);</code></td>
</tr>
</tr>
<tr>
<tr>
Line 302: Line 376:
</p>
</p>


<h4>Relational Operators</h4>
{{note| for division to work you have to use braces or spaces around dividend so it is not mistaken as IP address}}
 
====Relational Operators====
<p>
<p>


<table class="styled_table">
<table class="styled_table">
<tr>
<tr>
   <th width="100">Opearator</th>
   <th width="100">Operator</th>
   <th width="300">Description</th>
   <th width="300">Description</th>
   <th>Example</th>
   <th>Example</th>
Line 345: Line 421:
</p>
</p>


<h4>Logical Operators</h4>
====Logical Operators====
<p>
<p>
<table  class="styled_table">
<table  class="styled_table">
<tr>
<tr>
   <th width="100">Opearator</th>
   <th width="100">Operator</th>
   <th width="300">Description</th>
   <th width="300">Description</th>
   <th >Example</th>
   <th >Example</th>
</tr>
</tr>
<tr>
<tr>
   <td><b><var>“!” , “not”</var></b></td>
   <td><b><var>“!”</var></b></td>
   <td>logical NOT</td>
   <td>logical NOT</td>
   <td><code>:put (!true);</code></td>
   <td><code>:put (!true);</code></td>
Line 367: Line 443:
   <td>logical OR</td>
   <td>logical OR</td>
   <td><code>:put (true||false);</code></td>
   <td><code>:put (true||false);</code></td>
</tr>
<tr>
  <td><b><var>“in”</var></b></td>
  <td></td>
  <td><code>:put (1.1.1.1/32 in 1.0.0.0/8);</code></td>
</tr>
</tr>
</table>
</table>
</p>
</p>


<h4>Bitwise Operators</h4>
====Bitwise Operators====
<p>
 
Bitwise operators are working on number and ip address [[#Data_types|data types]].
Bitwise operators are working on number and ip address [[#Data_types|data types]].


<table class="styled_table">
<table class="styled_table">
<tr>
<tr>
   <th width="100" align="left">Opearator</th>
   <th width="100">Operator</th>
   <th width="300" align="left">Description</th>
   <th width="300">Description</th>
   <th align="left">Example</th>
   <th>Example</th>
</tr>
</tr>
<tr>
<tr>
Line 389: Line 471:
   <td><b><var>“|”</var></b></td>
   <td><b><var>“|”</var></b></td>
   <td>bitwise OR. Performs logical OR operation on each pair of corresponding bits. In each pair the result is “1” if one of bits or both bits are “1”, otherwise the result is “0”.</td>
   <td>bitwise OR. Performs logical OR operation on each pair of corresponding bits. In each pair the result is “1” if one of bits or both bits are “1”, otherwise the result is “0”.</td>
   <td><code></code></td>
   <td><code>:put (192.168.88.0|0.0.0.255)</code></td>
</tr>
</tr>
<tr>
<tr>
Line 399: Line 481:
   <td><b><var>“&”</var></b></td>
   <td><b><var>“&”</var></b></td>
   <td>bitwise AND. In each pair the result is “1” if first and second bit is “1”. Otherwise the result is “0”.</td>
   <td>bitwise AND. In each pair the result is “1” if first and second bit is “1”. Otherwise the result is “0”.</td>
   <td><code></code></td>
   <td><code>:put (192.168.88.77&255.255.255.0)</code></td>
</tr>
</tr>
<tr>
<tr>
   <td><b><var>“<<”</var></b></td>
   <td><b><var>“<<”</var></b></td>
   <td>left shift by given amount of bits</td>
   <td>left shift by given amount of bits</td>
   <td><code></code></td>
   <td><code>:put (192.168.88.77<<8)</code></td>
</tr>
</tr>
<tr>
<tr>
   <td><b><var>“>>”</var></b></td>
   <td><b><var>“>>”</var></b></td>
   <td>right shift by given amount of bits</td>
   <td>right shift by given amount of bits</td>
   <td><code></code></td>
   <td><code>:put (192.168.88.77>>24)</code></td>
</tr>
</tr>
</table>
</table>
</p>


<h4>Concatenation Operators</h4>
 
<p>
Calculate subnet address from given IP and CIDR Netmask using "&" operator:
<pre>
{
:local IP 192.168.88.77;
:local CIDRnetmask 255.255.255.0;
:put ($IP&$CIDRnetmask);
}
</pre>
 
Get last 8 bits from given IP addresses:
<pre>
:put (192.168.88.77&0.0.0.255);
</pre>
 
Use "|" operator and inverted CIDR mask to calculate the broadcast address:
<pre>
{
:local IP 192.168.88.77;
:local Network 192.168.88.0;
:local CIDRnetmask 255.255.255.0;
:local InvertedCIDR (~$CIDRnetmask);
:put ($Network|$InvertedCIDR)
}
</pre>
 
 
====Concatenation Operators====
 
<table  class="styled_table">
<table  class="styled_table">
<tr>
<tr>
   <th width="100">Opearator</th>
   <th width="100">Operator</th>
   <th width="300">Description</th>
   <th width="300">Description</th>
   <th>Example</th>
   <th>Example</th>
Line 434: Line 542:
</table>
</table>


</p>


<h4>Other Operators</h4>
It is possible to add variable values to strings without concatenation operator:
<p>
<pre>
:global myVar "world";
 
:put ("Hello " . $myVar);
# next line does the same as above
:put "Hello $myVar";
</pre>
 
By using $[] and $() in string it is possible to add expressions inside strings:
<pre>
:local a 5;
:local b 6;
:put " 5x6 = $($a * $b)";
 
:put " We have $[ :len [/ip route find] ] routes";
</pre>
 
====Other Operators====
 


<table class="styled_table">
<table class="styled_table">
<tr>
<tr>
   <th width="100">Opearator</th>
   <th width="100">Operator</th>
   <th width="300">Description</th>
   <th width="300">Description</th>
   <th>Example</th>
   <th>Example</th>
Line 447: Line 572:
<tr>
<tr>
   <td><b><var>“[]”</var></b></td>
   <td><b><var>“[]”</var></b></td>
   <td>command substitution</td>
   <td>command substitution. Can contain only single command line</td>
   <td><code>:put [ :len "my test string"; ];</code></td>
   <td><code>:put [ :len "my test string"; ];</code></td>
</tr>
</tr>
<tr>
<tr>
   <td><b><var>“()”</var></b></td>
   <td><b><var>“()”</var></b></td>
   <td>sub expression operator</td>
   <td>sub expression or grouping operator</td>
   <td><code>:put ( "value is " . (4+5));</code></td>
   <td><code>:put ( "value is " . (4+5));</code></td>
</tr>
<tr>
  <td><b><var>“->”</var></b></td>
  <td>access operator</td>
  <td><code>(object)->(key)</code></td>
</tr>
</tr>
<tr>
<tr>
Line 464: Line 584:
   <td>substitution operator</td>
   <td>substitution operator</td>
   <td><code>:global a 5; :put $a;</code></td>
   <td><code>:global a 5; :put $a;</code></td>
</tr>
<tr>
  <td><b><var>“~”</var></b></td>
  <td>binary operator that matches value against POSIX extended regular expression</td>
  <td>Print all routes which gateway ends with 202<br />
<code>/ip route print where gateway~"^[0-9 \\.]*202\$"</code></td>
</tr>
  <td><b><var>“->”</var></b></td>
  <td>Get an array element by key</td>
  <td><pre>[admin@x86] >:global aaa {a=1;b=2}
[admin@x86] > :put ($aaa->"a")
1
[admin@x86] > :put ($aaa->"b")
2</pre></td>
</tr>
</tr>
</table>
</table>
</p>


<h3>Variables</h3>
===Variables===
<p>
 
Scripting language has two types of variables: <ul>
Scripting language has two types of variables:  
<li> <var>global</var> - accessible from all current users scripts, defined by [[#Global_commands|global]] keyword;
<ul class="bullets">
<li> <var>global</var> - accessible from all scripts created by current user, defined by [[#Global_commands|global]] keyword;
<li> <var>local</var> - accessible only within the current [[#Scopes|scope]], defined by [[#Global_commands|local]] keyword.  
<li> <var>local</var> - accessible only within the current [[#Scopes|scope]], defined by [[#Global_commands|local]] keyword.  
</ul>
</ul>
{{Note | Starting from v6.2 there can be undefined variables. When variable is undefined parser will try to look for variables set, for example, by [[M:IP/DHCP_Server | DHCP]] <var>lease-script</var> or [[Hotspot]] <var>on-login</var> }}
{{Note | Variable value size is limited to 4096bytes }}
Every variable, except for built in RouterOS variables, must be declared before usage by local or global keywords. Undefined variables will be marked as undefined and will result in compilation error.
Every variable, except for built in RouterOS variables, must be declared before usage by local or global keywords. Undefined variables will be marked as undefined and will result in compilation error.
Example:
Example:
Line 481: Line 618:
:put $myVar
:put $myVar
</pre>
</pre>
Correct code:
Correct code:
<pre>
<pre>
Line 487: Line 625:
:put $myVar;
:put $myVar;
</pre>
</pre>
Exception is when using variables set, for example, by DHCP <var>lease-script</var>
<pre>
/system script
add name=myLeaseScript policy=\
    ftp,reboot,read,write,policy,test,winbox,password,sniff,sensitive,api \
    source=":log info \$leaseActIP\r\
    \n:log info \$leaseActMAC\r\
    \n:log info \$leaseServerName\r\
    \n:log info \$leaseBound"
/ip dhcp-server set  myServer lease-script=myLeaseScript
</pre>
Valid characters in variable names are letters and digits. If variable name contains any other character, then variable name should be put in double quotes. Example:
Valid characters in variable names are letters and digits. If variable name contains any other character, then variable name should be put in double quotes. Example:
<pre>
<pre>
:local myVar;  #valid variable name
#valid variable name
:local my-var; #invalid variable name
:local myVar;   
:global "my-var"; #valid because double quoted
#invalid variable name
:local my-var;  
#valid because double quoted
:global "my-var";  
</pre>
</pre>
If variable is initially defined without value then [[#Data_types|variable data type]] is set to <i>nil</i>, otherwise data type is determined automatically by scripting engine. Sometimes conversion from one data type to another is required. It can be achieved using [[#Global_commands|data conversion commands]]. Example:
If variable is initially defined without value then [[#Data_types|variable data type]] is set to <i>nil</i>, otherwise data type is determined automatically by scripting engine. Sometimes conversion from one data type to another is required. It can be achieved using [[#Global_commands|data conversion commands]]. Example:
<pre>
<pre>
Line 502: Line 658:
</pre>
</pre>


</p>
Variable names are case sensitive.
<pre>
:local myVar "hello"
# following line will generate error, because variable myVAr is not defined
:put $myVAr
# correct code
:put $myVar
</pre>
 
Set command without value will un-define the variable (remove from environment, new in v6.2)
<pre>
#remove variable from environment
:global myVar "myValue"
:set myVar;
</pre>
==== Reserved variable names====
 
All built in RouterOS properties are reserved variables. Variables which will be defined the same as the RouterOS built in properties can cause errors. To avoid such errors, use custom designations.
 
For example, following script will not work:
<pre>
{
:local type "ether1";
/interface print where name=$type;
}
</pre>
But will work with different defined variable:
<pre>
{
:local customname "ether1";
/interface print where name=$customname;
}
</pre>


<h3>Commands</h3>
===Commands===
<h4>Global commands</h4>
<h4>Global commands</h4>
<p>Every global command should start with <i>":"</i> token, otherwise it will be treated as variable. ( Velak laikam buus ka vares rakstit komandas bez ";"
<p>Every global command should start with <i>":"</i> token, otherwise it will be treated as variable.


<table class="styled_table">
<table class="styled_table">
Line 578: Line 766:
   <td><b><var>pick</var></b></td>
   <td><b><var>pick</var></b></td>
   <td><code><nowiki>:pick <var> <start>[<end>]</nowiki></code></td>
   <td><code><nowiki>:pick <var> <start>[<end>]</nowiki></code></td>
   <td>return range of elements or substring. If end position is not specified, will return all elements from given position to end of string or array.</td>
   <td>return range of elements or substring. If end position is not specified, will return only one element from an array.</td>
   <td><code>:put [:pick "abcde" 1 3]</code></td>
   <td><code>:put [:pick "abcde" 1 3]</code></td>
</tr>
</tr>
Line 584: Line 772:
   <td><b><var>log</var></b></td>
   <td><b><var>log</var></b></td>
   <td><code><nowiki>:log <topic> <message></nowiki></code></td>
   <td><code><nowiki>:log <topic> <message></nowiki></code></td>
   <td>write message to system log. Available topics are [[system logging]]</td>
   <td>write message to [[log | system log]]. Available topics are <code>"debug, error, info and warning"</code></td>
   <td><code>:log info "Hello from script";</code></td>
   <td><code>:log info "Hello from script";</code></td>
</tr>
</tr>
Line 596: Line 784:
   <td><b><var>set</var></b></td>
   <td><b><var>set</var></b></td>
   <td><code><nowiki>:set <var> [<value>]</nowiki></code></td>
   <td><code><nowiki>:set <var> [<value>]</nowiki></code></td>
   <td>assign value to declared variable. Ja set bez veertiibas tad typof ir 'nil' vajadzetu but nothing.</td>
   <td>assign value to declared variable.</td>
   <td><code>:global a; :set a true;</code></td>
   <td><code>:global a; :set a true;</code></td>
</tr>
</tr>
Line 603: Line 791:
   <td><code><nowiki>:find <arg> <arg> <start></nowiki></code></td>
   <td><code><nowiki>:find <arg> <arg> <start></nowiki></code></td>
   <td>return position of substring or array element</td>
   <td>return position of substring or array element</td>
   <td><code>:put [:find "abc" "a" -1]; #kaapeec -1?? jaabuut 0</code></td>
   <td><code>:put [:find "abc" "a" -1];</code></td>
</tr>
</tr>
<tr>
<tr>
Line 620: Line 808:
   <td><b><var>error</var></b></td>
   <td><b><var>error</var></b></td>
   <td><code><nowiki>:error <output> </nowiki></code></td>
   <td><code><nowiki>:error <output> </nowiki></code></td>
   <td>generate console error</td>
   <td>Generate console error and stop executing the script</td>
   <td><code></code></td>
   <td><code></code></td>
</tr>
</tr>
<tr>
<tr>
   <td><b><var>write</var></b></td>
   <td><b><var>execute</var></b></td>
   <td><code><nowiki> </nowiki></code></td>
   <td><code><nowiki>:execute <expression> </nowiki></code></td>
   <td>izmests</td>
   <td>Execute the script in background.</td>
   <td><code></code></td>
   <td><pre>{
:local j [:execute {/interface print follow where [:log info ~Sname~]}];
:delay 10s;
:do { /system script job remove $j } on-error={}
}</pre></td>
</tr>
</tr>
<tr>
<tr>
   <td><b><var>parse</var></b></td>
   <td><b><var>parse</var></b></td>
   <td><code><nowiki>:parse <expression> </nowiki></code></td>
   <td><code><nowiki>:parse <expression> </nowiki></code></td>
   <td>parse string and return parsed console commands. (parsees arii LUA)</td>
   <td>parse string and return parsed console commands. Can be used as function.</td>
   <td><code></code></td>
   <td><code>:global myFunc [:parse ":put hello!"];<br />
  $myFunc;</code></td>
</tr>
</tr>
<tr>
<tr>
Line 639: Line 832:
   <td><code><nowiki>:resolve <arg> </nowiki></code></td>
   <td><code><nowiki>:resolve <arg> </nowiki></code></td>
   <td>return IP address of given DNS name</td>
   <td>return IP address of given DNS name</td>
   <td><code>:put [:resolve "www.google.lv"];</code></td>
   <td><code>:put [:resolve "www.mikrotik.com"];</code></td>
</tr>
</tr>
<tr>
<tr>
Line 667: Line 860:
<tr>
<tr>
   <td><b><var>toip6</var></b></td>
   <td><b><var>toip6</var></b></td>
   <td><code><nowiki>:toip <var> </nowiki></code></td>
   <td><code><nowiki>:toip6 <var> </nowiki></code></td>
   <td>convert variable to IPv6 address</td>
   <td>convert variable to IPv6 address</td>
   <td><code></code></td>
   <td><code></code></td>
Line 687: Line 880:
   <td><code><nowiki>:totime <var> </nowiki></code></td>
   <td><code><nowiki>:totime <var> </nowiki></code></td>
   <td>convert variable to time</td>
   <td>convert variable to time</td>
  <td><code></code></td>
</tr>
<tr>
  <td><b><var>break</var></b></td>
  <td><code><nowiki>:break </nowiki></code></td>
  <td>It terminates the nearest enclosing loop. If a for loop is terminated by break, the loop control target keeps its current value. break may only occur syntactically nested in a [[#Loops|for]] or [[#Loops|while loop]].</td>
  <td><code></code></td>
</tr>
<tr>
  <td><b><var>continue</var></b></td>
  <td><code><nowiki>:continue </nowiki></code></td>
  <td>It continues with the next cycle of the nearest enclosing loop. continue may only occur syntactically nested in a [[#Loops|for]] or [[#Loops|while loop]].</td>
   <td><code></code></td>
   <td><code></code></td>
</tr>
</tr>
Line 704: Line 885:
</p>
</p>


<h4>Menu specific commands</h4>
====Menu specific commands====
<h5>Common commands</h5>
<h5>Common commands</h5>
<p>
<p>
Line 737: Line 918:
   <td><b><var>set</var></b></td>
   <td><b><var>set</var></b></td>
   <td><code><nowiki> set <id> <param>=<value>..<param>=<value></nowiki></code></td>
   <td><code><nowiki> set <id> <param>=<value>..<param>=<value></nowiki></code></td>
   <td>change selected items parameter, more than one parameter can be specified at the time</td>
   <td>change selected items parameter, more than one parameter can be specified at the time. Parameter can be unset by specifying '!' before parameter. <br />
Example: <br />
<code>/ip firewall filter
add chain=blah action=accept protocol=tcp port=123 nth=4,2 <br />
print <br />
set 0 !port chain=blah2 !nth protocol=udp
</code></td>
</tr>
</tr>
<tr>
<tr>
Line 762: Line 949:
   <td><b><var>find</var></b></td>
   <td><b><var>find</var></b></td>
   <td><code><nowiki> find <expression></nowiki></code></td>
   <td><code><nowiki> find <expression></nowiki></code></td>
   <td>find items by given expression.</td>
   <td>Returns list of internal numbers for items that are matched by given expression. For example: <code> :put [/interface find name~"ether"]</code></td>
</tr>
</tr>
</table>
</table>


</p>
</p>
<h5>import</h5>
=====import=====
Import command is available from root menu and is used to import configuration from files created by [[#Common_commands|export]] command or written manually by hand.
Import command is available from root menu and is used to import configuration from files created by [[#Common_commands|export]] command or written manually by hand.
<p>
<p>
Line 773: Line 960:
</p>
</p>


<h5>print parameters</h5>
=====print parameters=====
<p>
<p>


Several parameters are available for print command:
<table class="styled_table">
<tr>
  <th width="55">Parameter</th>
  <th width="400">Description</th>
  <th >Example</th>
</tr>
<tr>
  <td><b><var>append</var></b></td>
  <td></td>
  <td><code><nowiki></nowiki></code></td>
</tr>
<tr>
  <td><b><var>as-value</var></b></td>
  <td>print output as array of parameters and its values</td>
  <td><code><nowiki>:put [/ip address print as-value]</nowiki></code></td>
</tr>
<tr>
  <td><b><var>brief</var></b></td>
  <td>print brief description</td>
  <td><code><nowiki></nowiki></code></td>
</tr>
<tr>
  <td><b><var>detail</var></b></td>
  <td>print detailed description, output is not as readable as brief output, but may be useful to view all parameters</td>
  <td><code><nowiki></nowiki></code></td>
</tr>
<tr>
  <td><b><var>count-only</var></b></td>
  <td>print only count of menu items</td>
  <td><code><nowiki></nowiki></code></td>
</tr>
<tr>
  <td><b><var>file</var></b></td>
  <td>print output to file</td>
  <td><code><nowiki></nowiki></code></td>
</tr>
<tr>
  <td><b><var>follow</var></b></td>
  <td>print all current entries and track new entries until ctrl-c is pressed, very useful when viewing log entries </td>
  <td><code><nowiki>/log print follow</nowiki></code></td>
</tr>
<tr>
  <td><b><var>follow-only</var></b></td>
  <td>print and track only new entries until ctrl-c is pressed, very useful when viewing log entries</td>
  <td><code><nowiki>/log print follow-only</nowiki></code></td>
</tr>
<tr>
  <td><b><var>from</var></b></td>
  <td>print parameters only from specified item</td>
  <td><code><nowiki>/user print from=admin</nowiki></code></td>
</tr>
<tr>
  <td><b><var>interval</var></b></td>
  <td>continuously print output in selected time interval, useful to track down changes where <code>follow</code> is not acceptable</td>
  <td><code><nowiki>/interface print interval=2</nowiki></code></td>
</tr>
<tr>
  <td><b><var>terse</var></b></td>
  <td>show details in compact and machine friendly format</td>
  <td><code><nowiki></nowiki></code></td>
</tr>
<tr>
  <td><b><var>value-list</var></b></td>
  <td>show values one per line (good for parsing purposes)</td>
  <td><code><nowiki></nowiki></code></td>
</tr>
<tr>
  <td><b><var>without-paging</var></b></td>
  <td>If output do not fit in console screen then do not stop, print all information in one piece</td>
  <td><code><nowiki></nowiki></code></td>
</tr>
<tr>
  <td><b><var>where</var></b></td>
  <td>expressions followed by where parameter can be used to filter out matched entries</td>
  <td><code><nowiki>/ip route print where interface="ether1"</nowiki></code></td>
</tr>
</table>
<br />
More than one parameter can be specified at a time, for example, <code> /ip route print count-only interval=1 where interface="ether1" </code>
</p>
</p>


<h3>Loops and conditional statements</h3>
===Loops and conditional statements===
<p>
<p>
</p>
</p>
Line 831: Line 1,098:
</p>
</p>


<h3>Command syntax</h3>
 
===Functions===
 
Scripting language does not allow to create functions directly, however you could use :parse command as a workaround.
 
Starting from v6.2 new syntax is added to easier define such functions and even pass parameters.
It is also possible to return function value with ''':return''' command.
 
See examples below:
 
<pre>
#define function and run it
:global myFunc do={:put "hello from function"}
$myFunc
 
output:
hello from function
</pre>
 
<pre>
#pass arguments to the function
:global myFunc do={:put "arg a=$a"; :put "arg '1'=$1"}
$myFunc a="this is arg a value"  "this is arg1 value"
 
output:
arg a=this is arg a value
arg '1'=this is arg1 value
 
</pre>
 
Notice that there are two ways how to pass arguments:
* pass arg with specific name ("a" in our example)
* pass value without arg name, in such case arg "1", "2" ..  "n" are used.
 
 
'''Return example'''
<pre>
:global myFunc do={ :return ($a + $b)}
:put [$myFunc a=6 b=2]
 
output:
8
</pre>
 
 
 
You can even clone existing script from script environment and use it as function.
<pre>
#add script
/system script add name=myScript source=":put \"Hello $myVar !\""
</pre>
 
<pre>
:global myFunc [:parse [/system script get myScript source]]
$myFunc myVar=world
 
output:
Hello world !
</pre>
 
{{Warning | If function contains defined global variable which name matches the name of passed parameter, then  globally defined variable is ignored, for compatibility with scripts written for older versions. This feature can change in future versions. '''Avoid using parameters with same name as global variables.''' }}
 
For example:
<pre>
:global my2 "123"
 
:global myFunc do={ :global my2; :put $my2; :set my2 "lala"; :put $my2 }
$myFunc my2=1234
:put "global value $my2"
</pre>
 
Output will be:
<pre>
1234
lala
global value 123
</pre>
 
 
'''Nested function example'''
 
{{Note | to call another function its name needs to be declared (the same as for variables)}}
 
<pre>
:global funcA do={ :return 5 }
:global funcB do={
  :global funcA;
  :return ([$funcA] + 4)
}
:put [$funcB]
 
 
Output:
9
</pre>
 
===Catch run-time errors===
 
Starting from v6.2 scripting has ability to catch run-time errors.
 
For example, [code]:reslove[/code] command if failed will throw an error and break the script.
 
<pre>
[admin@MikroTik] > { :put [:resolve www.example.com]; :put "lala";}
failure: dns name does not exist
</pre>
 
Now we want to catch this error and proceed with our script:
<pre>
:do {
      :put [:resolve www.example.com];
} on-error={ :put "resolver failed"};
:put "lala"
 
output:
 
resolver failed
lala
</pre>
 
 
===Operations with Arrays===
 
{{Warning| Key name in array contains any character other than lowercase character, it should be put in quotes}}
 
For example:
<pre>
[admin@ce0] > {:local a { "aX"=1 ; ay=2 }; :put ($a->"aX")}
 
1
</pre>
 
 
'''Loop through keys and values'''
 
:foreach command can be used to loop through keys and elements:
 
<pre>
[admin@ce0] > :foreach k,v in={2; "aX"=1 ; y=2; 5} do={:put ("$k=$v")}
 
0=2
1=5
aX=1
y=2
 
</pre>
 
:if foreach command is used with one argument, then element value will be returned:
 
<pre>
[admin@ce0] > :foreach k in={2; "aX"=1 ; y=2; 5} do={:put ("$k")}
 
2
5
1
2
 
</pre>
 
{{Note | If array element has key then these elements are sorted in alphabetical order, elements without keys are moved before elements with keys and their order is not changed (see example above). }}
 
 
'''Change the value of single array element'''
 
<pre>
[admin@MikroTik] > :global a {x=1; y=2}
[admin@MikroTik] > :set ($a->"x") 5
[admin@MikroTik] > :environment print
a={x=5; y=2}
 
</pre>
 
==Script repository==
 
<p><b>Sub-menu level:</b> <code>/system script</code></p>
 
<p>Contains all user created scripts. Scripts can be executed in several different ways:</p>
<ul class="bullets">
<li><b>on event</b> - scripts are executed automatically on some facility events ([[M:System/Scheduler | scheduler]], [[M:Tools/Netwatch | netwatch]], [[M:Interface/VRRP | VRRP]])
<li><b>by another script</b> - running script within script is allowed
<li><b>manually</b> - from console executing [[#run|run]] command or in winbox
</ul>
 
{{Note | Only scripts (including schedulers, netwatch etc) with equal or higher permission rights can execute other scripts. }}
 
<br />
 
<table class="styled_table">
<tr>
  <th width="40%">Property</th>
  <th >Description</th>
</tr>
<tr>
    <td><var><b>comment</b></var> (<em>string</em>; Default: <i></i>)</td>
    <td> Descriptive comment for the script</td>
</tr>
<tr>
    <td><var><b>dont-require-permissions</b></var> (<em>yes | no</em>; Default: <i>no</i>)</td>
    <td> Bypass permissions check when script is being executed, useful when scripts are being executed from services that have limited permissions, such as [[ Manual:Tools/Netwatch | Netwatch]]</td>
</tr>
 
<tr>
    <td><var><b>name</b></var> (<em>string</em>; Default: <i>"Script[num]"</i>)</td>
    <td> name of the script</td>
</tr>
<tr>
    <td><var><b>policy</b></var> (<em>string</em>; Default: <i></i>)</td>
    <td> list of applicable policies:<br />
<ul class="bullets">
<li><b>api</b> - api permissions
<li><b>ftp</b> - can log on remotely via ftp and send and retrieve files from the router
<li><b>local</b> - can log on locally via console
<li><b>password</b> - change passwords
<li><b>policy</b> - manage user policies, add and remove user
<li><b>read</b> - can retrieve the configuration
<li><b>reboot</b> - can reboot the router
<li><b>sensitive</b> - allows to change "hide sensitive" parameter
<li><b>sniff</b> - can run sniffer, torch etc
<li><b>ssh</b> - can log on remotely via secure shell
<li><b>telnet</b> - can log on remotely via telnet
<li><b>test</b> - can run ping, traceroute, bandwidth test
<li><b>web</b> - can log on remotely via http
<li><b>winbox</b> - winbox permissions
<li><b>write</b> - can change the configuration
</ul>
Read more detailed policy descriptions [[Manual:Router_AAA#Properties | here]]
</td>
</tr>
<tr>
    <td><var><b>source</b></var> (<em>string</em>;)</td>
    <td> Script source code</td>
</tr>
</table>
 
<br />
Read only status properties:
<table class="styled_table">
<tr>
  <th width="40%">Property</th>
  <th >Description</th>
</tr>
<tr>
    <td><var><b>last-started</b></var> (<em>date</em>)</td>
    <td> Date and time when the script was last invoked.</td>
</tr>
<tr>
    <td><var><b>owner</b></var> (<em>string</em>)</td>
    <td> User who created the script</td>
</tr>
<tr>
    <td><var><b>run-count</b></var> (<em>integer</em>)</td>
    <td> Counter that counts how many times script has been executed</td>
</tr>
</table>
 
<br />
Menu specific commands
<table class="styled_table">
<tr>
  <th width="40%">Command</th>
  <th >Description</th>
</tr>
<tr>
    <td><var><b>run</b></var> (<em>run [id|name]</em>)</td>
    <td> Execute specified script by ID or name</td>
</tr>
</table>
 
 
===Environment===
 
<p><b>Sub-menu level:</b></p>
<ul>
<li><code>/system script environment</code></li>
<li><code>/environment</code></li>
</ul>
 
<p>Contains all user defined variables and their assigned values.</p>
 
[admin@MikroTik] > :global example;
[admin@MikroTik] > :set example 123
[admin@MikroTik] > /environment print 
"example"=123
 
<br />
Read only status properties:
 
<table class="styled_table">
<tr>
  <th width="40%">Property</th>
  <th >Description</th>
</tr>
<tr>
    <td><var><b>name</b></var> (<em>string</em>)</td>
    <td> Variable name</td>
</tr>
<tr>
    <td><var><b>user</b></var> (<em>string</em>)</td>
    <td> User who defined variable</td>
</tr>
<tr>
    <td><var><b>value</b></var> (<em></em>)</td>
    <td> Value assigned to variable</td>
</tr>
</table>
 
===Job===
 
<p><b>Sub-menu level:</b> <code>/system script job</code></p>
 
<p>
<p>
something will be written here, maybe
Contains list of all currently running scripts.
 
<br />
Read only status properties:
<table class="styled_table">
<tr>
  <th width="40%">Property</th>
  <th >Description</th>
</tr>
<tr>
    <td><var><b>owner</b></var> (<em>string</em>)</td>
    <td> User who is running script</td>
</tr>
<tr>
    <td><var><b>policy</b></var> (<em>array</em>)</td>
    <td> List of all policies applied to script</td>
</tr>
<tr>
    <td><var><b>started</b></var> (<em>date</em>)</td>
    <td> Local date and time when script was started</td>
</tr>
</table>
 
</p>
</p>
</div>


== See also ==
* [[M:Scripting-examples | Scripting Examples]]
* User submitted [[Scripts]]
{{Cont}}


[[Category:Manual]]
[[Category:Manual|S]]
[[Category:Unfinished]]
[[Category:System|S]]
[[Category:Console|S]]
[[Category:Case Studies|S]]

Revision as of 08:47, 4 July 2019

Version.png

Applies to RouterOS: any

Scripting language manual

This manual provides introduction to RouterOS built-in powerful scripting language.

Scripting host provides a way to automate some router maintenance tasks by means of executing user-defined scripts bounded to some event occurrence.

Scripts can be stored in Script repository or can be written directly to console. The events used to trigger script execution include, but are not limited to the System Scheduler, the Traffic Monitoring Tool, and the Netwatch Tool generated events.


Line structure

RouterOS script is divided into number of command lines. Command lines are executed one by one until the end of script or until runtime error occur.


Command line

RouterOS console uses following command syntax:

[prefix] [path] command [uparam] [param=[value]] .. [param=[value]]

  • [prefix] - ":" or "/" character which indicates if command is ICE or path. May or may not be required.
  • [path] - relative path to the desired menu level. May or may not be required.
  • command - one of the commands available at the specified menu level.
  • [uparam] - unnamed parameter, must be specified if command requires it.
  • [params] - sequence of named parameters followed by respective values

The end of command line is represented by the token “;” or NEWLINE. Sometimes “;” or NEWLINE is not required to end the command line.

Single command inside (), [] or {} does not require any end of command character. End of command is determined by content of whole script

:if ( true ) do={ :put "lala" }

Each command line inside another command line starts and ends with square brackets "[ ]" (command concatenation).

:put [/ip route get [find gateway=1.1.1.1]];  

Notice that code above contains three command lines:

  • :put
  • /ip route get
  • find gateway=1.1.1.1

Command line can be constructed from more than one physical line by following line joining rules.


Physical Line

A physical line is a sequence of characters terminated by an end-of-line (EOL) sequence. Any of the standard platform line termination sequences can be used:

  • unix – ASCII LF;
  • windows – ASCII CR LF;
  • mac – ASCII CR;

Standard C conventions for new line characters can be used ( the \n character).

Comments

A comment starts with a hash character (#) and ends at the end of the physical line. Whitespace or any other symbols are not allowed before hash symbol. Comments are ignored by syntax. If (#) character appear inside string it is not considered a comment.

Example
# this is a comment
 # bad comment
:global a; # bad comment

:global myStr "lala # this is not a comment"


Line joining

Two or more physical lines may be joined into logical lines using backslash character (\). A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals. A backslash is illegal elsewhere on a line outside a string literal.

Example
:if ($a = true \
      and $b=false) do={ :put “$a $b”; }

:if ($a = true \      # bad comment
      and $b=false) do={ :put “$a $b”; }

# comment \
    continued – invalid  (syntax error)


Whitespace between tokens

Whitespace can be used to separate tokens. Whitespace is necessary between two tokens only if their concatenation could be interpreted as a different token. Example:

{ 
   :local a true; :local b false;	
# whitespace is not required	
   :put (a&&b); 
# whitespace is required
   :put (a and b); 	
}

Whitespace are not allowed

  • between '<parameter>='
  • between 'from=' 'to=' 'step=' 'in=' 'do=' 'else='

Example:

#incorrect:
:for i from = 1 to = 2 do = { :put $i }
#correct syntax:
:for i from=1 to=2 do={ :put $i }
:for i from= 1 to= 2 do={ :put $i }	

#incorrect
/ip route add gateway = 3.3.3.3
#correct
/ip route add gateway=3.3.3.3

Scopes

Variables can be used only in certain regions of the script. These regions are called scopes. Scope determines visibility of the variable. There are two types of scopes - global and local. A variable declared within a block is accessible only within that block and blocks enclosed by it, and only after the point of declaration.

Global scope

Global scope or root scope is default scope of the script. It is created automatically and can not be turned off.


Local scope

User can define its own groups to block access to certain variables, these scopes are called local scopes. Each local scope is enclosed in curly braces ("{ }").

{
   :local a 3;
   {
      :local b 4;
      :put ($a+$b);
   }
#line below will show variable b in light red color since it is not defined in scope
   :put ($a+$b);
}

In code above variable b has local scope and will not be accessible after closed curly brace.

Icon-note.png

Note: Each line written in terminal is treated as local scope


So for example, defined local variable will not be visible in next command line and will generate syntax error

[admin@MikroTik] > :local myVar a;
[admin@MikroTik] > :put $myVar
syntax error (line 1 column 7)
Icon-warn.png

Warning: Do not define global variables inside local scopes.


Note that even variable can be defined as global, it will be available only from its scope unless it is not already defined.

{
   :local a 3;
   {
       :global b 4;
   }
   :put ($a+$b);
}

Code above will generate an error.

Keywords

The following words are keywords and cannot be used as variable and function names:

and       or       in

Delimiters

The following tokens serve as delimiters in the grammar:

()  []  {}  :   ;   $   / 


Data types

RouterOS scripting language has following data types:

Type Description
num (number) - 64bit signed integer, possible hexadecimal input;
bool (boolean) - values can bee true or false;
str (string) - character sequence;
ip - IP address;
ip-prefix - IP prefix;
ip6-prefix - IPv6 prefix
id (internal ID) - hexadecimal value prefixed by '*' sign. Each menu item has assigned unique number - internal ID;
time - date and time value;
array - sequence of values organized in an array;
nil - default variable type if no value is assigned;

Constant Escape Sequences

Following escape sequences can be used to define certain special character within string:

\" Insert double quote
\\ Insert backslash
\n Insert newline
\r Insert carriage return
\t Insert horizontal tab
\$ Output $ character. Otherwise $ is used to link variable.
\? Output ? character. Otherwise ? is used to print "help" in console.
\_ - space
\a - BEL (0x07)
\b - backspace (0x08)
\f - form feed (0xFF)
\v Insert vertical tab
\xx Print character from hex value. Hex number should use capital letters.
Example
:put "\48\45\4C\4C\4F\r\nThis\r\nis\r\na\r\ntest";

which will show on display
HELLO
This
is
a
test

Operators

Arithmetic Operators

Usual arithmetic operators are supported in RouterOS scripting language

Operator Description Example
"+" binary addition :put (3+4);
"-" binary subtraction :put (1-6);
"*" binary multiplication :put (4*5);
"/" binary division :put (10 / 2); :put ((10)/2)
"%" modulo operation :put (5 % 3);
"-" unary negation { :local a 1; :put (-a); }

Icon-note.png

Note: for division to work you have to use braces or spaces around dividend so it is not mistaken as IP address


Relational Operators

Operator Description Example
"<" less :put (3<4);
">" greater :put (3>4);
"=" equal :put (2=2);
"<=" less or equal
">=" greater or equal
"!=" not equal

Logical Operators

Operator Description Example
“!” logical NOT :put (!true);
“&&” , “and” logical AND :put (true&&true)
“||” , “or” logical OR :put (true||false);
“in” :put (1.1.1.1/32 in 1.0.0.0/8);

Bitwise Operators

Bitwise operators are working on number and ip address data types.


Operator Description Example
“~” bit inversion :put (~0.0.0.0)
“|” bitwise OR. Performs logical OR operation on each pair of corresponding bits. In each pair the result is “1” if one of bits or both bits are “1”, otherwise the result is “0”. :put (192.168.88.0|0.0.0.255)
“^” bitwise XOR. The same as OR, but the result in each position is “1” if two bits are not equal, and “0” if bits are equal.
“&” bitwise AND. In each pair the result is “1” if first and second bit is “1”. Otherwise the result is “0”. :put (192.168.88.77&255.255.255.0)
“<<” left shift by given amount of bits :put (192.168.88.77<<8)
“>>” right shift by given amount of bits :put (192.168.88.77>>24)


Calculate subnet address from given IP and CIDR Netmask using "&" operator:

{
:local IP 192.168.88.77;
:local CIDRnetmask 255.255.255.0;
:put ($IP&$CIDRnetmask);
}

Get last 8 bits from given IP addresses:

:put (192.168.88.77&0.0.0.255);

Use "|" operator and inverted CIDR mask to calculate the broadcast address:

{
:local IP 192.168.88.77;
:local Network 192.168.88.0;
:local CIDRnetmask 255.255.255.0;
:local InvertedCIDR (~$CIDRnetmask);
:put ($Network|$InvertedCIDR)
}


Concatenation Operators

Operator Description Example
“.” concatenates two strings :put (“concatenate” . “ “ . “string”);
“,” concatenates two arrays or adds element to array :put ({1;2;3} , 5 );


It is possible to add variable values to strings without concatenation operator:

:global myVar "world";

:put ("Hello " . $myVar);
# next line does the same as above
:put "Hello $myVar";

By using $[] and $() in string it is possible to add expressions inside strings:

:local a 5;
:local b 6;
:put " 5x6 = $($a * $b)";

:put " We have $[ :len [/ip route find] ] routes";

Other Operators

Operator Description Example
“[]” command substitution. Can contain only single command line :put [ :len "my test string"; ];
“()” sub expression or grouping operator :put ( "value is " . (4+5));
“$” substitution operator :global a 5; :put $a;
“~” binary operator that matches value against POSIX extended regular expression Print all routes which gateway ends with 202
/ip route print where gateway~"^[0-9 \\.]*202\$"
“->” Get an array element by key
[admin@x86] >:global aaa {a=1;b=2}
[admin@x86] > :put ($aaa->"a")
1
[admin@x86] > :put ($aaa->"b")
2

Variables

Scripting language has two types of variables:

  • global - accessible from all scripts created by current user, defined by global keyword;
  • local - accessible only within the current scope, defined by local keyword.
Icon-note.png

Note: Starting from v6.2 there can be undefined variables. When variable is undefined parser will try to look for variables set, for example, by DHCP lease-script or Hotspot on-login


Icon-note.png

Note: Variable value size is limited to 4096bytes


Every variable, except for built in RouterOS variables, must be declared before usage by local or global keywords. Undefined variables will be marked as undefined and will result in compilation error. Example:

# following code will result in compilation error, because myVar is used without declaration
:set myVar "my value";
:put $myVar

Correct code:

:local myVar;
:set myVar "my value";
:put $myVar;

Exception is when using variables set, for example, by DHCP lease-script

/system script
add name=myLeaseScript policy=\
    ftp,reboot,read,write,policy,test,winbox,password,sniff,sensitive,api \
    source=":log info \$leaseActIP\r\
    \n:log info \$leaseActMAC\r\
    \n:log info \$leaseServerName\r\
    \n:log info \$leaseBound"

/ip dhcp-server set  myServer lease-script=myLeaseScript

Valid characters in variable names are letters and digits. If variable name contains any other character, then variable name should be put in double quotes. Example:

#valid variable name
:local myVar;  
#invalid variable name
:local my-var; 
#valid because double quoted
:global "my-var"; 

If variable is initially defined without value then variable data type is set to nil, otherwise data type is determined automatically by scripting engine. Sometimes conversion from one data type to another is required. It can be achieved using data conversion commands. Example:

#convert string to array
:local myStr "1,2,3,4,5";
:put [:typeof $myStr];
:local myArr [:toarray $myStr];
:put [:typeof $myArr]

Variable names are case sensitive.

:local myVar "hello"
# following line will generate error, because variable myVAr is not defined
:put $myVAr
# correct code
:put $myVar

Set command without value will un-define the variable (remove from environment, new in v6.2)

#remove variable from environment
:global myVar "myValue"
:set myVar;

Reserved variable names

All built in RouterOS properties are reserved variables. Variables which will be defined the same as the RouterOS built in properties can cause errors. To avoid such errors, use custom designations.

For example, following script will not work:

{
:local type "ether1";
/interface print where name=$type;
} 

But will work with different defined variable:

{
:local customname "ether1";
/interface print where name=$customname;
} 

Commands

Global commands

Every global command should start with ":" token, otherwise it will be treated as variable.

Command Syntax Description Example
/ go to root menu
.. go back by one menu level
? list all available menu commands and brief descriptions
global :global <var> [<value>] define global variable :global myVar "something"; :put $myVar;
local :local <var> [<value>] define local variable { :local myLocalVar "I am local"; :put $myVar; }
beep :beep <freq> <length> beep built in speaker
delay :delay <time> do nothing for a given period of time
put :put <expression> put supplied argument to console
len :len <expression> return string length or array element count :put [:len "length=8"];
typeof :typeof <var> return data type of variable :put [:typeof 4];
pick :pick <var> <start>[<end>] return range of elements or substring. If end position is not specified, will return only one element from an array. :put [:pick "abcde" 1 3]
log :log <topic> <message> write message to system log. Available topics are "debug, error, info and warning" :log info "Hello from script";
time :time <expression> return interval of time needed to execute command :put [:time {:for i from=1 to=10 do={ :delay 100ms }}];
set :set <var> [<value>] assign value to declared variable. :global a; :set a true;
find :find <arg> <arg> <start> return position of substring or array element :put [:find "abc" "a" -1];
environment :environment print <start> print initialized variable information :global myVar true; :environment print;
terminal terminal related commands
error :error <output> Generate console error and stop executing the script
execute :execute <expression> Execute the script in background.
{
:local j [:execute {/interface print follow where [:log info ~Sname~]}];
:delay 10s;
:do { /system script job remove $j } on-error={}
}
parse :parse <expression> parse string and return parsed console commands. Can be used as function. :global myFunc [:parse ":put hello!"];
$myFunc;
resolve :resolve <arg> return IP address of given DNS name :put [:resolve "www.mikrotik.com"];
toarray :toarray <var> convert variable to array
tobool :tobool <var> convert variable to boolean
toid :toid <var> convert variable to internal ID
toip :toip <var> convert variable to IP address
toip6 :toip6 <var> convert variable to IPv6 address
tonum :tonum <var> convert variable to integer
tostr :tostr <var> convert variable to string
totime :totime <var> convert variable to time

Menu specific commands

Common commands

Following commands available from most sub-menus:

Command Syntax Description
add add <param>=<value>..<param>=<value> add new item
remove remove <id> remove selected item
enable enable <id> enable selected item
disable disable <id> disable selected item
set set <id> <param>=<value>..<param>=<value> change selected items parameter, more than one parameter can be specified at the time. Parameter can be unset by specifying '!' before parameter.

Example:
/ip firewall filter add chain=blah action=accept protocol=tcp port=123 nth=4,2
print
set 0 !port chain=blah2 !nth protocol=udp

get get <id> <param>=<value> get selected items parameter value
print print <param><param>=[<value>] print menu items. Output depends on print parameters specified. Most common print parameters are described here
export export [file=<value>] export configuration from current menu and its sub-menus (if present). If file parameter is specified output will be written to file with extension '.rsc', otherwise output will be printed to console. Exported commands can be imported by import command
edit edit <id> <param> edit selected items property in built-in text editor
find find <expression> Returns list of internal numbers for items that are matched by given expression. For example: :put [/interface find name~"ether"]

import

Import command is available from root menu and is used to import configuration from files created by export command or written manually by hand.

print parameters

Several parameters are available for print command:

Parameter Description Example
append
as-value print output as array of parameters and its values :put [/ip address print as-value]
brief print brief description
detail print detailed description, output is not as readable as brief output, but may be useful to view all parameters
count-only print only count of menu items
file print output to file
follow print all current entries and track new entries until ctrl-c is pressed, very useful when viewing log entries /log print follow
follow-only print and track only new entries until ctrl-c is pressed, very useful when viewing log entries /log print follow-only
from print parameters only from specified item /user print from=admin
interval continuously print output in selected time interval, useful to track down changes where follow is not acceptable /interface print interval=2
terse show details in compact and machine friendly format
value-list show values one per line (good for parsing purposes)
without-paging If output do not fit in console screen then do not stop, print all information in one piece
where expressions followed by where parameter can be used to filter out matched entries /ip route print where interface="ether1"


More than one parameter can be specified at a time, for example, /ip route print count-only interval=1 where interface="ether1"

Loops and conditional statements

Loops

Command Syntax Description
do..while :do { <commands> } while=( <conditions> ); :while ( <conditions> ) do={ <commands> }; execute commands until given condition is met.
for :for <var> from=<int> to=<int> step=<int> do={ <commands> } execute commands over a given number of iterations
foreach :foreach <var> in=<array> do={ <commands> }; execute commands for each elements in list

Conditional statement

Command Syntax Description
if :if(<condition>) do={<commands>} else={<commands>} <expression> If a given condition is true then execute commands in the do block, otherwise execute commands in the else block if specified.

Example:

{
   :local myBool true;
   :if ($myBool = false) do={ :put "value is false" } else={ :put "value is true" }
}


Functions

Scripting language does not allow to create functions directly, however you could use :parse command as a workaround.

Starting from v6.2 new syntax is added to easier define such functions and even pass parameters. It is also possible to return function value with :return command.

See examples below:

#define function and run it
:global myFunc do={:put "hello from function"}
$myFunc

output:
hello from function
#pass arguments to the function
:global myFunc do={:put "arg a=$a"; :put "arg '1'=$1"} 
$myFunc a="this is arg a value"  "this is arg1 value"

output:
arg a=this is arg a value
arg '1'=this is arg1 value

Notice that there are two ways how to pass arguments:

  • pass arg with specific name ("a" in our example)
  • pass value without arg name, in such case arg "1", "2" .. "n" are used.


Return example

:global myFunc do={ :return ($a + $b)}
:put [$myFunc a=6 b=2]

output:
8


You can even clone existing script from script environment and use it as function.

#add script
 /system script add name=myScript source=":put \"Hello $myVar !\""
:global myFunc [:parse [/system script get myScript source]]
$myFunc myVar=world

output:
Hello world !
Icon-warn.png

Warning: If function contains defined global variable which name matches the name of passed parameter, then globally defined variable is ignored, for compatibility with scripts written for older versions. This feature can change in future versions. Avoid using parameters with same name as global variables.


For example:

:global my2 "123"

:global myFunc do={ :global my2; :put $my2; :set my2 "lala"; :put $my2 }
$myFunc my2=1234
:put "global value $my2"

Output will be:

1234
lala
global value 123


Nested function example

Icon-note.png

Note: to call another function its name needs to be declared (the same as for variables)


:global funcA do={ :return 5 }
:global funcB do={ 
  :global funcA;
  :return ([$funcA] + 4)
}
:put [$funcB]


Output:
9 

Catch run-time errors

Starting from v6.2 scripting has ability to catch run-time errors.

For example, [code]:reslove[/code] command if failed will throw an error and break the script.

[admin@MikroTik] > { :put [:resolve www.example.com]; :put "lala";}
failure: dns name does not exist

Now we want to catch this error and proceed with our script:

:do {
      :put [:resolve www.example.com];
} on-error={ :put "resolver failed"};
:put "lala" 

output:

resolver failed
lala


Operations with Arrays

Icon-warn.png

Warning: Key name in array contains any character other than lowercase character, it should be put in quotes


For example:

[admin@ce0] > {:local a { "aX"=1 ; ay=2 }; :put ($a->"aX")}

1


Loop through keys and values

foreach command can be used to loop through keys and elements:
[admin@ce0] > :foreach k,v in={2; "aX"=1 ; y=2; 5} do={:put ("$k=$v")}

0=2
1=5
aX=1
y=2

if foreach command is used with one argument, then element value will be returned:
[admin@ce0] > :foreach k in={2; "aX"=1 ; y=2; 5} do={:put ("$k")}

2
5
1
2

Icon-note.png

Note: If array element has key then these elements are sorted in alphabetical order, elements without keys are moved before elements with keys and their order is not changed (see example above).



Change the value of single array element

[admin@MikroTik] > :global a {x=1; y=2}
[admin@MikroTik] > :set ($a->"x") 5 
[admin@MikroTik] > :environment print 
a={x=5; y=2}

Script repository

Sub-menu level: /system script

Contains all user created scripts. Scripts can be executed in several different ways:

  • on event - scripts are executed automatically on some facility events ( scheduler, netwatch, VRRP)
  • by another script - running script within script is allowed
  • manually - from console executing run command or in winbox
Icon-note.png

Note: Only scripts (including schedulers, netwatch etc) with equal or higher permission rights can execute other scripts.



Property Description
comment (string; Default: ) Descriptive comment for the script
dont-require-permissions (yes | no; Default: no) Bypass permissions check when script is being executed, useful when scripts are being executed from services that have limited permissions, such as Netwatch
name (string; Default: "Script[num]") name of the script
policy (string; Default: ) list of applicable policies:
  • api - api permissions
  • ftp - can log on remotely via ftp and send and retrieve files from the router
  • local - can log on locally via console
  • password - change passwords
  • policy - manage user policies, add and remove user
  • read - can retrieve the configuration
  • reboot - can reboot the router
  • sensitive - allows to change "hide sensitive" parameter
  • sniff - can run sniffer, torch etc
  • ssh - can log on remotely via secure shell
  • telnet - can log on remotely via telnet
  • test - can run ping, traceroute, bandwidth test
  • web - can log on remotely via http
  • winbox - winbox permissions
  • write - can change the configuration

Read more detailed policy descriptions here

source (string;) Script source code


Read only status properties:

Property Description
last-started (date) Date and time when the script was last invoked.
owner (string) User who created the script
run-count (integer) Counter that counts how many times script has been executed


Menu specific commands

Command Description
run (run [id|name]) Execute specified script by ID or name


Environment

Sub-menu level:

  • /system script environment
  • /environment

Contains all user defined variables and their assigned values.

[admin@MikroTik] > :global example;
[admin@MikroTik] > :set example 123
[admin@MikroTik] > /environment print  
"example"=123


Read only status properties:

Property Description
name (string) Variable name
user (string) User who defined variable
value () Value assigned to variable

Job

Sub-menu level: /system script job

Contains list of all currently running scripts.
Read only status properties:

Property Description
owner (string) User who is running script
policy (array) List of all policies applied to script
started (date) Local date and time when script was started

See also


[ Top | Back to Content ]