Scripting Manual

Document revision 1.7 (15-May-2003)
This document applies to the MikroTik RouterOS V2.7

Table Of Contents

Summary

Scripting gives a way to automate some router maintenance tasks by writing scripts to be executed if some event occurs. To write a script, the administrator must learn console commands described in the relevant documentation. Scripts may be written for the System Scheduler (see relevant manual), the Traffic Monitoring Tool (see relevant manual), and for the Netwatch Tool.

Specifications

Packages required : None
License required : Any
Home menu level : /system script
Protocols utilized : None
Hardware usage : not significant

Related Documents

Software Package Installation and Upgrading

Description

Although 2.7 console syntax has many changes from previous versions, most users will not notice any differences. However, if you are using scripting capabilities of RouterOS, it is recommended to read this section, even if you have some experience with previous versions.

This is more an introductory text, less a reference. It freely uses commands and concepts before explaining them, to make it as short, simple and comprehensive as possible. It might be necessary to read it several times. Many examples are given, because it is the best way to explain most things.

Command Syntax

Description

Console commands in RouterOS 2.7 are made from the following parts:
PREFIX PATH PATH_ARGUMENT COMMAND NAMELESS_ARGUMENTS ARGUMENTS

Property Description

PREFIX (: | /) - optional
PATH (multiple choice: text, ..) - a sequence of command level names. It is also optional, but the processing of commands without given path may change in future versions, so PATH is highly recommended. ".." means parent level path
PATH_ARGUMENT is required by some command levels (like /ip firewall rule), and is not allowed anywhere else
COMMAND (text) - command name from the command level specified by path
NAMELESS_ARGUMENTS (text) - arguments, specific to each command. Values of these arguments are written in fixed order after the name of a command, and only after all nameless argument values any named arguments can be given
ARGUMENTS (text) - sequence of argument names (like /user print brief without-paging). For arguments that need values, argument name is followed by a =, followed by a value of an argument

Notes

Variable substitution, command substitution and expressions are allowed only for PATH_ARGUMENT and command argument values. PREFIX, PATH, command name and argument names can only be given directly, as a word. So
:put (1 + 2)
is valid and
(":pu" . "t") 3
is not.

Example

The console commands' parts can be seen in the following examples:

/ping 10.0.0.13 count=5 PREFIX - "/" COMMAND - "ping" NAMELESS_ARGUMENTS - "10.0.0.13" ARGUMENTS - "count=5"

... ip firewall rule input
PATH - ".. ip firewall rule"
PATH_ARGUMENT - "input"
:for i from=1 to=10 do={:put $i}

PREFIX - ":"
COMMAND - "for"
NAMELESS_ARGUMENTS - "i"
ARGUMENTS - "from=1 to=10 do={:put $i}"
/interface monitor-traffic ether1,ether2,ipip1

PREFIX - "/"
PATH - "interface"
COMMAND - "monitor-traffic"
NAMELESS_ARGUMENTS - "ether1,ether2,ipip1"

Grouping

Description

It is possible to execute several commands from the same command level, by grouping them with braces '{}'.

Notes

