Manually rebooting routers, updating firewall address lists, or tweaking bandwidth limits is tedious and error‑prone. MikroTik RouterOS includes a powerful scripting engine and scheduler that can automate almost any task. This guide teaches you the basics of RouterOS scripting and shows you practical, production‑ready scripts for daily use.
Why Automate Your MikroTik?
- Save time – Let the router handle recurring tasks while you focus on more important work.
- Improve reliability – Scripts run exactly the same way every time, eliminating human error.
- React instantly – Use netwatch, scheduler, or DHCP events to trigger actions automatically.
- Enhance security – Dynamically block port scanners or brute‑force attempts.
Scripting Basics: The Building Blocks
1. The Script Editor
Access scripts under System → Scripts in WinBox, or via CLI:
/system script
Scripts are stored in order and can be run manually or triggered by events.
2. The Scheduler
Find it under System → Scheduler. Schedulers run scripts at specific times (e.g., daily at 3 AM) or intervals (e.g., every 5 minutes).
3. Basic Script Syntax
RouterOS scripts use a simple, command‑based language. Each command is on a new line. Variables use $variableName.
:local myMessage "Hello, MikroTik"
:put $myMessage
Conditional statements:
:if ([:len [/interface find where running]] > 0) do={
:put "At least one interface is running"
} else={
:put "No interfaces are running"
}
Loops are also available:
:foreach i in=[/interface ethernet find] do={
:put [/interface ethernet get $i name]
}
Practical Script Examples (Ready to Use)
Example 1: Automatic Daily Backup and Email
Create a backup file and send it via email.
Script (name: backup_email):
/system backup save name=auto-backup-$[/system clock get date]
/tool e-mail send to="[email protected]" subject="Router Backup" body="Daily backup attached." file=auto-backup-$[/system clock get date].backup
Scheduler (daily at 2 AM):
/system scheduler add name=daily-backup start-time=02:00:00 interval=1d on-event=backup_email
Example 2: Dynamic Address List Blocking (Brute‑Force Protection)
This script automatically adds IPs that try to access port 22 (SSH) too many times. Combine with firewall rules.
/ip firewall filter add chain=input protocol=tcp dst-port=22 connection-limit=3,32 action=add-src-to-address-list address-list=ssh-brute address-list-timeout=1h
No scheduler needed; the firewall rule does the work. But you can also create a script to clean the list daily.
Example 3: Dynamic Failover with Script (Alternative to Recursive Routing)
If your primary WAN goes down, switch default route to backup.
Script (name: wan_failover):
:local primaryStatus [/ping 1.1.1.1 count=3 interface=ether1]
:if ($primaryStatus = 0) do={
/ip route set [find comment="WAN1"] disabled=yes
/ip route set [find comment="WAN2"] disabled=no
} else={
/ip route set [find comment="WAN1"] disabled=no
/ip route set [find comment="WAN2"] disabled=yes
}
Scheduler (every 30 seconds):
/system scheduler add name=check-wan interval=30s on-event=wan_failover
Example 4: Nightly Bandwidth Restrictions (for Home/Office)
Set lower bandwidth for guest network after midnight.
Script (name: guest_throttle):
:if ([/system clock get time] >= "00:00:00" and [/system clock get time] < "06:00:00") do={
/queue simple set [find name=guest-limit] max-limit=5M/1M
} else={
/queue simple set [find name=guest-limit] max-limit=20M/5M
}
This script should run every hour, or just set two separate scheduled events (one at midnight, one at 6 AM).
Example 5: Log Monitoring and Email Alert on Pattern Match
When a certain log entry appears (e.g., "administrator login failed"), send an email.
Script (name: alert_admin):
/tool e-mail send to="[email protected]" subject="Security Alert" body="Failed admin login attempt detected at $[/system clock get date] $[/system clock get time]"
Set up a log rule under System → Logging → Actions to run the script when a matching message is added.
Example 6: Weekly Firewall Update (Block Malicious IPs)
Download an external list of known bad IPs and add them to an address list.
/tool fetch url="https://rules.emergingthreats.net/blockrules/emerging-botcc.rules" mode=http dst-path=badips.txt
:local badips [/file get badips.txt contents]
:foreach line in=$badips do={
:if ([:len $line] > 0) do={
/ip firewall address-list add address=$line list=malicious timeout=7d
}
}
This is a simplified example; in practice, you’d need to parse the file properly.
Advanced Scripting Concepts
Using Variables and Environments
RouterOS supports global and local variables. Global variables persist across script runs.
:global mycounter
:if ([:typeof $mycounter] = "nothing") do={ :set mycounter 0 }
:set mycounter ($mycounter + 1)
:log info "Script run count: $mycounter"
Interacting with Files
You can read, write, and delete files. Useful for storing temporary data or exporting configurations.
/file print
/file remove something.txt
/file set something.txt contents="new data"
Handling Errors
Use :do with on-error to catch failures.
:do {
/interface wireless set wlan1 ssid="NewName"
} on-error={
:log error "Failed to change SSID"
}
Security Best Practices for Scripts
- Avoid plain‑text passwords – never store passwords in scripts unless absolutely necessary. Use certificates or protected files.
- Limit script permissions – scripts run with full router privileges. Be careful when using
fetchfrom untrusted sources. - Test scripts in a lab before deploying on production routers.
- Log script activity – add
:log infostatements to track what your automation is doing.
Common Mistakes and How to Avoid Them
- Missing quotation marks – RouterOS is strict about quotes, especially when values contain spaces.
- Using
findwithout checking result – always verify that something was found before acting on it. - Infinite loops – avoid long or infinite loops; the scheduler will run scripts repeatedly as needed.
- Not escaping special characters – $ is a variable prefix. Use
\$to output a literal $.
Troubleshooting Scripts
Run scripts manually from the CLI to see errors:
/system script run backup_email
:error "Something went wrong"
View script errors in the log:
/log print where topics~"script"
Use :put to output values for debugging (visible in CLI).
Real‑World Use Cases
ISP Capping Overage Users
A script that runs every hour, queries a RADIUS server (via fetch), and sets bandwidth limits on subscriber PPP secrets if they exceed their quota.
Home User: Auto‑Reboot on Pager
If ping to 8.8.8.8 fails 10 times in a row, reboot the router automatically to restore connectivity.
Hotel: Nightly Reset of Hotspot Users
At 4 AM, log out all active hotspot users to enforce daily vouchers.
/ip hotspot user remove [find]
/ip hotspot active remove [find]
Conclusion
MikroTik's scripting engine turns a static router into a dynamic, self‑healing network device. Start with small scripts – a daily backup, a simple failover check – then gradually automate more tasks. Combine scripts with the scheduler, netwatch, or log actions to react to real‑time events. The examples in this guide are ready to adapt to your own environment.
For further reading, check MikroTik's official Scripting Manual and explore the /system script environment for persistent global variables.