MikroTik backup script

In this article, I will give an example of a script for backing up the configuration of MikroTik devices.

The script will be run in the Linux operating system, the MiroTik configuration file will be transmitted via SSH (SCP), so it is better to connect using a key rather than a password. But since there are many devices, they change, I decided to use a password so that one day I do not forget to copy the key to a new MikroTik device, and also not to waste time on it.

Content of my script:

#ssh-keygen -f "/root/.ssh/known_hosts" -R
sshpass -p $PASS ssh admin@ export file=ixnfo
sshpass -p $PASS scp -oStrictHostKeyChecking=no admin@ /backups/mikrotik/`date +%Y%m%d-`office.rsc
find /backups/mikrotik/ -type f -mtime +90 -exec rm {} \;

The command “ssh-keygen -f” removes a device from the list of known devices, this is necessary when a valid device has been replaced with a new one and the IP address of the old device is assigned to it, if this is not done, there will be a connection error.
The following command in the script connects to the device and creates a text copy of the configuration to the ixnfo.rsc file.
Then, through the scp command, it reconnects to the device and downloads this file to the desired directory.
The last command searches for files older than 90 days and deletes them so that the disk system does not run out of memory.

To make the script automatically run every day, for example at night at 1:14, add the line below to /etc/crontab:

14 1 * * * root /backups/scripts/backup_cfg_mikrotik.sh > /dev/null 2>&1

Also in the IP – Services menu, in the “Available From” field, we will allow connection to SSH only from trusted IP addresses. I will also give an example of a command:

/ip service
set ssh address=,

Or, in the IP – Firewall menu, we will allow connection to SSH only from trusted IP addresses, I will give an example of the command:

/ip firewall filter
add action=accept chain=input dst-port=22 protocol=tcp src-address=

See also my articles:

Leave a comment

Leave a Reply