Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.


Panel
bordertrue
borderColorgrey
borderStylesolid


Expand
titleTable of Contents
Table of Contents



Scripting language manual

...

Scripts can be stored in the Script repository or can be written directly to the 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.

Line structure

The 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

The RouterOS console uses the following command syntax:

...

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

...

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

...

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

Code Block
languageros
: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:

...

  • A comment starts with a hash character (#) and ends at the end of the physical line.
  • RouterOS does not support multiline comments.
  • If (a #) character appears inside the string it is not considered a comment.

...

The following rules apply to use using backslash as a line-joining tool:

  • 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.

...

Code Block
languageros
:if ($a = true \
	and $b=false) do={ :put “$a"$a $b”$b"; } 
:if ($a = true \ # bad comment 
	and $b=false) do={ :put “$a"$a $b”$b"; }
# comment \
	continued - invalid (syntax error)

Whitespace between tokens

...

Note that even variable can be defined as global, it will be available only from its scope unless it is not already definedreferenced to be visible outside of the scope.

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

The code above will generate an expected result because the accessibility of variable "b" and its value will end after the end of the scope.

Keywords

output 3, because outside of the scope b is not visible. 

The following code will fix the problem and will output 7:

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


Keywords

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

...

TypeDescription
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 an assigned a 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;

...

:put "\48\45\4C\4C\4F\r\nThis\r\nis\r\na\r\ntest";

which will show on the display
HELLO
This
is
a
test

Operators

...

Usual arithmetic operators are supported in the RouterOS scripting language

...

Bitwise operators are working on number, IP, and IPv6 address data types.

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

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

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

...

OperatorDescriptionExample
"."concatenates two strings:put (“concatenate” . “ “ . “string”"concatenate" . " " . "string");
","concatenates two arrays or adds an element to the array:put ({1;2;3} , 5 );

...

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

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

Other Operators

...


OperatorDescriptionExample
“[]”command substitution. Can contain only a single command line:put [ :len "my test string"; ];
“()”subexpression or grouping operator:put ( "value is " . (4+5));
“$”substitution operator:global a 5; :put $a;
“~”the binary operator that matches value against POSIX extended regular expressionPrint all routes which whose 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

...

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

Note: Starting from v6.2 there There can be undefined variables. When a variable is undefined, the parser will try to look for variables set, for example, by DHCP lease-script or Hotspot on-loginNote: 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 a compilation error. Example:

...

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

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

...

Code Block
languageros
:local “my"my-Var”Var";
:set “my"my-Var”Var" "my value";
:put $”my-Var”$"my-Var";

Reserved variable names

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

...

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

CommandSyntaxDescriptionExample
/
go to the root menu
..
go back by one menu level
?
list all available menu commands and brief descriptions
global:global <var> [<value>]define a global variable:global myVar "something"; :put $myVar;
local:local <var> [<value>]define the local variable{ :local myLocalVar "I am local"; :put $myVar; }
beep:beep <freq> <length>beep built-in speaker
delay

convert:
delay <time>do nothing for a given period of timeput:put <expression>put supplied argument to console
convert from=[arg] to=[arg]

Converts specified value from one format to another. By default uses an automatically parsed value, if the "from" format is not specified (for example, "001" becomes "1", "10.1" becomes "10.0.0.1", etc.).

from specifies the format of the value - base32, base64, hex, raw, rot13, url.

to specifies the format of the output value - base32, base64, hex, raw, rot13, url.

:put [:convert 001 to=hex ]

31

:put [:convert [/ip dhcp-client/option/get hostname raw-value] from=hex to=raw ]

MikroTik

delay:delay <time>do nothing for a given period of time
environment:environment print <start>print initialized variable information:global myVar true; :environment print;
error:error <output>Generate console error and stop executing the script
execute:execute <expression>

Execute the script in the background. The result can be written in the file by setting a "file"parameter or printed to the CLI by setting "as-string".

When using the "as-string" parameter executed script is blocked (not executed in the background).

Executed script can not be larger than 64kB


Code Block
languageros
{
:local j [:execute {/interface print follow where [:log info ~Sname~]}];
:delay 10s;
:do { /system script job remove $j } on-error={}
}


find:find <arg> <arg> <start>return position of a substring or array element:put [:find "abc" "a" -1];
jobname
:jobnamereturn current script name
Code Block
languageros
titleLimit script execution to single instance
:if ([/system script job print count-only as-value where script=[:jobname] ] > 1) do={
  :error "script instance already running"
  }


len:len <expression>return string length or array element count:put [:len "length=8"]
;typeof:typeof <var>the return data type of variable
;
log:log <topic> <message>write a message to the system log. Available topics are "debug, error, info and warning":log info "Hello from script";
parse:parse <expression>parse the string and return parsed console commands. Can be used as a function.:global myFunc [:parse ":put hello!"];
$myFunc
:put [:typeof 4]
;
pick:pick <var> <start>[
<end>
<count>]

return range of elements or substring. If the

end position

count is not specified, will return only one element from an array.

  • var - value to pick elements from
  • start - element to start picking from (the first element index is 0)
  • count - number of elements to pick starting from the first element with index=0


Code Block
languageros
[admin@MikroTik] > :put [:pick
"abcde" 1 3]log:log <topic> <message>write a message to the 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 the command:put [:time {:for i from=1 to=10 do={ :delay 100ms }}];set:set <var> [<value>]assign value to a declared variable.:global a; :set a true;find:find <arg> <arg> <start>return position of a substring or array element:put [:find "abc" "a" -1];environment:environment print <start>print initialized variable information:global myVar true; :environment print;terminalterminal related commandserror:error <output>Generate console error and stop executing the scriptexecute:execute <expression>Execute the script in the background. The result can be written in the file by settingfile parameter.
{
:local j [:execute {/interface print follow where [:log info ~Sname~]}];
:delay 10s;
:do { /system script job remove $j } on-error={}
}
parse:parse <expression>parse the string and return parsed console commands. Can be used as a function.:global myFunc [:parse ":put hello!"];
$myFunc;
resolve:resolve <arg>return the IP address of the given DNS name:put [:resolve "www.mikrotik.com"];rndnum:rndnum from=[num] to=[num]random number generator:put [:rndnum from=1 to=99];rndstr:rndstr from=[str] length=[num]random string generator
 "abcde" 1 3]
bc


put:put <expression>put the supplied argument into the console:put "Hello world"
resolve:resolve <arg>return the IP address of the given DNS name:put [:resolve "www.mikrotik.com"];
retry:retry command=<expr> delay=[num] max=[num] on-error=<expr>Try to execute the given command "max" amount of times with a given "delay" between tries. On failure, execute the expression given in the "on-error" block

:retry command={abc} delay=1 max=2 on-error={:put "got error"}
got error

Code Block
languagetext
:retry command={abc} delay=1 max=2 on-error={:put "got error"}
got error


typeof:typeof <var>the return data type of variable:put [:typeof 4];
rndnum:rndnum from=[num] to=[num]random number generator:put [:rndnum from=1 to=99];
rndstr:rndstr from=[str] length=[num]

Random string generator.

from specifies characters to construct the string from and defaults to all ASCII letters and numerals.
length specifies the length of the string to create and defaults to 16.

:put [:rndnum from="abcdef%^&" length=33];



set:set <var> [<value>]assign value to a declared variable.:global a; :set a true;
terminal:terminal terminal related commands
time:time <expression>return interval of time needed to execute the command:put [:time {:for i from=1 to=10 do={ :delay 100ms }}];
timestamp:timestampreturns the time since epoch, where epoch is January 1, 1970 (Thursday), not counting leap seconds


Code Block
languagetext
[admin@MikroTik] > :put [:timestamp]
2735w21:41:43.481891543
or
[admin@MikroTik] > :put [:timestamp]
2735w1d21:41:43.481891543
with the day offset
:put [:rndnum from="abcdef%^&" length=33];


toarray:toarray <var>convert a variable to the array
tobool:tobool <var>convert a variable to boolean
toid:toid <var>convert a variable to internal ID
toip:toip <var>convert a variable to IP address
toip6:toip6 <var>convert a variable to IPv6 address
tonum:tonum <var>convert a variable to an integer
tostr:tostr <var>convert a variable to a string
totime:totime <var>convert a variable to time

Menu specific commands

Common commands

Following The following commands are available from most sub-menus:

CommandSyntaxDescription
addadd <param>=<value>..<param>=<value>add new item
removeremove <id>remove selected item
enableenable <id>enable selected item
disabledisable <id>disable selected item
setset <id> <param>=<value>..<param>=<value>change selected items parameter, more than one parameter can be specified at the time. The parameter can be unset by specifying '!' before the 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

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

...

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

...

ParameterDescriptionExample
append

as-valueprint output as an array of parameters and its values:put [/ip address print as-value]
briefprint brief description
detailprint detailed description, the output is not as readable as brief output but may be useful to view all parameters
count-onlyprint only count of menu items
fileprint output to a file
followprint all current entries and track new entries until ctrl-c is pressed, very useful when viewing log entries/log print follow
follow-onlyprint and track only new entries until ctrl-c is pressed, very useful when viewing log entries/log print follow-only
fromprint parameters only from specified item/user print from=admin
intervalcontinuously print output in a selected time interval, useful to track down changes where follow is not acceptable/interface print interval=2
terseshow details in a compact and machine-friendly format
value-listshow values one single per line (good for parsing purposes)
without-pagingIf the output does not fit in the console screen then do not stop, print all information in one piece
whereexpressions followed by where parameters can be used to filter outmatched entries/ip route print where interface="ether1"

...

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

...

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

...

  • on event - scripts are executed automatically on some facility events ( scheduler, netwatch, VRRP)
  • by another script - running script within the script is allowed
  • manually - from console executingrun command or in winbox

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

PropertyDescription
comment (string; Default: )Descriptive comment for the script
dont-require-permissions (yes | no; Default: no)Bypass permissions check when the 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: ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon)list of applicable policies:
  • ftp - can log on remotely via FTP and send and retrieve files from the router
  • password - change passwords
  • policy - manage user policies, add and remove user
  • read - can retrieve the configuration
  • reboot - can reboot the router
  • sensitive - allows changing "hide sensitive" parameter
  • sniff - can run sniffer, torch, etc
  • test - can run ping, traceroute, bandwidth test
  • write - can change the configuration

Read more detailed policy descriptions here

source (string;)Script source code

Read-only status properties:

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

Menu specific commands

...

PropertyDescription
owner (string)The user who is running the script
policy (array)List of all policies applied to the script
started (date)Local date and time when the script was started

See also

...