Fore more efficient network management, different tasks in MikroTik can be automated using scripts. For example, you can create a script to check the availability of some host(s), and it run manually, or automatically using the MikroTik scheduler. This guide will show you how to create, run, and schedule a script on MikroTik RouterOS.
Tested on MikroTik RouterOS v7.14.3.
Creating a Script
To create a script in MikroTik, execute:
[admin@MikroTik] > /system/script/add name=ping-check comment="Ping check [admin@MikroTik] > /system/script/edit ping-check source
Paste and save the following code:
# Variables
:local host "www.shellhacks.com"
# Ping check
:if ([ping $host count=1] = 0 do={
:log error "$host is DOWN"
} else={
:log info "$host is UP"
}
This script pings the specified host, i.e. www.shellhacks.com, and logs the results.
Running the Script
Once the script is ready, you can run it manually by executing:
[admin@MikroTik] > /system/script/run ping-check - sample output - Columns: SEQ, HOST, SIZE, TTL, TIME SEQ HOST SIZE TTL TIME 0 135.148.34.70 56 251 80ms911us
Check the logs to ensure that the script is functioning as expected:
[admin@MikroTik] > /log/print - sample output - ... 22:12:53 script,info www.shellhacks.com is UP
Scheduling the Script
To automate the process, add the script to the MikroTik scheduler and configure it to execute the script at the desired interval, e.g. every minute:
[admin@MikroTik] > /system/scheduler/add disabled=no \ interval=1m \ name="ping-check" \ comment="Ping check" \ on-event=ping-check \ policy=reboot,read,write,policy,test,password,sniff,sensitive,ftp,romon \ start-date=jan/01/1970 \ start-time=00:00:00
Checking Logs
After setting up the scheduler, check the logs to confirm the script is running correctly:
[admin@MikroTik] > /log/print - sample output - ... 22:14:00 script,info www.shellhacks.com is UP 22:15:00 script,info www.shellhacks.com is UP 22:16:00 script,info www.shellhacks.com is UP
Additional Resources
Conclusion
MikroTik scripts are a powerful way to automate different network tasks. By following this guide, you’ll have a functioning script that runs automatically and logs results efficiently. Additionally, you can integrate email or Telegram notifications to get alerted if the destination host becomes unreachable. Check out the additional resources above for more insights into MikroTik’s capabilities.