Script Manual
Script Manual
Manual:Scripting
From MikroTik Wiki
Line structure
Lo script RouterOS è diviso in numero di righe di comando. Le righe di comando vengono eseguite una alla volta fino alla fine dello script
o fino a quando si verifica un errore di runtime.
Command line
[prefisso] - ":" o "/" carattere che indica se il comando è ICE o percorso. Può o non può essere richiesto.
[percorso] - percorso relativo al livello di menu desiderato. Può o non può essere richiesto.
comando - uno dei comandi disponibili al livello di menu specificato.
[uparam] - parametro senza nome, deve essere specificato se il comando lo richiede.
[parametri] - sequenza di parametri denominati seguita da rispettivi valori
La fine della riga di comando è rappresentata dal token ";" o NEWLINE. A volte ";" o NEWLINE non è richiesto
termina la riga di comando.
Il singolo comando inside (), [] o {} non richiede alcun carattere di fine comando. La fine del comando è determinata da
contenuto dell'intero script
Ogni riga di comando all'interno di un'altra riga di comando inizia e termina con parentesi quadre "[]" (concatenazione dei .comandi).
:put
/ip route get
find gateway=1.1.1.1
La riga di comando può essere costruita da più di una linea fisica seguendo le regole di unione delle linee.
1 di 17 10/02/18, 13:03
Manual:Scripting - MikroTik Wiki https://wiki.mikrotik.com/index.php?title=Manual:Scripting&printabl...
Physical Line
Linea fisica
Una linea fisica è una sequenza di caratteri terminata da una sequenza di fine riga (EOL). Qualsiasi della piattaforma standard
le sequenze di terminazione di linea possono essere utilizzate:
unix – ASCII LF;
windows – ASCII CR LF;
mac – ASCII CR;
È possibile utilizzare le convenzioni C standard per i caratteri di nuova riga (il carattere \ n).
Comments
Un commento inizia con un carattere cancelletto (#) e termina alla fine della linea fisica. Spazio bianco o altri simboli
non consentito prima del simbolo hash. I commenti sono ignorati dalla sintassi. Se il carattere (#) appare all'interno della stringa non viene considerato
un commento.
Example
# this is a comment
# bad comment
:global a; # bad comment
Line joining
Due o più linee fisiche possono essere unite in linee logiche usando il carattere barra rovesciata (\). Una riga che termina con una barra rovesciata
non può portare un commento Un backslash non continua un commento. Un backslash non continua un token tranne che
stringhe letterali. Un backslash è illegale altrove su una riga al di fuori di una stringa letterale.
Example
# comment \
continued – invalid (syntax error)
2 di 17 10/02/18, 13:03
Manual:Scripting - MikroTik Wiki https://wiki.mikrotik.com/index.php?title=Manual:Scripting&printabl...
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
Le variabili possono essere utilizzate solo in alcune regioni dello script. Queste regioni sono denominate ambiti. L'ambito determina la visibilità di
la variabile. Esistono due tipi di ambiti: globali e locali . Una variabile dichiarata all'interno di un blocco è accessibile solo
all'interno di quel blocco e blocchi racchiusi da esso, e solo dopo il punto di dichiarazione
Global scope
L'ambito globale o l'ambito di root è l'ambito predefinito dello script. Viene creato automaticamente e non può essere disattivato.
Ambito locale
Local scope
L'utente può definire i propri gruppi per bloccare l'accesso a determinate variabili, questi ambiti sono chiamati ambiti locali. Ogni ambito locale
è racchiuso tra parentesi graffe ("{}").
{
: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);
}
Nel codice sopra la variabile b ha scope locale e non sarà accessibile dopo parentesi graffa chiusa.
Note: ogni riga scritta nel terminale viene considerata come ambito locale
Ad esempio, la variabile locale definita non sarà visibile nella riga di comando successiva e genererà un errore di sintassi
Si noti che anche la variabile può essere definita globale, sarà disponibile solo dal suo ambito a meno che non sia già definita.
3 di 17 10/02/18, 13:03
Manual:Scripting - MikroTik Wiki https://wiki.mikrotik.com/index.php?title=Manual:Scripting&printabl...
{
: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 not 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-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:
4 di 17 10/02/18, 13:03
Manual:Scripting - MikroTik Wiki https://wiki.mikrotik.com/index.php?title=Manual:Scripting&printabl...
Example
:put "\48\45\4C\4C\4F\r\nThis\r\nis\r\na\r\ntest";
Operators
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
5 di 17 10/02/18, 13:03
Manual:Scripting - MikroTik Wiki https://wiki.mikrotik.com/index.php?title=Manual:Scripting&printabl...
Logical Operators
Bitwise Operators
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
6 di 17 10/02/18, 13:03
Manual:Scripting - MikroTik Wiki https://wiki.mikrotik.com/index.php?title=Manual:Scripting&printabl...
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
</tr>
“~” binary operator that matches value against Print all routes which gateway ends with 202
POSIX extended regular expression /ip route print where gateway~"^[0-9 \\.]*202\$"
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
7 di 17 10/02/18, 13:03
Manual:Scripting - MikroTik Wiki https://wiki.mikrotik.com/index.php?title=Manual:Scripting&printabl...
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;
/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)
Commands
Global commands
Every global command should start with ":" token, otherwise it will be treated as variable.
8 di 17 10/02/18, 13:03
Manual:Scripting - MikroTik Wiki https://wiki.mikrotik.com/index.php?title=Manual:Scripting&printabl...
9 di 17 10/02/18, 13:03
Manual:Scripting - MikroTik Wiki https://wiki.mikrotik.com/index.php?title=Manual:Scripting&printabl...
warning"
time :time return :put [:time {:for i from=1 to=10 do={ :delay 100ms }}];
<expression> interval of
time needed
to execute
command
set :set <var> assign value :global a; :set a true;
[<value>] to declared
variable.
find :find <arg> return :put [:find "abc" "a" -1];
<arg> position of
<start> substring or
array
element
environment :environment print :global myVar true; :environment print;
print initialized
<start> variable
information
terminal terminal
related
commands
error :error Generate
<output> console
error and
stop
executing
the script
execute :execute Execute the
<expression> script in {
:local j [:execute {/interface print follow where [:log info ~Sname~]}];
background. :delay 10s;
:do { /system script job remove $j } on-error={}
}
10 di 17 10/02/18, 13:03
Manual:Scripting - MikroTik Wiki https://wiki.mikrotik.com/index.php?title=Manual:Scripting&printabl...
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
11 di 17 10/02/18, 13:03
Manual:Scripting - MikroTik Wiki https://wiki.mikrotik.com/index.php?title=Manual:Scripting&printabl...
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 array of parameters and its values :put [/ip address print as-value]
interval continuously print output in selected time interval, useful to /interface print interval=2
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 to /ip route print where
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
for :for <var> from=<int> to=<int> execute commands over a given number of iterations
step=<int> do={ <commands> }
foreach :foreach <var> in=<array> do={ execute commands for each elements in list
<commands> };
Conditional statement
12 di 17 10/02/18, 13:03
Manual:Scripting - MikroTik Wiki https://wiki.mikrotik.com/index.php?title=Manual:Scripting&printabl...
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
13 di 17 10/02/18, 13:03
Manual:Scripting - MikroTik Wiki https://wiki.mikrotik.com/index.php?title=Manual:Scripting&printabl...
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
14 di 17 10/02/18, 13:03
Manual:Scripting - MikroTik Wiki https://wiki.mikrotik.com/index.php?title=Manual:Scripting&printabl...
Warning: Key name in array contains any character other than lowercase character, it should be put in quotes
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
15 di 17 10/02/18, 13:03
Manual:Scripting - MikroTik Wiki https://wiki.mikrotik.com/index.php?title=Manual:Scripting&printabl...
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
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:
16 di 17 10/02/18, 13:03
Manual:Scripting - MikroTik Wiki https://wiki.mikrotik.com/index.php?title=Manual:Scripting&printabl...
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
17 di 17 10/02/18, 13:03