How to Write a Mikrotik Automatic Backup Email Script in RouterOS

Direct Answer
To write a Mikrotik automatic backup email script in RouterOS, utilize scripting to schedule backups and configure email settings for automated delivery.
In the dynamic realm of network management, ensuring the consistent backup of router configurations is paramount for maintaining operational integrity and swift disaster recovery. Mikrotik's RouterOS offers robust scripting capabilities that allow network engineers to automate routine tasks, such as backing up configurations and emailing them to designated recipients. This automation not only minimizes the potential for manual errors but also ensures that backups are performed at regular intervals without requiring constant human intervention. Crafting an efficient script involves leveraging RouterOS's built-in scripting language to create a scheduled task that systematically generates a backup file and sends it via email, thereby streamlining the backup process. By implementing such a script, network administrators can achieve greater reliability and peace of mind, knowing that their network configurations are securely archived and readily accessible in the event of an unforeseen failure or configuration corruption. This article delves into the intricacies of scripting within RouterOS, providing a step-by-step guide to constructing a robust automatic backup email solution tailored to the unique requirements of Mikrotik devices.
Understanding RouterOS Scripting Environment and API
The RouterOS scripting environment is a powerful tool that allows network engineers to automate a variety of tasks within MikroTik routers. It operates as an interpreted language within RouterOS, providing the capability to execute scripts that can manage configurations, monitor network status, and perform automated backups.
Scripts in RouterOS are executed in a sequential manner and can be scheduled to run at specific times or triggered by specific events. The scripting environment supports a range of commands and functions, including those for file manipulation, network monitoring, and system configuration adjustments.
To begin writing a script in RouterOS, the user must first access the terminal or use the WinBox graphical interface. In the terminal, scripts can be created and edited using the command line, while WinBox provides a more user-friendly interface for script management.
Within the terminal, the user can navigate to the script management menu by entering the command /system script
. This command provides access to various scripting options, including the ability to add, edit, and remove scripts from the system.To create a new script, the user should use the command /system script add
followed by the necessary parameters, such as name and source. The source parameter is particularly important as it contains the actual script code that will be executed.The API of RouterOS provides a method for external applications to interact with the router, allowing for even more complex automation and integration possibilities. The API operates over a TCP connection and uses a proprietary binary protocol for communication.
Before utilizing the RouterOS API, it is essential to ensure that API access is enabled on the router. This can be done by navigating to /ip service
and confirming that the API service is set to enabled.Once API access is confirmed, external applications can connect to the router using the API service port, which defaults to 8728. Proper authentication is required, typically involving a username and password with appropriate permissions.
Scripts can be designed to perform various tasks, such as sending emails, by utilizing available RouterOS functions like /tool e-mail
When writing a script to send an email, the user must configure the email settings in RouterOS, which involves specifying the SMTP server, from address, and authentication details. This is achieved by using the /tool e-mail set
command with the appropriate parameters.For enhanced security, it is advisable to use secure connections for email transmission, such as TLS or SSL, if supported by the SMTP server. This ensures that sensitive information, including backup files, is transmitted securely over the network.
To automate the backup process, the script should include commands to create a backup file. This can be done using the /system backup save
command, which generates a backup file of the current router configuration.After generating the backup file, the script should include commands to attach the file to an email and send it to the specified recipient. This involves using the /tool e-mail send
command with parameters for the recipient's email address, subject, body, and attachment file path.It's important to test the script thoroughly to ensure that it functions as expected and that emails are sent correctly with the backup file attached. Testing should include verifying that the backup file is generated correctly and that the email is delivered to the intended recipient.
Once the script is verified, it can be scheduled to run automatically using the /system scheduler
feature in RouterOS. This allows the script to execute at specified intervals, ensuring regular backups and notifications.To add a scheduled task, the user should navigate to /system scheduler
and use the add command with parameters such as name, interval, and on-event, where on-event specifies the script to be executed.By leveraging the RouterOS scripting environment and API, network engineers can create robust automation solutions that enhance the reliability and efficiency of network management tasks. This capability is particularly useful for maintaining regular backups and ensuring network configurations are preserved.
Understanding the intricacies of the scripting environment and API is crucial for effectively utilizing these tools in a MikroTik network. Mastery of these components enables the creation of custom scripts that can significantly streamline network operations and reduce manual intervention.

