Manual:Scripting: Difference between revisions

From MikroTik Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 3: Line 3:
<div class=manual>
<div class=manual>


<h2>Scripting language manual</h2>
==Scripting language manual==
<p>
<p>
This manual provides introduction to RouterOS built-in powerful scripting language.
This manual provides introduction to RouterOS built-in powerful scripting language.
Line 15: Line 15:
</p>
</p>


<h3>Line structure</h3>
===Line structure===
<p>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.</p>
<p>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.</p>


<h4>Command line</h4>
====Command line====
<p>
<p>
RouterOS console uses following command syntax:<br />
RouterOS console uses following command syntax:<br />
Line 49: Line 49:
</p>
</p>


<h4>Physical Line</h4>
====Physical Line====
<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:
<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 class="bullets">
<ul class="bullets">
Line 59: Line 59:
</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 72: 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 90: 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 126: Line 126:
</p>
</p>


<h4>Scopes</h4>
====Scopes====
<p>
<p>
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>.
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>.
Line 179: Line 179:
</p>
</p>


<h3>Keywords</h3>
===Keywords===
<p>
<p>


Line 195: 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 204: 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 248: Line 248:
</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 321: Line 321:
</p>
</p>


<h3>Operators</h3>
===Operators===
<p>
<p>
</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 363: Line 363:
</p>
</p>


<h4>Relational Operators</h4>
====Relational Operators====
<p>
<p>


Line 406: Line 406:
</p>
</p>


<h4>Logical Operators</h4>
====Logical Operators====
<p>
<p>
<table  class="styled_table">
<table  class="styled_table">
Line 437: Line 437:
</p>
</p>


<h4>Bitwise Operators</h4>
====Bitwise Operators====
<p>
<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]].
Line 480: Line 480:
</p>
</p>


<h4>Concatenation Operators</h4>
====Concatenation Operators====
<p>
<p>
<table  class="styled_table">
<table  class="styled_table">
Line 520: Line 520:
</p>
</p>


<h4>Other Operators</h4>
====Other Operators====
<p>
<p>


Line 538: Line 538:
   <td>sub expression or grouping 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 558: Line 553:
</p>
</p>


<h3>Variables</h3>
===Variables===
<p>
<p>
Scripting language has two types of variables:  
Scripting language has two types of variables:  
Line 608: Line 603:
</p>
</p>


<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.
<p>Every global command should start with <i>":"</i> token, otherwise it will be treated as variable.
Line 790: Line 785:
</p>
</p>


<h4>Menu specific commands</h4>
====Menu specific commands====
<h5>Common commands</h5>
<h5>Common commands</h5>
<p>
<p>
Line 853: Line 848:


</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 859: Line 854:
</p>
</p>


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


Line 944: Line 939:
</p>
</p>


<h3>Loops and conditional statements</h3>
===Loops and conditional statements===
<p>
<p>
</p>
</p>
Line 1,076: Line 1,071:
</p>
</p>


<h3>Environment</h3>
===Environment===


<p><b>Sub-menu level:</b> <code>/system script environment</code></p>
<p><b>Sub-menu level:</b> <code>/system script environment</code></p>
Line 1,105: Line 1,100:
</p>
</p>


<h3>Job</h3>
===Job===


<p><b>Sub-menu level:</b> <code>/system script job</code></p>
<p><b>Sub-menu level:</b> <code>/system script job</code></p>

Revision as of 08:22, 12 May 2010

Applies to RouterOS: v3, v4

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 generate error
   :put ($a+$b);
}

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

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)

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        not       in

Delimiters

The following tokens serve as delimiters in the grammar:

()  []  {}  :   ;   $   / 


Data types

RouterOS scripting language has following data types:

Type Description
number - 64bit signed integer, possible hexadecimal input;
boolean - values can bee true or false;
string - character sequence;
IP - IP address;
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:

\" - double quote
\\ - backslash
\n - newline
\r - carriage return
\t - horizontal tab
\$
\?
\_ - space
\a - BEL (0x07)
\b - backspace (0x08)
\f - form feed (0xFF)
\v - vertical tab
\xx - hex value
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

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

Relational Operators

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

Logical Operators

Opearator Description Example
“!” , “not” 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.

Opearator 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”.
“^” 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”.
“<<” left shift by given amount of bits
“>>” right shift by given amount of bits

Concatenation Operators

Opearator 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

Opearator 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"

Variables

Scripting language has two types of variables:

  • global - accessible from all current users scripts, defined by global keyword;
  • local - accessible only within the current scope, defined by local keyword.

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;

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

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. Ja set bez veertiibas tad typof ir 'nil' vajadzetu but nothing. :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
parse :parse <expression> parse string and return parsed console commands.
resolve :resolve <arg> return IP address of given DNS name :put [:resolve "www.google.lv"];
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
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> find items by given expression.

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" }
}

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


Property Description
name (string; Default: "Script[num]") name of the script
policy (string; Default: ) list of applicable policies:
  • ftp - user can log on remotely via ftp and send and retrieve files from the router
  • local - user can log on locally via console
  • policy - manage user policies, add and remove user
  • read - user can retrieve the configuration
  • reboot - user can reboot the router
  • ssh - user can log on remotely via secure shell
  • telnet - user can log on remotely via telnet
  • test - user can run ping, traceroute, bandwidth test
  • web - user can log on remotely via http
  • write - user can retrieve and change the configuration
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

Contains all user defined variables and their assigned values.
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 ]