MikroTik RouterOS Scripting Language Tutorial
MikroTik’s RouterOS scripting language provides a flexible and powerful way to automate tasks, configure routers, and streamline network management. This tutorial is designed to give you a comprehensive introduction to the language and syntax, including plenty of examples and detailed descriptions of the key scripting elements.
1. Introduction to MikroTik RouterOS Scripting
The RouterOS scripting language allows administrators to automate complex tasks such as configuration changes, monitoring, and backups. You can use scripts to trigger actions based on network events, manage large configurations efficiently, and even integrate external services for monitoring and alerting.
RouterOS scripting can be run in the CLI (Command Line Interface) or scheduled and saved as scripts for regular execution.
2. Basic Structure and Syntax
The MikroTik scripting language is simple yet powerful, consisting of several key elements:
- Commands: Perform actions such as configuring interfaces, routing, or firewalls.
- Variables: Store and manipulate data within a script.
- Conditional Logic: Perform different actions based on specific conditions.
- Loops: Repeat actions multiple times, either for a set number or indefinitely until a condition is met.
3. Variables
Variables in RouterOS scripting allow you to store values temporarily and use them later in the script. They are declared using the :local
keyword.
Syntax
:local varName value
:local
defines a variable that is local to the script.varName
is the name of the variable.value
is the value to be stored in the variable (can be a string, number, or other data types).
Example
:local myIP "192.168.88.1"
:local myNumber 10
:put $myIP
In this example, we declare two variables: one for storing an IP address and another for a number. The :put
command outputs the value of the variable.
4. Commands
Almost any RouterOS command you can run manually can also be included in a script. You can configure interfaces, change IP addresses, and adjust firewall rules using the same commands in scripts.
Syntax
/command [parameters]
Example
/interface ethernet set ether1 disabled=yes
This command disables the ether1
interface. Any RouterOS command can be used in a script just as you would use it interactively in the CLI.
5. Conditional Logic (If Statements)
Conditional logic in scripts allows for decision-making based on variable values or network conditions. The most common form is the if
statement.
Syntax
:if (condition) do={
# actions
}
condition
is a statement that must be true for the code block inside the do={}
to execute.
Example
:local interfaceName "ether1"
:if ([/interface ethernet get $interfaceName disabled] = true) do={
/interface ethernet enable $interfaceName
}
In this example, if the interface ether1
is disabled, the script will enable it. The [ ]
brackets are used to get the status of an interface.
Else Statements
You can extend the if
statement with else
to run alternative actions if the condition is false.
Syntax
:if (condition) do={
# actions if true
} else={
# actions if false
}
Example:
:if ([/interface ethernet get $interfaceName disabled] = true) do={
/interface ethernet enable $interfaceName
} else={
/interface ethernet disable $interfaceName
}
If the interface is disabled, the script enables it, and if it’s enabled, the script disables it.
6. Loops
Loops allow you to repeat actions in RouterOS scripting. There are two main types: for
loops and while
loops.
For Loop
A for
loop repeats a block of code for a specific number of times or over a range of values.
Syntax
:for var from=start to=end do={
# actions
}
var
is the loop variable that changes with each iteration.start
is the starting value of the loop.end
is the end value, at which the loop stops.
Example
:for i from=1 to=5 do={
:put ("Loop number: " . $i)
}
This loop prints "Loop number: X" five times, where X
is the current loop iteration value (from 1 to 5).
While Loop
A while
loop keeps repeating as long as a specified condition is true.
Syntax
:while (condition) do={
# actions
}
Example
:local counter 0
:while ($counter < 5) do={
:set counter ($counter + 1)
:put ("Counter is now: " . $counter)
}
This loop runs until the counter
variable reaches 5, increasing its value by 1 in each iteration.
7. Functions (Simulated Using Scripts)
RouterOS does not have true functions, but you can simulate them by creating scripts that can be executed on-demand.
Creating a Script
- Open WinBox or access your router via SSH.
- Go to System > Scripts.
- Click Add New and enter your script code.
Running a Script
You can run a script manually or schedule it using the scheduler
.
Example Function (Script)
/system script add name="greetUser" source={:put "Hello, World!"}
This script will print "Hello, World!" when executed.
To run the script:
/system script run greetUser
8. Working with Arrays (Lists)
Arrays or lists in RouterOS scripting allow you to store multiple values and work with them as a group.
Syntax
:local myList [list "item1" "item2" "item3"]
Accessing List Elements
You can access specific elements of the list using the :pick
command.
Syntax
:put [:pick $myList 0]
This retrieves the first element (item1
) from the list.
9. Scheduling Scripts
You can automate the execution of scripts using the RouterOS scheduler.
Example
/system scheduler add name="dailyBackup" interval=24h on-event="/system backup save name=([/system clock get date])"
This script creates a backup every 24 hours and names the backup file with the current date.
10. Practical Examples
Example 1: Interface Status Check
This script checks whether an interface is down and enables it if necessary.
:local interfaceName "ether1"
:if ([/interface ethernet get $interfaceName disabled] = true) do={
/interface ethernet enable $interfaceName
/log info "Ether1 was disabled and has been enabled."
} else={
/log info "Ether1 is already enabled."
}
Example 2: Dynamic Firewall Blocking
This script adds an IP to a firewall block list if a condition is met.
:local attackIP "192.168.88.100"
:if ([/ip firewall address-list find where address=$attackIP] = "") do={
/ip firewall address-list add list=blocked address=$attackIP
/ip firewall filter add chain=input src-address=$attackIP action=drop
/log info ("Blocked IP: " . $attackIP)
}
Example 3: Traffic Monitoring
This script logs the current RX and TX byte counts for an interface every minute.
/system script add name="logTraffic" source={
:local iface "ether1"
:local rxBytes [/interface ethernet get $iface rx-byte]
:local txBytes [/interface ethernet get $iface tx-byte]
/log info ("Traffic on " . $iface . ": RX=" . $rxBytes . " TX=" . $txBytes)
}
/system scheduler add name="monitorTraffic" interval=1m on-event="logTraffic"
11. Debugging and Best Practices
- Use
:put
for debugging: You can use:put
to display variable values at different stages of script execution for troubleshooting. - Test scripts on non-critical devices: Always test your scripts in a safe environment before deploying them on production systems.
- Keep your scripts organized: Comment your scripts thoroughly and use descriptive variable names.
12. Conclusion
MikroTik RouterOS scripting is an essential tool for automating tasks and improving network management efficiency. By understanding variables, loops, conditional logic, and scheduling, you can automate everything from backups to complex firewall management.
Continue practicing with different scripts and explore the RouterOS CLI to fully leverage the capabilities of this powerful scripting language.