Configuring SMTP Settings for Secure Email Transmission
Configuring SMTP settings in MikroTik RouterOS is crucial for ensuring secure transmission of backup emails. This process involves setting up the SMTP server parameters and specifying the necessary security protocols to safeguard the email communication.
To begin, access the MikroTik router via Winbox or through the command line interface (CLI). Once logged in, navigate to the "Tools" menu and select "Email" to access the email configuration settings. In the CLI, this can be done using the command /tool e-mail
.Set the SMTP server address by using the command /tool e-mail set server
. Replace server with the actual SMTP server address, such as smtp.dominetec.local. This address is typically provided by the email service provider and is essential for routing the email messages correctly.Next, configure the SMTP port used for secure transmission. The default port for SMTP is 25, but for secure transmission, ports 465 or 587 are preferable. Use the command /tool e-mail set port=587
to specify the port number. Ensure that the chosen port aligns with the SMTP server's configuration and supports TLS or SSL encryption.Enable TLS encryption to secure the email transmission by setting the tls
parameter to yes. This can be achieved with the command /tool e-mail set tls=yes. TLS (Transport Layer Security) provides an encrypted channel, protecting the data from interception and tampering during transmission.Specify the email address that will appear as the sender in the backup emails by setting the from
parameter. Use the command /tool e-mail set from=backup@dominetec.local, replacing backup@dominetec.local with the desired sender email address. This address should be a valid and active email account that can send emails through the configured SMTP server.Configure the username and password for SMTP authentication. This is necessary for most SMTP servers to prevent unauthorized access. Use the commands /tool e-mail set user=username
After setting up the SMTP server details, test the email configuration to ensure that it works correctly. This can be done by sending a test email using the command /tool e-mail send to=recipient@dominetec.local subject="Test Email" body="This is a test email."
. Replace recipient@dominetec.local with a valid email address to receive the test message.Monitor the logs to check for any errors during the test email transmission. Access the logs through the "Log" menu in Winbox or use the command /log print
in the CLI. Look for entries related to email sending to confirm successful delivery or diagnose any issues.Adjust the SMTP settings if necessary, based on the feedback from the test email and log entries. Common issues may include incorrect server addresses, port misconfigurations, or authentication failures. Ensure that all parameters are correctly set and that the MikroTik router has internet access to reach the SMTP server.
It is also advisable to configure the router's DNS settings to ensure proper resolution of the SMTP server's domain name. Use the command /ip dns set servers=8.8.8.8,8.8.4.4
to specify reliable DNS servers, such as Google's public DNS servers. This step helps in resolving any potential issues related to domain name resolution during the email sending process.Finally, consider setting up email notifications for critical events or scheduled tasks, utilizing the configured SMTP settings. This enhances the router's monitoring capabilities and ensures timely alerts for network administrators. Proper configuration of SMTP settings is integral to maintaining the security and reliability of automated email transmissions in MikroTik RouterOS.
| Parameter | Hardware Specifications | Voltage Stats | Cable Standards |
|---|---|---|---|
| CPU Architecture | ARM, MIPSBE, TILE | N/A | N/A |
| RAM Capacity | 64MB to 2GB depending on model | N/A | N/A |
| Power Consumption | Varies by model, typically 5W to 60W | Input Voltage: 12V to 57V | N/A |
| Ethernet Ports | 10/100/1000 Mbps | N/A | Supports Cat5e, Cat6, Cat6a |
| Routing Modes | Static, RIP, OSPF, BGP | N/A | N/A |
| PoE Standards | 802.3af/at | Passive PoE: 18V to 28V | N/A |
| Wireless Standards | 802.11a/b/g/n/ac | N/A | N/A |
| Backup Methods | Local, FTP, Email | N/A | N/A |
Para entender mais detalhes, leia o artigo completo sobre configuração recomendada no blog
.Developing a Robust Backup Script with Error Handling
In configuring a Mikrotik RouterOS to automatically back up and email its configuration, it is essential to implement a script with comprehensive error handling. This ensures that backup operations are reliable and that any issues are promptly reported for corrective action. The script should be designed to handle errors gracefully, log events, and send notifications if any part of the process fails.
Begin by accessing the Mikrotik router via the command line interface (CLI) or through Winbox. The script will be created within the system scripts section, which can be accessed by navigating to System
> Scripts. Here, a new script can be added by clicking on the Add button or using the command/system script add name=BackupScript in the CLI.
The script should start by defining variables for the backup file name and email parameters. Use the :local
:local backupFileName "backup-\$[/system clock get date]-\$[/system clock get time].backup" creates a unique file name based on the current date and time.
Next, the script should execute the backup command and incorporate error checking. The command /system backup save name=\$backupFileName
:if ([/file find name=\$backupFileName] = "") do={ :log error "Backup creation failed." } to verify that the backup file was successfully created.
Once the backup file is verified, configure the email settings to send the backup. Define the email server, recipient, and other parameters using /tool e-mail set
:if ([/tool e-mail send to="admin@dominetec.local" subject="Router Backup" file=\$backupFileName] = false) do={ :log error "Email sending failed." }.
Incorporate logging throughout the script to record each step of the process. Use :log info
:log error for any failures. This will aid in troubleshooting by providing a detailed history of the script's execution. For example, log the start and end of the backup process with :log info "Backup process started." and :log info "Backup process completed successfully.".
To ensure the script runs at regular intervals, schedule it using the Scheduler
feature. Navigate to System > Scheduler and create a new task that executes the script. Set the interval according to your backup policy, such as daily or weekly. Use the command/system scheduler add name=BackupSchedule interval=1d on-event=BackupScript to automate the script execution every day.
Finally, test the entire process thoroughly to ensure reliability. Manually run the script from the CLI using /system script run BackupScript
By following these steps, a robust Mikrotik RouterOS backup script with error handling can be developed, ensuring that network configurations are regularly and securely backed up. Proper implementation of error handling and logging will facilitate quick identification and resolution of any issues, maintaining the integrity and availability of network configurations.