You should not change current command level in scripts by typing just it's path, without any command, like you when working with console interactively. Such changes have no effect in scripts. Consider:
[admin@MikroTik] ip address> /user {
{... /ip route
{... print
{... }
Flags: X - disabled
  0   ;;; system default user
      name="admin" group=full address=0.0.0.0/0

  1   name="x" group=write address=0.0.0.0/0

  2   name="y" group=read address=0.0.0.0/0


[admin@MikroTik] ip route>
Although the current command level is changed to /ip route, it has effect only on next command entered from prompt, print command is still considered to be /user print.

Example

We will add two users to the user menu in the example below:
[admin@MikroTik] ip address> /user {
{... add name=x password=y group=write
{... add name=y password=z group=read
{... print
{... }
Flags: X - disabled
  0   ;;; system default user
      name="admin" group=full address=0.0.0.0/0

  1   name="x" group=write address=0.0.0.0/0

  2   name="y" group=read address=0.0.0.0/0


[admin@MikroTik] ip address>

Variables

Description

Console allows you to create and use global (system wide) and local (only usable within one script) variables. Variables can be accessed by writing '$' followed by name of variable. Variable names can contain letters, digits and '-' character. A variable must be declared prior to using it in scripts. There are three types of declaration available:
  • global

  • Global variables can be accessed by all scripts and console logins on the same router. There is no way currently to remove global variable, except rebooting router. Variables are not kept across reboots.
  • local

  • Local variables are not shared with any other script, other instance of the same script or other console logins. Its value is lost when script finishes or when variable name is freed by :unset.
  • loop index variables

  • These are used only in do= block of commands and are removed after command completes.
  • monitor commands, that have do= argument

  • See details below.

    You can assign new value to variable using :set command. It has two unnamed arguments: the name of the variable and the new value of the variable.

    Notes

    Loop variables "shadows" already introduced local variables with the same name.

    Introducing variable has no effect on other scripts that may be running. It just tells the current script what variable names can be used, and where to get their values. After variable is no longer needed, it's name can be freed by :unset command. If you free local variable, it's value is lost. If you free global variable, it's value is still kept in router, it just becomes inaccessible from current script.

    Example

    [admin@MikroTik] ip route> :put $a
    ERROR: unknown variable a
    [admin@MikroTik] ip route>
    
    You must first declare a variable.
    Like this:
    [admin@MikroTik] ip route> /
    [admin@MikroTik] > :global g1
    [admin@MikroTik] > :set g1 "this is global variable"
    [admin@MikroTik] > :put $g1
    this is global variable
    [admin@MikroTik] >
    
    or like this:
    [admin@MikroTik] > :local l1
    [admin@MikroTik] > :set l1 "this is local variable"
    [admin@MikroTik] > :put $l1
    this is local variable
    [admin@MikroTik] >
    
    or, finally, like this:
    [admin@MikroTik] > :for l1 from=1 to=3 do={:put $l1}
    1
    2
    3
    [admin@MikroTik] > :put $l1
    this is local variable
    [admin@MikroTik] >
    
    The following example will create a local variable with start value 0 and then will increase it by 1:
    [admin@MikroTik] > :local counter
    [admin@MikroTik] > :set counter 0
    [admin@MikroTik] > :put $counter
    0
    [admin@MikroTik] > :set counter ($counter + 1)
    [admin@MikroTik] > :put $counter
    1
    [admin@MikroTik] >
    
    Because increasing or decreasing variable's value by one is such a common case, there are two commands that do just that. :incr increases value of variable by 1, and :decr decreases it by 1.
    [admin@MikroTik] > :incr counter
    [admin@MikroTik] > :put $counter
    2
    [admin@MikroTik] >
    

    Command substitution, return values

    Description

    Some console commands are most useful if their output can be used as an argument value in other commands. In console, this is done by "returning" value from commands. Return value is not displayed on the screen. When you type such a command between square brackets '[' ']', this command is executed and it's return value is used as the value of these brackets. This is called command substitution.

    Example

    Consider find command.
    [admin@MikroTik] > /interface
    [admin@MikroTik] interface> find type=ether
    [admin@MikroTik] interface>
    
    It displays nothing on screen, and returns internal numbers of items with matching property values. This is how return value looks:
    [admin@MikroTik] interface> :put [find type=ether]
    *A,*B
    [admin@MikroTik] interface>
    
    and this is how it can be used in other commands
    [admin@MikroTik] interface> enable [find type=ether]
    [admin@MikroTik] interface>
    
    Besides find, some other commands also return useful values. /ping returns number of successful pings:
    [admin@MikroTik] interface> :put [/ping 10.0.0.1 count=3]
    10.0.0.1 64 byte pong: ttl=64 time<1 ms
    10.0.0.1 64 byte pong: ttl=64 time<1 ms
    10.0.0.1 64 byte pong: ttl=64 time<1 ms
    3 packets transmitted, 3 packets received, 0 packet loss
    round-trip min/avg/max = 0/0.0/0 ms
    3
    [admin@MikroTik] interface>
    
    :set returns value of it's second argument. :time returns the measured time value. :incr and :decr return new value of variable. Another important case is add command, which return internal number of newly created item.
    [admin@MikroTik] interface> /user
    [admin@MikroTik] user> :put [add name=z password=x group=full]
    *7
    [admin@MikroTik] user>
    
    This way you can store it in variable for later use.

    Operators

    Description

    Console can do simple calculations with numbers, time values, ip addresses, strings and lists. It is achieved by writing expressions and putting them in parentheses '(' and ')'.

    Supported operations are:

  • ! - logical NOT

  • Unary operator. Argument is a boolean value. Result is an opposite boolean value.
  • - - unary minus

  • Unary operator. Argument and result is a number.
  • ~ - bit inversion

  • Unary operator. Inverts bits in IP address.
  • + - sum

  • Binary operator. Adds two numbers, two time values, or add number to an IP address.
  • - - subtraction

  • Binary operator. Subtracts two numbers one from another, two time values, two IP addresses or an IP address and a number.
  • * - multiplication

  • Binary operator. Multiplies two numbers, or multiply a time value by a number.
  • / - division

  • Binary operator. Divides one number by another (gives an integer), or a time value by a number (gives time value).
  • comparison operators

  • < - less
    > - more
    <= - less or equal
    >= - more or equal
    Binary operators. Compare two numbers, two time values, or two IP addresses. Give boolean value.
    != - not equal
    = - equal
    Binary operators. Compare two values of the same type. Arrays are equal if their respective elements are equal.
  • && - logical AND

  • || - logical OR

  • Binary operators. Logical operation on two boolean values. Result of && is true, if both operands are true. Result of || is true if either operand is true.
  • bitwise operators

  • & - bitwise and
    | - bitwise or
    ^ - bitwise xor
    Binary operators. Bitwise operations on two IP addresses. Result is also an IP address.
    << - shift left
    >> - shift right
    Binary operators. Shift IP value left or right by given amount of bits. First argument is an IP address and second argument is an integer. Result is an IP address.
  • . - concatenation

  • Binary operator. Concatenates two strings, or appends one list to another, or appends an element to a list.

    Example

    [admin@MikroTik] user> :put (1 + 2)
    3
    [admin@MikroTik] user> /interface
    [admin@MikroTik] interface> :put ([find type=ipip ] . [find type=ether ])
    *6,*A,*B
    [admin@MikroTik] interface>
    
    logical NOT
    [admin@MikroTik] interface> :put (!true)
    false
    [admin@MikroTik] interface> :put (!(2>3))
    true
    [admin@MikroTik] interface>
    
    unary minus
    [admin@MikroTik] interface> :put (-1<0)
    true
    [admin@MikroTik] > :put (--1)
    1
    
    bit inversion
    [admin@MikroTik] interface> :put (~255.255.0.0)
    0.0.255.255
    [admin@MikroTik] interface>
    
    sum
    [admin@MikroTik] interface> :put (3s + 5s)
    8s
    [admin@MikroTik] interface> :put (10.0.0.15 + 0.0.10.0)
    ERROR: cannot add ip address to ip address
    [admin@MikroTik] interface> :put (10.0.0.15 + 10)
    10.0.0.25
    [admin@MikroTik] interface>
    
    subtraction
    [admin@MikroTik] interface> :put (15 - 10)
    5
    [admin@MikroTik] interface> :put (10.0.0.15 - 10.0.0.3)
    12
    [admin@MikroTik] interface> :put (10.0.0.15 - 12)
    10.0.0.3
    [admin@MikroTik] interface> :put (15h - 2s)
    14h59m58s
    [admin@MikroTik] interface>
    
    multiplication
    [admin@MikroTik] interface> :put (12s * 4)
    48s
    [admin@MikroTik] interface> :put (-5 * -2)
    10
    [admin@MikroTik] interface>
    
    division
    [admin@MikroTik] interface> :put (10s / 3)
    3s333.333ms
    [admin@MikroTik] interface> :put (5 / 2)
    2
    [admin@MikroTik] interface>
    
    comparison
    [admin@MikroTik] interface> :put (10.0.2.3<=2.0.3.10)
    false
    [admin@MikroTik] interface> :put (100000s>27h)
    true
    [admin@MikroTik] interface> :put (60s,1d!=1m,3600s)
    false
    [admin@MikroTik] interface> :put (bridge=routing)
    false
    [admin@MikroTik] interface> :put (yes=false)
    false
    [admin@MikroTik] interface> :put (true=aye)
    ERROR: cannot compare if truth value is equal to string
    [admin@MikroTik] interface>
    
    logical AND, logical OR
    [admin@MikroTik] interface> :put ((yes && yes) || (yes && no))
    true
    [admin@MikroTik] interface> :put ((no || no) && (no || yes))
    false
    [admin@MikroTik] interface>
    
    bitwise AND, bitwise OR, bitwise XOR
    [admin@MikroTik] interface> :put (10.16.0.134 & ~255.255.255.0)
    0.0.0.134
    [admin@MikroTik] interface>
    
    shift operators
    [admin@MikroTik] interface> :put (~((0.0.0.1 << 7) - 1))
    255.255.255.128
    [admin@MikroTik] interface>
    
    concatenation
    [admin@MikroTik] interface> :put (1 . 3)
    13
    [admin@MikroTik] interface> :put (1,2 . 3)
    1,2,3
    [admin@MikroTik] interface> :put (1 . 3,4)
    13,4
    [admin@MikroTik] interface> :put (1,2 . 3,4)
    1,2,3,4
    [admin@MikroTik] interface> :put ((1 . 3) + 1)
    ERROR: cannot add string to integer number
    [admin@MikroTik] interface>
    

    Value types

    Description

    Console can work with several types of values. Currently it distinguishes between strings, boolean values, numbers, time intervals, IP addresses, internal numbers and lists. Currently console tries to convert any value to the most specific type first, backing up if it fails. This is the order in which console attempts to convert a value:
  • list
  • internal number
  • number
  • IP address
  • time value
  • boolean value
  • string value

    There is no way to explicitly control this type conversion, but it most likely will be changed in future versions. Meanwhile, this can help to explain why console sometimes "corrupts" values, that are meant to be strings, but look like one of the above types:

    [admin@MikroTik] interface> :put 1s1d90039
    2d1h40s
    [admin@MikroTik] interface>
    
    In console integers are internally represented as 64 bit signed numbers, so the range of variable values can be from -9223372036854775808 to 9223372036854775807. It is possible to input them as hexadecimal numbers, by prefixing with "0x":
    [admin@MikroTik] interface> :put 0x123ABCDEF4567890
    1313569907099990160
    [admin@MikroTik] interface> /
    [admin@MikroTik] >
    
    Lists are written as comma separated sequence of values. Putting whitespaces around commas is not recommended, because it might confuse console about word boundaries.
    [admin@MikroTik] > :foreach i in 1,2,3 do {:put $i}
    1
    2
    3
    [admin@MikroTik] > :foreach i in 1, 2, 3 do {:put $i}
    ERROR: no such argument (2,)
    [admin@MikroTik] >
    
    Boolean values are written as either true or false. Console also accepts yes for true, and no for false.

    Internal numbers begin with '*'.

    Time intervals are written as sequence of numbers, that can be followed by letters specifying the units of time measure. The default is a second. Numbers may have decimal point. It is also possible to use the HH:MM:SS notation. Here are some examples:

    [admin@MikroTik] > :put "1000s"
    16m40s
    [admin@MikroTik] > :put "1day 1day 1day"
    3d
    [admin@MikroTik] > :put "1day day 1day"
    1day day 1day
    [admin@MikroTik] > :put "1.5hours"
    1h30m
    [admin@MikroTik] > :put "1:15"
    1h15m
    [admin@MikroTik] > :put "0:3:2.05"
    3m2s50ms
    [admin@MikroTik] >
    
    Accepted time units:
    d, day, days - unit is 24 hours
    h, hour, hours - unit is 1 hour
    m - unit is 1 minute
    s - unit is 1 second
    ms - unit is 1 millisecond (0.001 second)

    Common Commands

    Description

    Console has many built-in commands that start with ':' prefix. Although they don't change configuration directly, they are useful for writing scripts. You can see entire list of such commands by pressing '?' after typing the ':' prefix:
    [admin@MikroTik] > :
    
    	local  introduces local variable
           global  introduces global variable
    	unset  forgets variable
    	  set  creates or changes variable value
    	  put  prints argument on the screen
    	while  executes command while condition is true
    	   if  executes command if condition is true
    	   do  executes command
    	 time  times command
    	 incr  increments variable
    	 decr  decrements variable
    	  for  executes command for a range of integer values
          foreach  executes command for every element in a list
    	delay  does nothing for a while (default 1 second)
      environment  information about variables
    	  log  add entry in the system logs
    [admin@MikroTik] > :
    
    :local, :global, :unset, :set, :incr and :decr commands are explained in the section about variables. All other commands will be explained in this section.
    [admin@MikroTik] > :if (yes) do={:put yes} else={:put no}
    true
    [admin@MikroTik] > :if ([/ping 10.0.0.1 count=1] = 0) do {:put "gw unreachable"}
    10.0.0.1 pong timeout
    1 packets transmitted, 0 packets received, 100% packet loss
    gw unreachable
    [admin@MikroTik] >
    
    There are four loop control commands in console. They all have do statement, which holds console commands that have to be executed repeatedly.

    Special Commands

    Monitor

    It is possible to access values that are shown by most monitor commands from scripts. If monitor command has do argument, it can be supplied either script name (see /system scripts), or console commands.

    Get

    It is also possible to access from scripts values that are shown by most print commands. Most command levels that have print command, also have get command. It has one or two unnamed arguments. If this command level deals with a list of items, first argument is a name or internal number of an item. Second argument is a name of item's property which should be returned.

    Notes

    Monitor command with do argument can also be called directly from scripts. It will not print anything then, just execute the given script.

    Names of properties that can be accessed by get are the same as shown by print command, plus names of item flags (like the disabled in the example below). You can use tab key completions to see what properties any particular get command can return.

    Monitor Example

    In the example below monitor command will execute given script each time it prints stats on the screen, and it will assign all printed values to local variables with the same name:
    [admin@MikroTik] > /interface
    [admin@MikroTik] interface> monitor-traffic ether2 once do={:environment print}
        received-packets-per-second: 2
           received-bits-per-second: 960.00bps
    	sent-packets-per-second: 0
    	   sent-bits-per-second: 0.00bps
    
    Global Variables
    Local Variables
    sent-bits-per-second=0
    received-packets-per-second=2
    received-bits-per-second=960
    sent-packets-per-second=0
    [admin@kzd] interface>
    

    Get Example

    The example below will get ether1 status from the interfaces list. If ether1 is disabled, it will return the value true:
    [admin@MikroTik] interface> :put [/interface get ether1  disabled ]
    true
    [admin@MikroTik] interface>
    
    If command level has general settings, get command only takes the name of property:
    [admin@MikroTik] interface> :put [/system clock get time ]
    feb/28/2003 12:44:39
    [admin@MikroTik] interface>
    

    Additional Features

    It is possible to include comments in console scripts. If script line starts with '#', all characters until newline are ignored.

    It is possible to put multiple commands on a single line, separating them by ';'. Console treats ';' as end of line when separating script text into commands.

    If you want to use any of {}[]"'\$ characters in a string, you have to prefix them with '\' character. Console takes any character following '\' literally, without assigning any special meaning to it, except for such cases:

    \a	bell (alarm), character code 7
    \b	backspace, character code 8
    \f	form feed, character code 12
    \n	newline, character code 10
    \r	carriage return, character code 13
    \t	tabulation, character code 9
    \v	vertical tabulation, character code 11
    \_	space, character code 32
    
    Also, '\' followed by any amount of whitespace characters (spaces, newlines, carriage returns, tabulations), followed by newline is treated as a single whitespace, except inside quotes, where it is treated as nothing. This is used by console to break up long lines in scripts generated by export commands.

    Scripts

    Submenu level : /system script

    Description

    In RouterOS v2.7, a script may be started in three ways:

    Property Description

    name (name; default: scriptN) - name of the script to be referenced when invoking it
    source (text; default: "") - the script itself
    owner (name; default: admin) - the name of the user who created the script
    run-count (integer; default: 0) - usage counter. This counter is incremented each time the script is executed, it can be reset to zero by setting 'run-counter=0'. The counters will reset after reboot.
    last-started (time) - date and time when the script has been last invoked. The argument is shown only if the 'run-count=0'.
    policy (multiple choice: ftp, local, policy, read, reboot, ssh, telnet, test, web, write; default: reboot,read,write,policy,test) - the name(s) of the specific policy. Can be choosen of the:
  • 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

    Notes

    You can't do more in the scripts than you are allowed to do by your current user name, that is, you can't use disabled policies. For example, if there is a policy group in /user group which allows you ssh,local,telnet,read,write,policy,test,web and if this group is assigned to yout user name then you can't make a script that reboots the router.

    You can execute a script by using the run command.

    Example

    The following example is a script for writing message "hello" to the system log:

    [admin@MikroTik] system script> add name=log-test source={:log message=hello}
    [admin@MikroTik] system script> print
      0 name="log-test" source=":log message=hello" owner="admin"
        policy=reboot,read,write,policy,test run-count=0
    
    [admin@MikroTik] system script>
    

    Task Management

    Submenu level : /system script job

    Description

    This facility is used to manage the active or scheduled tasks. You can see the status of all currently active tasks using the print command.

    Property Description

    name (name) - name of the script to be referenced when invoking it. source (text) - the script itself
    owner (text; default: admin) - the name of the user who created the script

    Example

    For example, we have a script that delays some process for 10 minutes:
    [admin@MikroTik] system script> add name=DelayeD source={:delay 10m}
    [admin@MikroTik] system script> print
      0 name="log-test" source=":log message=hello" owner=admin
        last-started=feb/27/2003 11:05:19 run-count=1
    
      1 name="DelayD" source=":delay 10m" owner="admin"
        policy=reboot,read,write,policy,test run-count=0
    [admin@MikroTik] system script> run DelayeD
    [admin@MikroTik] system script> job print
      # SCRIPT  OWNER                   STARTED
      0 DelayeD admin                   feb/27/2003 11:17:33
    
    [admin@MikroTik] system script>
    
    You can cancel execution of a script by removing it from the jobs list:
    [admin@MikroTik] system script> job remove 0
    [admin@MikroTik] system script> job print
    [admin@MikroTik] system script> print
      0 name="log-test" source=":log message=hello" owner="admin"
        policy=reboot,read,write,policy,test last-started=feb/27/2003 11:05:13
        run-count=1
    
      1 name="DelayD" source=":delay 10m" owner="admin"
        policy=reboot,read,write,policy,test last-started=feb/27/2003 11:17:33
        run-count=1
    
    [admin@MikroTik] system script>
    

    Script Editor

    Submenu level : /system script edit

    Description

    system script edit is simple full-screen editor for scripts. It's used for multiline script writing. To run the script editor just type system script edit script-name source, where script-name is the name of the script you want to edit.

    Special Keys

    Delete - delete character a cursor position
    Ctrl-h, backspace - delete character before cursor. Unindent line
    Tab - indent line
    Ctrl-b, LeftArrow - move cursor left
    Ctrl-f, RightArrow - move cursor right
    Ctrl-p, UpArrow - move cursor up
    Ctrl-n, DownArrow - move cursor down
    Ctrl-a, Home - move cursor to the beginning of line or script
    Ctrl-e, end - move cursor to the end of line or script
    Ctrl-y - insert contents of cut buffer at cursor position
    Ctrl-k - delete characters from cursor position to the end of line
    Ctrl-u - undo editing action
    Ctrl-o - exit editor and accept changes
    Ctrl-x - exit editor and discard changes

    Notes

    All characters that are deleted by backspace, delete, Ctrl-k keys are accumulated in cut buffer. Pressing any other key finishes adding to this buffer (Ctrl-y can paste it's contents), and next delete operation will replace it's contents. Undo doesn't change contents of cut buffer.

    Editor works only on VT102 compatible terminals (terminal names "vt102", "linux", "xterm", "rxvt" are recognized as VT102 at the moment). Delete, backspace and cursor keys might not work with all terminal programs, use 'Ctrl' alternatives in such cases.

    Example

    The following example shows the process of sript editing using edit command:

    Edit example

    This script is used for writing message "hello" and 3 messages "kuku" to the system log.

    Network Watching Tool

    Specifications

    Packages required : advanced-tools
    License required : Any
    Home menu level : /tool netwatch
    Protocols utilized : None
    Hardware usage: not significant

    Description

    Netwatch monitors state of hosts on the network. It does so by sending ICMP pings to list of specified IP addresses. For each entry in netwatch table you can specify IP address, ping interval and console scripts. The main advantage of netwatch is it's ability to issue arbitrary console commands on host state changes.

    Property Description

    host (IP address; default: 0.0.0.0) - IP address of host that should be monitored
    interval (time; default: 1s) - time between pings. Lowering this will make state changes more responsive, but can create unnecessary traffic and consume system resources
    timeout (time; default: 1s) - timeout for each ping. If no reply from a host is received in this time, the host is considered unreachable (down)
    up-script (name) - console script that is executed once when state of a host changes from unknown or down to up
    down-script (name) - console script that is executed once when state of a host changes from unknown or up to down
    since (read-only: time) - time when state of host changed last time
    status (read-only: up | down | unknown) - tells the current status of the host
  • up - the host is up
  • down - the host is down
  • unknown - when any properties of this list entry are changed, or it is enabled or disabled

    Example

    This example will run the scripts gw_1 or gw_2 which change the default gateway depending on the status of one of the gateways:

    [admin@MikroTik] system script> add name=gw_1 source={/ip route set
    {... [/ip route find dst 0.0.0.0] gateway 10.0.0.1}
    [admin@MikroTik] system script> add name=gw_2 source={/ip route set 
    {.. [/ip route find dst 0.0.0.0] gateway 10.0.0.217}
    [admin@MikroTik] system script> /tool netwatch
    [admin@MikroTik] tool netwatch> add host=10.0.0.217 interval=10s timeout=998ms \
    \... up-script=gw_2 down-script=gw_1
    [admin@MikroTik] tool netwatch> print
    Flags: X - disabled
      #   HOST	      TIMEOUT		   INTERVAL		STATUS
      0   10.0.0.217      997ms		   10s			up
    [admin@MikroTik] tool netwatch> print detail
    Flags: X - disabled
      0   host=10.0.0.217 timeout=997ms interval=10s since=feb/27/2003 14:01:03
          status=up up-script=gw_2 down-script=gw_1
    
    [admin@MikroTik] tool netwatch>
    
    Without scripts, netwatch can be used just as an information tool to see which links are up, or which specific hosts are running at the moment.

    Let's look at the example above - it changes default route if gateway becomes unreachable. How it's done? There are two scripts. The script "gw_2" is executed once when status of host changes to up. In our case, it's equivalent to entering this console command:

    [MikroTik] > /ip route set [/ip route find dst 0.0.0.0] gateway 10.0.0.217
    
    The /ip route find dst 0.0.0.0 command returns list of all routes whose dst-address value is zero. Usually that's the default route. It is substituted as first argument to /ip route set command, which changes gateway of this route to 10.0.0.217

    The script "gw_1" is executed once when status of host becomes down. It does the following:

    [MikroTik] > /ip route set [/ip route find dst 0.0.0.0] gateway 10.0.0.1
    
    It changes the default gateway if 10.0.0.217 address has become unreachable.

    Here's another example, that sends email notification whenever the 10.0.0.215 host goes down:

    [admin@MikroTik] system script> add name=e-down source={/tool e-mail send
    {... from="rieks@mt.lv" server="159.148.147.198" body="Router down"
    {... subject="Router at second floor is down" to="rieks@latnet.lv"}
    [admin@MikroTik] system script> add name=e-up source={/tool e-mail send
    {... from="rieks@mt.lv" server="159.148.147.198" body="Router up"
    {.. subject="Router at second floor is up" to="rieks@latnet.lv"}
    [admin@MikroTik] system script>
    [admin@MikroTik] system script> /tool netwatch
    [admin@MikroTik] system netwatch> add host=10.0.0.215 timeout=999ms \
    \... interval=20s up-script=e-up down-script=e-down
    [admin@MikroTik] tool netwatch> print detail
    Flags: X - disabled
      0   host=10.0.0.215 timeout=998ms interval=20s since=feb/27/2003 14:15:36
          status=up up-script=e-up down-script=e-down
    
    [admin@MikroTik] tool netwatch>
    

    System Scheduler

    Specifications

    Packages required : None
    License required : Any
    Home menu level : /system scheduler
    Protocols utilized : none
    Hardware usage: not significant

    Description

    System sheduler provides a vay to execute scripts at designated time.

    Property Description

    name (name) - name of the task
    interval (time interval; default: 0s) - interval between two script executions, if time interval is set to zero, the script is only executed at it's start time, otherwise it is executed repeatedly at the time interval specified
    run-count (read-only: integer) - to monitor script usage, this counter is incremented each time the script is executed
    script (name) - name of the script. The script must be present at /system script
    start-date (date) - date of first execution
    start-time (time) - time of first execution

    Notes

    Rebooting the router will reset run-count counter.

    If more than one script has to be executed at one time, they are executed in the order they appear in the scheduler configuration. This can be important if, for example, one scheduled script is used to disable another. The order of scripts can be changed with the move command.

    If a more complex execution pattern is needed, it can usually be done by scheduling several scripts, and making them enable and disable each other.

    Example

    We will add a task that executes the script log-test every hour:
    [admin@MikroTik] system script> add name=log-test source=:log
    [admin@MikroTik] system script> print
      0 name="log-test" source=":log" owner=admin run-count=0
    
    [admin@MikroTik] system script> .. scheduler
    [admin@MikroTik] system scheduler> add name=run-1h interval=1h script=log-test
    [admin@MikroTik] system scheduler> print
    Flags: X - disabled
      #   NAME      SCRIPT   START-DATE  START-TIME INTERVAL             RUN-COUNT
      0   run-1h    log-test oct/30/2008 15:08:22   1h                   1
    [admin@MikroTik] system scheduler>
    
    In another example there will be two scripts added that will change the bandwidth setting of a queue rule "Cust0". Everyday at 9AM the queue will be set to 64Kb/s and at 5PM the queue will be set to 128Kb/s. The queue rule, the scripts, and the scheduler tasks are below:
    [admin@MikroTik] queue simple> add name=Cust0 interface=ether1 \
    \... dst-address=192.168.0.0/24 limit-at=64000
    [admin@MikroTik] queue simple> print
    Flags: X - disabled, I - invalid
      0   name="Cust0" src-address=0.0.0.0/0 dst-address=192.168.0.0/24
          interface=ether1 limit-at=64000 queue=default priority=8 bounded=yes
    
    [admin@MikroTik] queue simple> /system script
    [admin@MikroTik] system script> add name=start_limit source={/queue simple set \
    \... Cust0 limit-at=64000}
    [admin@MikroTik] system script> add name=stop_limit source={/queue simple set \
    \... Cust0 limit-at=128000}
    [admin@MikroTik] system script> print
      0 name="start_limit" source="/queue simple set Cust0 limit-at=64000"
        owner=admin run-count=0
    
      1 name="stop_limit" source="/queue simple set Cust0 limit-at=128000"
        owner=admin run-count=0
    
    [admin@MikroTik] system script> .. scheduler
    [admin@MikroTik] system scheduler> add interval=24h name="set-64k" \
    \... start-time=9:00:00 script=start_limit
    [admin@MikroTik] system scheduler> add interval=24h name="set-128k" \
    \... start-time=17:00:00 script=stop_limit
    [admin@MikroTik] system scheduler> print
    Flags: X - disabled
      #   NAME      SCRIPT   START-DATE  START-TIME INTERVAL             RUN-COUNT
      0   set-64k   start... oct/30/2008 09:00:00   1d                   0
      1   set-128k  stop_... oct/30/2008 17:00:00   1d                   0
    [admin@MikroTik] system scheduler>
    
    The following example schedules script that sends each week backup of router configuration by e-mail.
    [admin@MikroTik] system script> add name=e-backup source={/system backup
    {... save name=email; /tool e-mail send to="root@host.com" subject=[/system
    {... identity get name]" Backup" file=email.backup}
    [admin@MikroTik] system script> print
      0 name="e-backup" source="/system backup save name=ema... owner=admin
        run-count=0
    
    [admin@MikroTik] system script> .. scheduler
    [admin@MikroTik] system scheduler> add interval=7d name="email-backup" \
    \... script=e-backup
    [admin@MikroTik] system scheduler> print
    Flags: X - disabled
      #   NAME      SCRIPT   START-DATE  START-TIME INTERVAL             RUN-COUNT
      0   email-... e-backup oct/30/2008 15:19:28   7d                   1
    [admin@MikroTik] system scheduler>
    
    Do not forget to set the e-mail settings, i.e., the SMTP server and From: address under /tool e-mail. For example:
    [admin@MikroTik] tool e-mail> set server=159.148.147.198 from=SysAdmin@host.com
    [admin@MikroTik] tool e-mail> print
        server: 159.148.147.198
          from: SysAdmin@host.com
    [admin@MikroTik] tool e-mail>
    
    Example below will put 'x' in logs each hour from midnight till noon:
    [admin@MikroTik] system script> add name=enable-x source={/system scheduler
    {... enable x}
    [admin@MikroTik] system script> add name=disable-x source={/system scheduler
    {... disable x}
    [admin@MikroTik] system script> add name=log-x source={:log message=x}
    [admin@MikroTik] system script> .. scheduler
    [admin@MikroTik] system scheduler> add name=x-up start-time=00:00:00 \
    \... interval=24h script=enable-x
    [admin@MikroTik] system scheduler> add name=x-down start-time=12:00:00
    \... interval=24h script=disable-x
    [admin@MikroTik] system scheduler> add name=x start-time=00:00:00 interval=1h \
    \... script=log-x
    [admin@MikroTik] system scheduler> print
    Flags: X - disabled
      #   NAME      SCRIPT   START-DATE  START-TIME INTERVAL             RUN-COUNT
      0   x-up      enable-x oct/30/2008 00:00:00   1d                   0
      1   x-down    disab... oct/30/2008 12:00:00   1d                   0
      2   x         log-x    oct/30/2008 00:00:00   1h                   0
    [admin@MikroTik] system scheduler>
    

    Traffic Monitor

    Specifications

    Packages required : None
    License required : Any
    Home menu level : /tool traffic-monitor
    Protocols utilized : None
    Hardware usage: not significant

    Description

    The traffic monitor tool is used to execute console scripts on when interface traffic crosses some given thresholds. Each item in traffic monitor list consists of its name (which is useful if you want to disable or change properties of this item from another script), some parameters specifying traffic condition and the pointer to a script or scheduled event to execute when this condition is met.

    Property Description

    name (name) - name of the traffic monitor item
    interface (name) - interface to monitor
    threshold (integer; default: 0) - traffic threshold
    trigger (above | always | below; default: above) - condition on which to execute script
  • above - the script will be run each time traffic exceeds the threshold
  • always - triggers scripts on both above and below conditions
  • below - triggers script in the opposite condition, when traffic drops under the threshold
    traffic (transmitted | received; default: transmitted) - type of traffic to monitor
  • transmitted - transmitted packets
  • received - received packets
    on-event (name) - Script source. Must be present under /system script

    Example

    The example monitor enables the interface ether2, if the received traffic exceeds 15kbps on ether1, and disables the interface ether2, if the received traffic falls below 12kbps on ether1.
    [admin@MikroTik] system script> add name=eth-up source={/interface enable ether2}
    [admin@MikroTik] system script> add name=eth-down source={/interface disable
    {... ether2}
    [admin@MikroTik] system script> /tool traffic-monitor
    [admin@MikroTik] tool traffic-monitor> add name=turn_on interface=ether1 \
    \... on-event=eth-up threshold=15000 trigger=above traffic=received
    [admin@MikroTik] tool traffic-monitor> add name=turn_off interface=ether1 \
    \... on-event=eth-down threshold=12000 trigger=below traffic=received
    [admin@MikroTik] tool traffic-monitor> print
    Flags: X - disabled, I - invalid
      #   NAME           INTERFACE     TRAFFIC     TRIGGER THRESHOLD  ON-EVENT
      0   turn_on        ether1        received    above   15000      eth-up
      1   turn_off       ether1        received    below   12000      eth-down
    [admin@MikroTik] tool traffic-monitor>
    

    Sigwatch

    Specifications

    Packages required : advanced-tools
    License required : Any
    Home menu level : /tool sigwatch
    Protocols utilized : None
    Hardware usage: not significant

    Description

    Sigwatch can be used to monitor state of serial port pins.

    Property Description

    name - name of the sigwatch item
    log (yes | no; default: no) - add or not message in form "name-of-sigwatch-item: signal changed [to high | to low]" to System-Info facility whenever this sigwatch item is triggered
    script (name) - script that is executed whenever this item is triggered
    on-condition (on | off; default: on) - on what condition to trigger actions of this item
  • on - trigger when state of pin changes to high
  • off - trigger when state of pin changes to low
  • change - trigger whenever state of pin changes. If state of pin changes rapidly, there might be triggered only one action for several state changes
    port (name) - serial port to monitor
    signal (dtr | rts | cts | dcd | ri | dsr; default: rts) - name of signal or number of pin (for standard 9-pin connector) to monitor
  • dtr - Data Terminal Ready - pin #4
  • rts - Request To Send - pin #7
  • cts - Clear To Send - pin #8
  • dcd - Data Carrier Detect - pin #1
  • ri - Ring Indicator - pin #9
  • dsr - Data Set Ready - pin #6
    count (read-only: integer) - how many time event for this item was triggered. Count is reset on reboot and on most item configuration changes
    state (read-only: text) - last remembered state of monitored signal

    Notes

    You can type actual script source instead of the script name from /system script list.

    Example

    In the following example we'll add new sigwatch item that monitors whether serial1 port has cts signal.
    [admin@10.179] tool sigwatch> pr
    Flags: X - disabled
      #   NAME                                  PORT    SIGNAL     ON-CONDITION LOG
      0   test                                  serial1 cts        change       no
    
    [admin@MikroTik] tool sigwatch>
    
    By typing a command print detail interval=1s we can prove whether a cable is connected or disconnected. See the state argument - if the cable is connected to the serial port, it shows on, when disconnected - off:
    [admin@MikroTik] tool sigwatch> print detail
    Flags: X - disabled
      0   name="test" port=serial1 signal=cts on-condition=change log=no script=""
          count=1 state=on
    
    [admin@MikroTik] tool sigwatch> print detail
    Flags: X - disabled
      0   name="test" port=serial1 signal=cts on-condition=change log=no script=""
          count=1 state=on
    
    [admin@MikroTik] tool sigwatch> print detail
    Flags: X - disabled
      0   name="test" port=serial1 signal=cts on-condition=change log=no script=""
          count=2 state=off
    
    [admin@MikroTik] tool sigwatch> print detail
    Flags: X - disabled
      0   name="test" port=serial1 signal=cts on-condition=change log=no script=""
          count=2 state=off
    
    [admin@MikroTik] tool sigwatch>
    
    In the port menu it's seen what signal is used by serial cable. For example, without any cables it looks like this:
    [admin@MikroTik] port> print stats
      0 name="serial0" line-state=dtr,rts
    
      1 name="serial1" line-state=dtr,rts
    [admin@MikroTik] port>
    
    But after adding a serial cable to the serial port:
    [admin@MikroTik] port> print stats
      0 name="serial0" line-state=dtr,rts
    
      1 name="serial1" line-state=dtr,rts,cts
    [admin@MikroTik] port>
    
    It means that the line-state beside the dtr and rts signals has also cts when a serial cable is connected.

    The example below will execute a script whenever on-condition changes to off:

    [admin@10.MikroTik] tool sigwatch> pr detail
    Flags: X - disabled
      0   name="cts_rest" port=serial1 signal=cts on-condition=off log=no
          script=/system shutdown count=0 state=on
    
    It means that if a serial cable is connected to the serial port, all works fine, but as soon as it's disconnected - the router shuts down. It will continue all the time until the serial cable will not be connected again.
    © Copyright 1999-2003, MikroTik