Manual - Scripting - MikroTik Wiki
Manual - Scripting - MikroTik Wiki
Contents
Applies to
Scripting language manual RouterOS:
Line structure any
Command line
Physical Line
Comments
Example
Line joining
Example
Whitespace between tokens
Scopes
Global scope
Local scope
Keywords
Delimiters
Data types
Constant Escape Sequences
Example
Operators
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Concatenation Operators
Other Operators
Variables
Reserved variable names
Commands
Global commands
Menu specific commands
Common commands
import
print parameters
Loops and conditional statements
Loops
Conditional statement
Functions
Catch run-time errors
Operations with Arrays
Script repository
Environment
Job
See also
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.
If you are already familiar with scripting in RouterOS, you might want to see our Tips & Tricks (https://wiki.mi
krotik.com/wiki/Manual:Scripting_Tips_and_Tricks).
Line structure
RouterOS script is divided into a number of command lines. Command lines are executed one by one until the
end of the script or until a runtime error occurs.
Command line
[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
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
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:
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
Line joining
Two or more physical lines may be joined into logical lines using the 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
# comment \
continued – invalid (syntax error)
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);
}
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 the default scope of the script. It is created automatically and can not be turned
off.
Local scope
User can define their 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.
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);
}
Keywords
The following words are keywords and cannot be used as variable and function names:
and or in
Delimiters
() [] {} : ; $ /
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 - IPv6 address
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;
Following escape sequences can be used to define certain special character within string:
Example
:put "\48\45\4C\4C\4F\r\nThis\r\nis\r\na\r\ntest";
Arithmetic Operators
Note: for division to work you have to use braces or spaces around dividend so it is not mistaken as
IP address
Relational Operators
Logical Operators
Bitwise operators are working on number, IP and IPv6 address data types.
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);
}
: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 :put ({1;2;3} , 5 );
element to array
By using $[] and $() in string it is possible to add expressions inside strings:
:local a 5;
:local b 6;
:put " 5x6 = $($a * $b)";
Other Operators
Operator Description Example
“[]” command substitution. Can contain only :put [ :len "my test string"; ];
single command line
“()” sub expression or grouping operator :put ( "value is " . (4+5));
“$” substitution operator :global a 5; :put $a;
“~” binary operator that matches value Print all routes which gateway ends with 202
against POSIX extended regular /ip route print where gateway~"^[0-9
expression \\.]*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
global - accessible from all scripts created by current user, defined by global keyword;
local - accessible only within the current scope, defined by local keyword.
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
# 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;
/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"
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:
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:
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;
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.
{
:local type "ether1";
/interface print where name=$type;
}
{
: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.
parse :parse <expression> parse string and return parsed :global myFunc [:parse
console commands. Can be used ":put hello!"];
as function. $myFunc;
resolve :resolve <arg> return IP address of given DNS :put [:resolve
name "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
Common commands
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
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
as-value print output as an 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 /log print follow
is pressed, very useful when viewing log entries
follow-only print and track only new entries until ctrl-c is pressed, /log print follow-only
very useful when viewing log entries
from print parameters only from specified item /user print from=admin
interval continuously print output in selected time interval, /interface print interval=2
useful to track down changes where follow is not
acceptable
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 /ip route print where
to filter out matched entries 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
Conditional statement
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.
output:
hello from function
output:
arg a=this is arg a value
arg '1'=this is arg1 value
Return example
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 !\""
output:
Hello world !
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 myFunc do={ :global my2; :put $my2; :set my2 "lala"; :put $my2 }
$myFunc my2=1234
:put "global value $my2"
1234
lala
global value 123
Note: to call another function its name needs to be declared (the same as for variables)
Output:
9
For example, [code]:reslove[/code] command if failed will throw an error and break the script.
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
For example:
0=2
1=5
aX=1
y=2
if foreach command is used with one argument, then element value will be returned:
2
5
1
2
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).
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
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; Bypass permissions check when script is being executed, useful
Default: no) 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:
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
Command Description
run (run [id|name]) Execute specified script by ID or name
Environment
Sub-menu level:
Property Description
name (string) Variable name
user (string) User who defined variable
value () Value assigned to variable
Job
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
Scripting Examples
User submitted Scripts
Manual:Scripting Tips and Tricks