Skip to content

Instantly share code, notes, and snippets.

@sebastian13
Last active June 24, 2024 23:34
Show Gist options
  • Save sebastian13/3b05cbbbdd3326a402391e81e1a8f7af to your computer and use it in GitHub Desktop.
Save sebastian13/3b05cbbbdd3326a402391e81e1a8f7af to your computer and use it in GitHub Desktop.
Backup & Auto Upgrade Mikrotik RouterOS

Backup & Auto Upgrade Mikrotik Routers

  1. Set SMTP
/tool e-mail
set address=smtp.gmail.com [email protected] port=587 tls=starttls \
    [email protected] password=___
  1. Create the 3 scripts, named backup2mail, upgrade-firmware, upgrade-routeros

  2. Create schedulers

/system scheduler
add name=upgrade-routeros on-event=upgrade-routeros start-time=04:00:00 interval=1d
add name=upgrade-firmware on-event=":delay 30s\n/system script run upgrade-firmware" start-time=startup
add name=backup2mail on-event=backup2mail start-time=06:00:00 interval=4w
:local recipient
:set recipient "__@__.com"
:local BackupPassword "___";
:global Identity [ / system identity get name ];
:log info message="Creating a cloud backup and sending export compact to $recipient"
# Export Compact
:put "Create export compact"
/export compact file=export-compact
:delay 10s;
# Cloud-Backup
:do {
:if ([ /system backup cloud print count-only ] > 0) do={
:put "Create, upload and replace cloud backup."
/system backup cloud upload-file action=create-and-upload \
password=$BackupPassword replace=[ get ([ find ]->0) name ];
} else={
:put "Create a new cloud backup."
/system backup cloud upload-file action=create-and-upload \
password=$BackupPassword;
}
} on-error={
:error "Cloud Backup failed for $Identity failed."
}
# Get latest Cloud-Backup Details
:local backupn [/system backup cloud get 0 name ];
:local backupk [/system backup cloud get 0 secret-download-key ];
:local backupd [/system backup cloud get 0 date ];
:local backupr [/system backup cloud get 0 ros-version ];
:local backups [/system backup cloud get 0 size ];
# Send E-Mail
/tool e-mail send to=$recipient \
subject="Export-Compact | $Identity" \
body="A Cloud-Backup was created for $Identity. A compact export is attached.\n\nName: $backupn \nDate: $backupd \nRouterOS: $backupr \nSize: $backups \nDownload key: $backupk \n" \
file=export-compact.rsc
:delay 10s;
/file remove export-compact
:log info "Checking firmware...";
/system routerboard
:if ([get current-firmware] != [get upgrade-firmware]) do={
:log info "Updating firmware";
upgrade;
# Automatic restart
:delay 10s
/system reboot
} else={
:log info "No firmware update needed."
}
:log info message="Checking for RouterOS Updates"
/system package update
check-for-updates once
:delay 5s;
:if ( [get status] = "New version is available") do={
/system script run backup2mail
/system package update install
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment