查看: 690|回复: 0

[Mikrotik Ros] Mikrotik RouterOS自动备份和更新

[复制链接]

124

主题

0

回帖

508

积分

管理员

积分
508
发表于 2026-8-20 21:42:39 | 显示全部楼层 |阅读模式
1.配置参数
获取 脚本并在文件开头配置其参数。
此步骤很简单,因为所有参数都有很好的注释。 重要!不要忘记提供正确的电子邮件地址以进行备份并注意scriptMode变量。

2. 创建新脚本
系统 -> 脚本 [添加]

重要!脚本名称必须是将BackupAndUpdate
您先前配置的脚本插入到源区域。


  1. # Script name: BackupAndUpdate
  2. #
  3. #----------SCRIPT INFORMATION---------------------------------------------------
  4. #
  5. # Script:  Mikrotik RouterOS automatic backup & update
  6. # Version: 24.06.04
  7. # Created: 07/08/2018
  8. # Updated: 04/06/2024
  9. # You can contact me by e-mail at tebiev@mail.com
  10. #
  11. # IMPORTANT!
  12. # Minimum supported RouterOS version is v6.43.7
  13. #
  14. #----------MODIFY THIS SECTION AS NEEDED----------------------------------------
  15. ## Notification e-mail
  16. ## (Make sure you have configurated Email settings in Tools -> Email)
  17. :local emailAddress "这里修改成你的邮箱地址xxxxx@qq.com";

  18. ## Script mode, possible values: backup, osupdate, osnotify.
  19. # backup    -   Only backup will be performed. (default value, if none provided)
  20. #
  21. # osupdate  -   The script will install a new RouterOS version if it is available.
  22. #               It will also create backups before and after update process (it does not matter what value `forceBackup` is set to)
  23. #               Email will be sent only if a new RouterOS version is available.
  24. #               Change parameter `forceBackup` if you need the script to create backups every time when it runs (even when no updates were found).
  25. #
  26. # osnotify  -   The script will send email notifications only (without backups) if a new RouterOS update is available.
  27. #               Change parameter `forceBackup` if you need the script to create backups every time when it runs.
  28. :local scriptMode "osupdate";

  29. ## Additional parameter if you set `scriptMode` to `osupdate` or `osnotify`
  30. # Set `true` if you want the script to perform backup every time it's fired, whatever script mode is set.
  31. :local forceBackup false;

  32. ## Backup encryption password, no encryption if no password.
  33. :local backupPassword ""

  34. ## If true, passwords will be included in exported config.
  35. :local sensitiveDataInConfig true;

  36. ## Update channel. Possible values: stable, long-term, testing, development
  37. :local updateChannel "stable";

  38. ## Installs only patch versions of RouterOS updates.
  39. ## Works only if you set scriptMode to "osupdate"
  40. ## Means that new update will be installed only if MAJOR and MINOR version numbers remained the same as currently installed RouterOS.
  41. ## Example: v6.43.6 => major.minor.PATCH
  42. ## Script will send information if new version is greater than just patch.
  43. :local installOnlyPatchUpdates false;

  44. ## If true, device public IP address information will be included into the email message
  45. :local detectPublicIpAddress true;

  46. ## Allow anonymous statistics collection. (script mode, device model, OS version)
  47. :local allowAnonymousStatisticsCollection true;

  48. ##------------------------------------------------------------------------------------------##
  49. #  !!!! DO NOT CHANGE ANYTHING BELOW THIS LINE, IF YOU ARE NOT SURE WHAT YOU ARE DOING !!!!  #
  50. ##------------------------------------------------------------------------------------------##

  51. #Script messages prefix
  52. :local SMP "Bkp&Upd:"

  53. :log info "\r\n$SMP script "Mikrotik RouterOS automatic backup & update" started.";
  54. :log info "$SMP Script Mode: $scriptMode, forceBackup: $forceBackup";

  55. # Check email settings
  56. :if ([:len $emailAddress] = 0) do={
  57.     :log error ("$SMP \$emailAddress variable is empty. Script stopped.");
  58.     :error "$SMP bye!";
  59. }
  60. :local emailServer ""
  61. :do {
  62.     :set emailServer [/tool e-mail get server];
  63. } on-error={
  64.     # Old of getting email server before the RouterOS v7.12
  65.     :log info "$SMP Checking email server using old command `/tool e-mail get address`";
  66.     :set emailServer [/tool e-mail get address];
  67. }
  68. :if ($emailServer = "0.0.0.0") do={
  69.     :log error ("$SMP Email server address is not correct, please check Tools -> Email. Script stopped.");
  70.     :error "$SMP bye!";
  71. }
  72. :if ([:len [/tool e-mail get from]] = 0 or [/tool e-mail get from] = "<>") do={
  73.     :log error ("$SMP Email configuration FROM address is not correct, please check Tools -> Email. Script stopped.");
  74.     :error "$SMP bye!";
  75. }


  76. #Check if proper identity name is set
  77. if ([:len [/system identity get name]] = 0 or [/system identity get name] = "MikroTik") do={
  78.     :log warning ("$SMP Please set identity name of your device (System -> Identity), keep it short and informative.");
  79. };

  80. ############### vvvvvvvvv GLOBALS vvvvvvvvv ###############
  81. # Function converts standard mikrotik build versions to the number.
  82. # Possible arguments: paramOsVer
  83. # Example:
  84. # :put [$buGlobalFuncGetOsVerNum paramOsVer=[/system routerboard get current-RouterOS]];
  85. # Result will be: 64301, because current RouterOS version is: 6.43.1
  86. :global buGlobalFuncGetOsVerNum do={
  87.     :local osVer $paramOsVer;
  88.     :local osVerNum;
  89.     :local osVerMicroPart;
  90.     :local zro 0;
  91.     :local tmp;

  92.     # Replace word `beta` with dot
  93.     :local isBetaPos [:tonum [:find $osVer "beta" 0]];
  94.     :if ($isBetaPos > 1) do={
  95.         :set osVer ([:pick $osVer 0 $isBetaPos] . "." . [:pick $osVer ($isBetaPos + 4) [:len $osVer]]);
  96.     }
  97.     # Replace word `rc` with dot
  98.     :local isRcPos [:tonum [:find $osVer "rc" 0]];
  99.     :if ($isRcPos > 1) do={
  100.         :set osVer ([:pick $osVer 0 $isRcPos] . "." . [:pick $osVer ($isRcPos + 2) [:len $osVer]]);
  101.     }

  102.     :local dotPos1 [:find $osVer "." 0];

  103.     :if ($dotPos1 > 0) do={

  104.         # AA
  105.         :set osVerNum  [:pick $osVer 0 $dotPos1];

  106.         :local dotPos2 [:find $osVer "." $dotPos1];
  107.                 #Taking minor version, everything after first dot
  108.         :if ([:len $dotPos2] = 0) do={:set tmp [:pick $osVer ($dotPos1+1) [:len $osVer]];}
  109.         #Taking minor version, everything between first and second dots
  110.         :if ($dotPos2 > 0) do={:set tmp [:pick $osVer ($dotPos1+1) $dotPos2];}

  111.         # AA 0B
  112.         :if ([:len $tmp] = 1) do={:set osVerNum "$osVerNum$zro$tmp";}
  113.         # AA BB
  114.         :if ([:len $tmp] = 2) do={:set osVerNum "$osVerNum$tmp";}

  115.         :if ($dotPos2 > 0) do={
  116.             :set tmp [:pick $osVer ($dotPos2+1) [:len $osVer]];
  117.             # AA BB 0C
  118.             :if ([:len $tmp] = 1) do={:set osVerNum "$osVerNum$zro$tmp";}
  119.             # AA BB CC
  120.             :if ([:len $tmp] = 2) do={:set osVerNum "$osVerNum$tmp";}
  121.         } else={
  122.             # AA BB 00
  123.             :set osVerNum "$osVerNum$zro$zro";
  124.         }
  125.     } else={
  126.         # AA 00 00
  127.         :set osVerNum "$osVer$zro$zro$zro$zro";
  128.     }

  129.     :return $osVerNum;
  130. }


  131. # Function creates backups (system and config) and returns array with names
  132. # Possible arguments:
  133. #    `backupName`               | string    | backup file name, without extension!
  134. #    `backupPassword`           | string    |
  135. #    `sensitiveDataInConfig`    | boolean   |
  136. # Example:
  137. # :put [$buGlobalFuncCreateBackups name="daily-backup"];
  138. :global buGlobalFuncCreateBackups do={
  139.     :log info ("$SMP Global function "buGlobalFuncCreateBackups" was fired.");

  140.     :local backupFileSys "$backupName.backup";
  141.     :local backupFileConfig "$backupName.rsc";
  142.     :local backupNames {$backupFileSys;$backupFileConfig};

  143.     ## Make system backup
  144.     :if ([:len $backupPassword] = 0) do={
  145.         /system backup save dont-encrypt=yes name=$backupName;
  146.     } else={
  147.         /system backup save password=$backupPassword name=$backupName;
  148.     }
  149.     :log info ("$SMP System backup created. $backupFileSys");

  150.     ## Export config file
  151.     :if ($sensitiveDataInConfig = true) do={
  152.         # Since RouterOS v7 it needs to be explicitly set that we want to export sensitive data
  153.         :if ([:pick [/system package update get installed-version] 0 1] < 7) do={
  154.             :execute "/export compact terse file=$backupName";
  155.         } else={
  156.             :execute "/export compact show-sensitive terse file=$backupName";
  157.         }
  158.     } else={
  159.         /export compact hide-sensitive terse file=$backupName;
  160.     }
  161.     :log info ("$SMP Config file was exported. $backupFileConfig, the script execution will be paused for a moment.");

  162.     #Delay after creating backups
  163.     :delay 20s;
  164.     :return $backupNames;
  165. }

  166. :global buGlobalVarUpdateStep;
  167. ############### ^^^^^^^^^ GLOBALS ^^^^^^^^^ ###############

  168. :local scriptVersion "23.11.25";

  169. # Current time `hh-mm-ss`
  170. :local currentTime ([:pick [/system clock get time] 0 2] . "-" . [:pick [/system clock get time] 3 5] . "-" . [:pick [/system clock get time] 6 8]);

  171. :local currentDateTime ("-" . $currentTime);

  172. # Detect old date format, Example: `nov/11/2023`
  173. :if ([:len [:tonum [:pick [/system clock get date] 0 1]]] = 0) do={
  174.     :set currentDateTime ([:pick [/system clock get date] 7 11] . [:pick [/system clock get date] 0 3] . [:pick [/system clock get date] 4 6] . "-" . $currentTime);
  175. } else={
  176.     # New date format, Example: `2023-11-11`
  177.     :set currentDateTime ([/system clock get date] . "-" . $currentTime);
  178. };

  179. :local isSoftBased false;
  180. :if ([:pick [/system resource get board-name] 0 3] = "CHR" or [:pick [/system resource get board-name] 0 3] = "x86") do={
  181.     :set isSoftBased true;
  182. };

  183. :local deviceOsVerInst          [/system package update get installed-version];
  184. :local deviceOsVerInstNum       [$buGlobalFuncGetOsVerNum paramOsVer=$deviceOsVerInst];
  185. :local deviceOsVerAvail         "";
  186. :local deviceOsVerAvailNum      0;
  187. :local deviceIdentityName       [/system identity get name];
  188. :local deviceIdentityNameShort  [:pick $deviceIdentityName 0 18]
  189. :local deviceUpdateChannel      [/system package update get channel];


  190. :local deviceRbModel            "CloudHostedRouter";
  191. :local deviceRbSerialNumber     "--";
  192. :local deviceRbCurrentFw        "--";
  193. :local deviceRbUpgradeFw        "--";

  194. :if ($isSoftBased = false) do={
  195.     :set deviceRbModel          [/system routerboard get model];
  196.     :set deviceRbSerialNumber   [/system routerboard get serial-number];
  197.     :set deviceRbCurrentFw      [/system routerboard get current-firmware];
  198.     :set deviceRbUpgradeFw      [/system routerboard get upgrade-firmware];
  199. };

  200. :local isOsUpdateAvailable false;
  201. :local isOsNeedsToBeUpdated false;

  202. :local isSendEmailRequired true;

  203. :local mailSubject  "$SMP Device - $deviceIdentityNameShort.";
  204. :local mailBody     "";

  205. :local mailBodyDeviceInfo   "\r\n\r\nDevice information: \r\nIdentity: $deviceIdentityName \r\nModel: $deviceRbModel \r\nSerial number: $deviceRbSerialNumber \r\nCurrent RouterOS: $deviceOsVerInst ($[/system package update get channel]) $[/system resource get build-time] \r\nCurrent routerboard FW: $deviceRbCurrentFw \r\nDevice uptime: $[/system resource get uptime]";
  206. :local mailBodyCopyright    "\r\n\r\nMikrotik RouterOS automatic backup & update (ver. $scriptVersion) \r\nhttps://github.com/beeyev/Mikrotik-RouterOS-automatic-backup-and-update";
  207. :local changelogUrl         ("Check RouterOS changelog: https://mikrotik.com/download/changelogs/" . $updateChannel . "-release-tree");

  208. :local backupName           "v$deviceOsVerInst_$deviceUpdateChannel_$currentDateTime";
  209. :local backupNameBeforeUpd  "backup_before_update_$backupName";
  210. :local backupNameAfterUpd   "backup_after_update_$backupName";

  211. :local backupNameFinal  $backupName;
  212. :local mailAttachments  [:toarray ""];


  213. :local ipAddressDetectServiceDefault "https://ipv4.mikrotik.ovh/"
  214. :local ipAddressDetectServiceFallback "https://api.ipify.org/"
  215. :local publicIpAddress "not detected";
  216. :local telemetryDataQuery "";

  217. :local updateStep $buGlobalVarUpdateStep;
  218. :do {/system script environment remove buGlobalVarUpdateStep;} on-error={}
  219. :if ([:len $updateStep] = 0) do={
  220.     :set updateStep 1;
  221. }

  222. ## IP address detection & anonymous statistics collection
  223. :if ($updateStep = 1 or $updateStep = 3) do={
  224.     :if ($updateStep = 3) do={
  225.         :log info ("$SMP Waiting for one minute before continuing to the final step.");
  226.         :delay 1m;
  227.     }

  228.     :if ($detectPublicIpAddress = true or $allowAnonymousStatisticsCollection = true) do={
  229.         :if ($allowAnonymousStatisticsCollection = true) do={
  230.             :set telemetryDataQuery ("\?mode=" . $scriptMode . "&osver=" . $deviceOsVerInst . "&model=" . $deviceRbModel);
  231.         }

  232.         :do {:set publicIpAddress ([/tool fetch http-method="get" url=($ipAddressDetectServiceDefault . $telemetryDataQuery) output=user as-value]->"data");} on-error={

  233.             :if ($detectPublicIpAddress = true) do={
  234.                 :log warning "$SMP Could not detect public IP address using default detection service."
  235.                 :log warning "$SMP Trying to detect public ip using fallback detection service."

  236.                 :do {:set publicIpAddress ([/tool fetch http-method="get" url=$ipAddressDetectServiceFallback output=user as-value]->"data");} on-error={
  237.                     :log warning "$SMP Could not detect public IP address using fallback detection service."
  238.                 }
  239.             }
  240.         }

  241.         :if ($detectPublicIpAddress = true) do={
  242.             # Always truncate the string for safety measures
  243.             :set publicIpAddress ([:pick $publicIpAddress 0 15])
  244.             :set mailBodyDeviceInfo ($mailBodyDeviceInfo . "\r\nPublic IP address: " . $publicIpAddress);
  245.         }
  246.     }
  247. }


  248. ## STEP ONE: Creating backups, checking for new RouterOs version and sending email with backups,
  249. ## Steps 2 and 3 are fired only if script is set to automatically update device and if a new RouterOs version is available.
  250. :if ($updateStep = 1) do={
  251.     :log info ("$SMP Performing the first step.");

  252.     # Checking for new RouterOS version
  253.     if ($scriptMode = "osupdate" or $scriptMode = "osnotify") do={
  254.         log info ("$SMP Checking for new RouterOS version. Current version is: $deviceOsVerInst");
  255.         /system package update set channel=$updateChannel;
  256.         /system package update check-for-updates;
  257.         :delay 5s;
  258.         :set deviceOsVerAvail [/system package update get latest-version];

  259.         # If there is a problem getting information about available RouterOS versions from server
  260.         :if ([:len $deviceOsVerAvail] = 0) do={
  261.             :log warning ("$SMP There is a problem getting information about new RouterOS from server.");
  262.             :set mailSubject    ($mailSubject . " Error: No data about new RouterOS!")
  263.             :set mailBody         ($mailBody . "Error occured! \r\nMikrotik couldn't get any information about new RouterOS from server! \r\nWatch additional information in device logs.")
  264.         } else={
  265.             #Get numeric version of OS
  266.             :set deviceOsVerAvailNum [$buGlobalFuncGetOsVerNum paramOsVer=$deviceOsVerAvail];

  267.             # Checking if OS on server is greater than installed one.
  268.             :if ($deviceOsVerAvailNum > $deviceOsVerInstNum) do={
  269.                 :set isOsUpdateAvailable true;
  270.                 :log info ("$SMP New RouterOS is available! $deviceOsVerAvail");
  271.             } else={
  272.                 :set isSendEmailRequired false;
  273.                 :log info ("$SMP System is already up to date.");
  274.                 :set mailSubject ($mailSubject . " No new OS updates.");
  275.                 :set mailBody      ($mailBody . "Your system is up to date.");
  276.             }
  277.         };
  278.     } else={
  279.         :set scriptMode "backup";
  280.     };

  281.     if ($forceBackup = true) do={
  282.         # In this case the script will always send an email, because it has to create backups
  283.         :set isSendEmailRequired true;
  284.     }

  285.     # If a new OS version is available to install
  286.     if ($isOsUpdateAvailable = true and $isSendEmailRequired = true) do={
  287.         # If we only need to notify about a new available version
  288.         if ($scriptMode = "osnotify") do={
  289.             :set mailSubject    ($mailSubject . " New RouterOS is available! v.$deviceOsVerAvail.")
  290.             :set mailBody       ($mailBody . "New RouterOS version is available to install: v.$deviceOsVerAvail ($updateChannel) \r\n$changelogUrl")
  291.         }

  292.         # If we need to initiate RouterOS update process
  293.         if ($scriptMode = "osupdate") do={
  294.             :set isOsNeedsToBeUpdated true;
  295.             # If we need to install only patch updates
  296.             :if ($installOnlyPatchUpdates = true) do={
  297.                 #Check if Major and Minor builds are the same.
  298.                 :if ([:pick $deviceOsVerInstNum 0 ([:len $deviceOsVerInstNum]-2)] = [:pick $deviceOsVerAvailNum 0 ([:len $deviceOsVerAvailNum]-2)]) do={
  299.                     :log info ("$SMP New patch version of RouterOS firmware is available.");
  300.                 } else={
  301.                     :log info           ("$SMP New major or minor version of RouterOS firmware is available. You need to update it manually.");
  302.                     :set mailSubject    ($mailSubject . " New RouterOS: v.$deviceOsVerAvail needs to be installed manually.");
  303.                     :set mailBody       ($mailBody . "New major or minor RouterOS version is available to install: v.$deviceOsVerAvail ($updateChannel). \r\nYou chose to automatically install only patch updates, so this major update you need to install manually. \r\n$changelogUrl");
  304.                     :set isOsNeedsToBeUpdated false;
  305.                 }
  306.             }

  307.             #Check again, because this variable could be changed during checking for installing only patch updats
  308.             if ($isOsNeedsToBeUpdated = true) do={
  309.                 :log info           ("$SMP New RouterOS is going to be installed! v.$deviceOsVerInst -> v.$deviceOsVerAvail");
  310.                 :set mailSubject    ($mailSubject . " New RouterOS is going to be installed! v.$deviceOsVerInst -> v.$deviceOsVerAvail.");
  311.                 :set mailBody       ($mailBody . "Your Mikrotik will be updated to the new RouterOS version from v.$deviceOsVerInst to v.$deviceOsVerAvail (Update channel: $updateChannel) \r\nA final report with detailed information will be sent once the update process is completed. \r\nIf you do not receive a second email within the next 10 minutes, there may be an issue. Please check your device logs for further information.");
  312.                 #!! There is more code connected to this part and first step at the end of the script.
  313.             }

  314.         }
  315.     }

  316.     ## Checking If the script needs to create a backup
  317.     :log info ("$SMP Checking If the script needs to create a backup.");
  318.     if ($forceBackup = true or $scriptMode = "backup" or $isOsNeedsToBeUpdated = true) do={
  319.         :log info ("$SMP Creating system backups.");
  320.         if ($isOsNeedsToBeUpdated = true) do={
  321.             :set backupNameFinal $backupNameBeforeUpd;
  322.         };
  323.         if ($scriptMode != "backup") do={
  324.             :set mailBody ($mailBody . "\r\n\r\n");
  325.         };

  326.         :set mailSubject    ($mailSubject . " Backup was created.");
  327.         :set mailBody       ($mailBody . "System backups were created and attached to this email.");

  328.         :set mailAttachments [$buGlobalFuncCreateBackups backupName=$backupNameFinal backupPassword=$backupPassword sensitiveDataInConfig=$sensitiveDataInConfig];
  329.     } else={
  330.         :log info ("$SMP Creating a backup is not necessary.");
  331.     }

  332.     # Combine first step email
  333.     :set mailBody ($mailBody . $mailBodyDeviceInfo . $mailBodyCopyright);
  334. }

  335. ## STEP TWO: (after first reboot) routerboard firmware upgrade
  336. ## Steps 2 and 3 are fired only if script is set to automatically update device and if new RouterOs is available.
  337. :if ($updateStep = 2) do={
  338.     :log info ("$SMP Performing the second step.");
  339.     ## RouterOS is the latest, let's check for upgraded routerboard firmware
  340.     if ($deviceRbCurrentFw != $deviceRbUpgradeFw) do={
  341.         :set isSendEmailRequired false;
  342.         :delay 10s;
  343.         :log info "$SMP Upgrading routerboard firmware from v.$deviceRbCurrentFw to v.$deviceRbUpgradeFw";
  344.         ## Start the upgrading process
  345.         /system routerboard upgrade;
  346.         ## Wait until the upgrade is completed
  347.         :delay 5s;
  348.         :log info "$SMP routerboard upgrade process was completed, going to reboot in a moment!";
  349.         ## Set scheduled task to send final report on the next boot, task will be deleted when it is done. (That is why you should keep original script name)
  350.         /system scheduler add name=BKPUPD-FINAL-REPORT-ON-NEXT-BOOT on-event=":delay 5s; /system scheduler remove BKPUPD-FINAL-REPORT-ON-NEXT-BOOT; :global buGlobalVarUpdateStep 3; :delay 10s; /system script run BackupAndUpdate;" start-time=startup interval=0;
  351.         ## Reboot system to boot with new firmware
  352.         /system reboot;
  353.     } else={
  354.         :log info "$SMP It appears that your routerboard is already up to date, skipping this step.";
  355.         :set updateStep 3;
  356.     };
  357. }

  358. ## STEP THREE: Last step (after second reboot) sending final report
  359. ## Steps 2 and 3 are fired only if script is set to automatically update device and if new RouterOs is available.
  360. ## This step is executed after some delay
  361. :if ($updateStep = 3) do={
  362.     :log info ("$SMP Performing the third step.");
  363.     :log info "Bkp&Upd: RouterOS and routerboard upgrade process was completed. New RouterOS version: v.$deviceOsVerInst, routerboard firmware: v.$deviceRbCurrentFw.";
  364.     ## Small delay in case mikrotik needs some time to initialize connections
  365.     :log info "$SMP Sending the final email with report and backups.";
  366.     :set mailSubject    ($mailSubject . " RouterOS Upgrade is completed, new version: v.$deviceOsVerInst!");
  367.     :set mailBody       "RouterOS and routerboard upgrade process was completed. \r\nNew RouterOS version: v.$deviceOsVerInst, routerboard firmware: v.$deviceRbCurrentFw. \r\n$changelogUrl \r\n\r\nBackups of the upgraded system are in the attachment of this email.  $mailBodyDeviceInfo $mailBodyCopyright";
  368.     :set mailAttachments [$buGlobalFuncCreateBackups backupName=$backupNameAfterUpd backupPassword=$backupPassword sensitiveDataInConfig=$sensitiveDataInConfig];
  369. }

  370. # Remove functions from global environment to keep it fresh and clean.
  371. :do {/system script environment remove buGlobalFuncGetOsVerNum;} on-error={}
  372. :do {/system script environment remove buGlobalFuncCreateBackups;} on-error={}

  373. ##
  374. ## SENDING EMAIL
  375. ##
  376. # Trying to send email with backups as attachments.

  377. :if ($isSendEmailRequired = true) do={
  378.     :log info "$SMP Dispatching email message; estimated completion within 30 seconds.";
  379.     :do {/tool e-mail send to=$emailAddress subject=$mailSubject body=$mailBody file=$mailAttachments;} on-error={
  380.         :delay 5s;
  381.         :log error "$SMP could not send email message ($[/tool e-mail get last-status]). Will attempt redelivery shortly."

  382.         :delay 5m;

  383.         :do {/tool e-mail send to=$emailAddress subject=$mailSubject body=$mailBody file=$mailAttachments;} on-error={
  384.             :delay 5s;
  385.             :log error "$SMP failed to send email message ($[/tool e-mail get last-status]) for the second time."

  386.             if ($isOsNeedsToBeUpdated = true) do={
  387.                 :set isOsNeedsToBeUpdated false;
  388.                 :log warning "$SMP script is not going to initialise update process due to inability to send backups to email."
  389.             }
  390.         }
  391.     }

  392.     :delay 30s;

  393.     :if ([:len $mailAttachments] > 0 and [/tool e-mail get last-status] = "succeeded") do={
  394.         :log info "$SMP File system cleanup."
  395.         /file remove $mailAttachments;
  396.         :delay 2s;
  397.     }

  398. }


  399. # Fire RouterOS update process
  400. if ($isOsNeedsToBeUpdated = true) do={

  401.     :if ($isSoftBased = false) do={
  402.         ## Set scheduled task to upgrade routerboard firmware on the next boot, task will be deleted when upgrade is done. (That is why you should keep original script name)
  403.         /system scheduler add name=BKPUPD-UPGRADE-ON-NEXT-BOOT on-event=":delay 5s; /system scheduler remove BKPUPD-UPGRADE-ON-NEXT-BOOT; :global buGlobalVarUpdateStep 2; :delay 10s; /system script run BackupAndUpdate;" start-time=startup interval=0;
  404.     } else= {
  405.         ## If the script is executed on CHR, step 2 will be skipped
  406.         /system scheduler add name=BKPUPD-UPGRADE-ON-NEXT-BOOT on-event=":delay 5s; /system scheduler remove BKPUPD-UPGRADE-ON-NEXT-BOOT; :global buGlobalVarUpdateStep 3; :delay 10s; /system script run BackupAndUpdate;" start-time=startup interval=0;
  407.     };


  408.     :log info "$SMP everything is ready to install new RouterOS, going to reboot in a moment!"
  409.     ## Command is reincarnation of the "upgrade" command - doing exactly the same but under a different name
  410.     /system package update install;
  411. }

  412. :log info "$SMP script "Mikrotik RouterOS automatic backup & update" completed it's job.\r\n";
