Panel | ||||||
---|---|---|---|---|---|---|
| ||||||
|
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 | ||
---|---|---|
| ||
: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 | ||
---|---|---|
| ||
: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 | ||
---|---|---|
| ||
{ :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 | ||
---|---|---|
| ||
{
:local a 3;
{
:global b 4;
}
:global b;
:put ($a+$b);
} |
Keywords
The following words are The following words are keywords and cannot be used as variable and function names:
...
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 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 displayHELLO
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.
Operator | Description | Example |
---|---|---|
“~” | 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 | ||
---|---|---|
| ||
{ :local IP 192.168.88.77; :local CIDRnetmask 255.255.255.0; :put ($IP&$CIDRnetmask); } |
...
Operator | Description | Example |
---|---|---|
“".”" | 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 | ||
---|---|---|
| ||
: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 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 expression | Print 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-login
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 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 | ||
---|---|---|
| ||
#convert string to array :local myStr "1,2,3,4,5"; :put [:typeof $myStr]; :local myArr [:toarray $myStr]; :put [:typeof $myArr] |
...
Code Block | ||
---|---|---|
| ||
: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.
Command | Syntax | Description | Example |
---|---|---|---|
/ | 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 |
convert | : |
:put <expression>
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. |
| ||||||||
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 |
| |||||||
find | :find <arg> <arg> <start> | return position of a substring or array element | :put [:find "abc" "a" -1]; | |||||||
jobname | :jobname | return current script name |
| |||||||
len | :len <expression> | return string length or array element |
:put [:len "length=8"];
count | :put [:len "length=8"]; | ||
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!"]; |
:typeof <var>
; | ||
pick | :pick <var> <start>[<count>] | return range of elements or substring. If the count is not specified, will return only one element from an array.
|
|
|
|
put | : |
"debug, error, info and warning"
:log info "Hello from script";
:time <expression>
:put [:time {:for i from=1 to=10 do={ :delay 100ms }}];
Code Block | ||
---|---|---|
| ||
[admin@MikroTik] > :put [:timestamp]
2735w21:41:43.481891543 |
:set <var> [<value>]
:global a; :set a true;
:find <arg> <arg> <start>
:put [:find "abc" "a" -1];
:environment print <start>
:global myVar true; :environment print;
:error <output>
:execute <expression>
Code Block | ||
---|---|---|
| ||
{
:local j [:execute {/interface print follow where [:log info ~Sname~]}];
:delay 10s;
:do { /system script job remove $j } on-error={}
} |
:parse <expression>
:global myFunc [:parse ":put hello!"];
$myFunc;
:resolve <arg>
:put [:resolve "www.mikrotik.com"];
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"}
| |||||
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. |
| |||||
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 | :timestamp | returns the time since epoch, where epoch is January 1, 1970 (Thursday), not counting leap seconds |
|
|
|
:rndnum from=[num] to=[num]
:put [:rndnum from=1 to=99];
:rndstr from=[str] length=[num]
: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
...
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. The parameter can be unset by specifying '!' before the parameter. Example: |
get | get <id> <param>=<value> | get the selected items item's parameter value |
print <param><param>=[<value>] | print menu items. Output depends on the print parameters specified. The most common print parameters are described here | |
export | export [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 |
edit | edit <id> <param> | edit selected items property in the 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"] |
...
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.
...
Parameter | Description | Example |
---|---|---|
append | ||
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, the 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 a 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 a selected time interval, useful to track down changes where follow is not acceptable | /interface print interval=2 |
terse | show details in a compact and machine-friendly format | |
value-list | show values one single per line (good for parsing purposes) | |
without-paging | If the output does not fit in the console screen then do not stop, print all information in one piece | |
where | expressions 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 executing a 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; 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:
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) | The user who created the script |
run-count (integer) | Counter that counts how many times the script has been executed |
Menu specific commands
...
Property | Description |
---|---|
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
- Scripting ExamplesUser-submitted Scripts
- Manual: Scripting Tips and Tricks
...