Automating Script Execution with Scheduled Tasks
To ensure the automatic execution of the Mikrotik backup email script, it is essential to configure scheduled tasks within RouterOS. This process involves creating a schedule that triggers the execution of the script at predefined intervals, ensuring that backups are consistently generated and emailed without manual intervention.
Begin by accessing the Mikrotik RouterOS interface, either through the Winbox utility or via SSH for command-line access. Navigate to the System
menu and select Scheduler to open the scheduling configuration panel.In the Scheduler configuration, click on the Add New
button to create a new scheduled task. Assign a descriptive name to the schedule for easy identification, such as AutoBackupEmail.Next, set the Interval
field to define how frequently the script should run. For daily execution, set the interval to 1d, which represents one day.In the Start Time
field, specify the time of day when the script should first execute. This can be set to a time when network activity is low, such as 02:00:00 for 2 AM.The On Event
field requires the exact script name that was previously created for the backup and email process. Enter the script name, ensuring it matches the name configured in the /system script section.For example, if the script is named BackupEmailScript
, the On Event field should contain BackupEmailScript. This links the scheduler to the specific script intended for execution.To ensure the task is active, verify that the Enabled
checkbox is selected. This setting ensures that the schedule is operational and ready to trigger the script as configured.After configuring the schedule, click OK
or Apply to save the changes. The scheduled task will now appear in the list, along with its status and next execution time.For command-line configuration, use the following syntax to create the scheduled task:
- /system scheduler add name=AutoBackupEmail interval=1d start-time=02:00:00 on-event=BackupEmailScript
This command line mirrors the GUI configuration, setting the interval, start time, and linking the script by name. Ensure the command is entered accurately to avoid execution errors.
It is advisable to test the scheduled task to confirm it triggers the script as expected. Manually adjust the start time temporarily to a few minutes ahead of the current time and observe if the script executes.
Monitor the Log
section under System to verify the script execution and email dispatch. Successful execution logs will confirm the task is functioning correctly.Should any issues arise, check the script for errors or misconfigurations. Ensure the email settings, such as SMTP server and recipient address, are correctly specified in the script.
Regularly review the scheduled tasks and script logs to ensure ongoing reliability and to address any potential issues promptly. This proactive maintenance helps sustain the automated backup and email process, securing network configurations effectively.
Recomenda-se também a leitura do guia sobre boas práticas de infraestrutura física e lógica
Testing and Validating Email Backup Functionality in Diverse Network Scenarios
To ensure the reliability of the Mikrotik automatic backup email script, it is crucial to conduct a series of tests across various network scenarios. This involves verifying the script's performance in different network environments and under varying conditions to ensure consistent operation.
Step 1: Configuring the Email Settings
Begin by accessing the Mikrotik RouterOS interface through Winbox or a terminal session. Navigate to System
> Email to set up the email server configuration. Enter the SMTP server address, port, and authentication details such as the username and password.Use the following command-line example to configure email settings:
/tool e-mail set address=smtp.dominetec.local port=587 user=user@dominetec.local password=yourpassword from=user@dominetec.local
Step 2: Script Implementation
Create the backup script by navigating to System
> Scripts in the RouterOS interface. Add a new script with a descriptive name, such as "AutoBackupEmail".Input the script code, which includes commands to create a backup file, save it locally, and send it via email. An example script might look like this:
/system backup save name=auto-backup; /tool e-mail send to=recipient@dominetec.local subject="Router Backup" file=auto-backup.backup
Step 3: Testing in a Stable Network Environment
Conduct initial tests in a stable network environment to verify basic functionality. Ensure that the router has a stable internet connection and that the email server is accessible.
Run the script manually using the command-line interface:
/system script run AutoBackupEmail
Check the email account to confirm the receipt of the backup file. Verify that the file is complete and not corrupted.
Step 4: Validating in a High-Latency Network
Simulate a high-latency network environment by introducing artificial delays using network emulation tools. This can be done by configuring queue trees or using third-party network simulators.
Execute the backup script again and monitor the time taken for the email to be sent. Ensure that the script handles delays gracefully without timing out or failing.
Step 5: Testing Under Network Congestion
Introduce network congestion by generating additional traffic on the network. This can be achieved by using bandwidth-consuming applications or network stress testing tools.
Run the backup script and observe its behavior under congested conditions. Confirm that the email is still sent successfully and that the backup file remains intact.
Step 6: Evaluating in a Unstable Network
Simulate an unstable network by intermittently disconnecting the internet connection or altering the network topology. This can be performed by disconnecting cables or disabling interfaces temporarily.
Trigger the script execution and verify its ability to retry sending the email after a connection is restored. Ensure that the script logs any failures and attempts to resend the backup.
Step 7: Security and Authentication Testing
Test the script's ability to handle various authentication mechanisms supported by the SMTP server. This includes testing with plain text, SSL/TLS, and STARTTLS protocols.
Modify the email configuration to accommodate different security settings and validate the script's compatibility with each. Confirm that the backup email is sent securely without exposing sensitive information.
Step 8: Logging and Monitoring
Implement logging within the script to capture detailed information about each execution attempt. Use the /log
Review the logs to identify any anomalies or errors during the email sending process. Utilize monitoring tools to alert administrators in case of failures or repeated issues.
Step 9: Final Validation and Documentation
Conduct a final validation test in a production-like environment to ensure the script's readiness for deployment. Confirm that all previous issues have been resolved and that the script operates reliably.
Document the test results, including any modifications made to the script or network configurations. Provide a comprehensive report to stakeholders outlining the script's performance and reliability.
By following these steps, network engineers can thoroughly test and validate the Mikrotik automatic backup email script across diverse network scenarios, ensuring robust and reliable functionality.

Frequently Asked Questions (FAQ)
How do I create an automatic backup script in Mikrotik RouterOS?
To create an automatic backup script in Mikrotik RouterOS, access the terminal and use the "/system script add" command to define a new script. The script should include commands to generate a backup file using "/system backup save" and specify a filename with a timestamp to avoid overwriting previous backups.
How can I configure Mikrotik to automatically email the backup file?
To configure automatic email of the backup file, use the "/tool e-mail send" command within the script. Ensure your Mikrotik is configured with a valid SMTP server under "/tool e-mail" settings and include parameters for recipient, subject, and attachment of the backup file.
What steps are necessary to schedule the backup script in Mikrotik?
Schedule the backup script by using the "/system scheduler add" command. Define the interval or specific time for execution and reference the script by its name to ensure it runs automatically at the desired times.
How can I verify that the backup email script is functioning correctly?
To verify functionality, manually run the script using "/system script run" and check the email account for the backup file. Review the Mikrotik logs for any errors related to script execution or email delivery issues.