复制代码

3.配置邮件服务器
工具 -> 电子邮件
配置您的电子邮件服务器参数。



要检查电子邮件设置,请在终端中运行以下命令发送测试消息:

  1. /tool e-mail send to="这里修改成你的邮箱地址@qq.com" subject="backup & update test!" body="It works!";
复制代码

4.创建计划任务
系统 -> 调度程序 [添加]
名称:Backup And Update
开始时间:(03:10:00链中所有 mikrotik 设备的开始时间必须不同)
间隔:1d 00:00:00
事件发生时:/system script run BackupAndUpdate;



或者您可以使用此命令来创建任务:

  1. /system scheduler add name="Firmware Updater" on-event="/system script run BackupAndUpdate;" start-time=03:10:00 interval=1d comment="" disabled=no
复制代码

5.测试脚本
一切设置完成后,验证脚本是否正常运行非常重要。为此,请在 WinBox 中打开一个新终端和一个日志窗口,然后通过

  1. /system script run BackupAndUpdate
复制代码

在终端中键入内容手动执行脚本。您将在日志窗口中看到脚本的操作。如果脚本完成且没有任何错误,请检查您的电子邮件。您将收到一条新消息,其中包含来自 MikroTik 的备份。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注公众号

相关侵权、举报、投诉及建议等,请发 E-mail:admin@discuz.vip

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.|蜀ICP备17024538号-6

在本版发帖
关注公众号
QQ客服返回顶部