Автор Тема: Отправка почтой логов и бекапов Миротика send-to EMail Mikrotik's logs & backups  (Прочитано 1323 раз)

0 Пользователей и 1 Гость просматривают эту тему.

Оффлайн Дмитрий

  • Global Moderator
  • Jr. Member
  • *****
  • Сообщений: 71
  • Country: ua
  • Karma: +1/-0
  • Пол: Мужской
  • ICQ: 41488731
Отправка почтой системных логов и бекапа Микротика
(To send email Mikrotik's system logs and backups)

Системные отчеты логов получать на почту можно легко не насилую при этом флеш накопитель ;)

создадим простой скрипт в планировщике (sheduler) :

Код: You are not allowed to view links. Register or Login
### Mikrotik's logs send to e-mail
:global logMessages;
:set logMessages ""
:foreach i in=[/log find ] do={
:set logMessages ($logMessages. [/log get $i time ]. " ");
:set logMessages ($logMessages. [/log get $i message ]);
:set logMessages ($logMessages. "\n")
}
/tool e-mail send subject="$[/system identity get name] MikroTik system logs" to="admin@ix-ua.net" body="$logMessages"

Можно настроить планировщик высылать тревожные сообщения при входе в систему, добавив запись под именем LoginALERT :

Код: You are not allowed to view links. Register or Login
# BEGIN SETUP
:local scheduleName "LoginALERT"
:local emailAddress "admin@ix-ua.net"
:local startBuf [:toarray [/log find message~"logged in" || message~"login failure"]]
:local removeThese {"telnet";"whatever string you want"}
# END SETUP

# warn if schedule does not exist
:if ([:len [/system scheduler find name="$scheduleName"]] = 0) do={
  /log warning "[LOGMON] ERROR: Schedule does not exist. Create schedule and edit script to match name"
}

# get last time
:local lastTime [/system scheduler get [find name="$scheduleName"] comment]
# for checking time of each log entry
:local currentTime
# log message
:local message
 
# final output
:local output

:local keepOutput false
# if lastTime is empty, set keepOutput to true
:if ([:len $lastTime] = 0) do={
  :set keepOutput true
}


:local counter 0
# loop through all log entries that have been found
:foreach i in=$startBuf do={
 
# loop through all removeThese array items
  :local keepLog true
  :foreach j in=$removeThese do={
#   if this log entry contains any of them, it will be ignored
    :if ([/log get $i message] ~ "$j") do={
      :set keepLog false
    }
  }
  :if ($keepLog = true) do={
   
   :set message [/log get $i message]

#   LOG DATE
#   depending on log date/time, the format may be different. 3 known formats
#   format of jan/01/2002 00:00:00 which shows up at unknown date/time. Using as default
    :set currentTime [ /log get $i time ]
#   format of 00:00:00 which shows up on current day's logs
   :if ([:len $currentTime] = 8 ) do={
     :set currentTime ([:pick [/system clock get date] 0 11]." ".$currentTime)
    } else={
#     format of jan/01 00:00:00 which shows up on previous day's logs
     :if ([:len $currentTime] = 15 ) do={
        :set currentTime ([:pick $currentTime 0 6]."/".[:pick [/system clock get date] 7 11]." ".[:pick $currentTime 7 15])
      }
   }
   
#   if keepOutput is true, add this log entry to output
   :if ($keepOutput = true) do={
     :set output ($output.$currentTime." ".$message."\r\n")
   }
#   if currentTime = lastTime, set keepOutput so any further logs found will be added to output
#   reset output in the case we have multiple identical date/time entries in a row as the last matching logs
#   otherwise, it would stop at the first found matching log, thus all following logs would be output
    :if ($currentTime = $lastTime) do={
     :set keepOutput true
     :set output ""
   }
  }

#   if this is last log entry
  :if ($counter = ([:len $startBuf]-1)) do={
#   If keepOutput is still false after loop, this means lastTime has a value, but a matching currentTime was never found.
#   This can happen if 1) The router was rebooted and matching logs stored in memory were wiped, or 2) An item is added
#   to the removeThese array that then ignores the last log that determined the lastTime variable.
#   This resets the comment to nothing. The next run will be like the first time, and you will get all matching logs
   :if ($keepOutput = false) do={
#     if previous log was found, this will be our new lastTime entry     
     :if ([:len $message] > 0) do={
        :set output ($output.$currentTime." ".$message."\r\n")
      }
    }
  }
  :set counter ($counter + 1)
}

# If we have output, save new date/time, and send email
if ([:len $output] > 0) do={
  /system scheduler set [find name="$scheduleName"] comment=$currentTime
  /tool e-mail send to="$emailAddress" subject="MikroTik alert $currentTime" body="$output"
  /log info "[LOGMON] New logs found, send email"
}

To send EMail Beckup - сливаем бекапы на почту

тока укажите пароль вместо YOURPASS или удалите вообще "password=YOURPASS" будет без пароля, но это нехорошо ;)

Код: You are not allowed to view links. Register or Login
{
:log info "Starting Backup Script...";
:local sysname [/system identity get name];
:local sysver [/system package get system version];
:local model [/system routerboard get model];
:delay 2;
:log info "Deleting last Backups...";
:foreach i in=[/file find] do={:if ([:typeof [:find [/file get $i name] "$sysname.backup"]]!="nil") do={/file remove $i}};
:delay 2;
:local EMail "admin@ix-ua.net";
:local backupfile ("(" . [:pick [/system clock get date] 0 3 ] . "." . [:pick [/system clock get date] 4 6] . "." . [:pick [/system clock get date] 7 11] . ")$model-v$sysver.$sysname.backup");
:log info "Creating new Full Backup file...";

/system backup save password=YOURPASS name=$backupfile;  ### <---- set YOURPASS or delete all "password=YOURPASS"
:delay 2;

:log info "Sending Full Backup file via E-mail...";
/tool e-mail send to=$EMail file=$backupfile \
subject=("$sysname Full Backup (" . [/system clock get date] . ")") \
body=("$sysname full Backup file see in attachment.\nRouterOS version: \
$sysver\nTime and Date stamp: " . [/system clock get time] . " " . \
[/system clock get date]);
:delay 5;
:local exportfile ("$sysname-backup-" . \
[:pick [/system clock get date] 7 11] . [:pick [/system \
clock get date] 0 3] . [:pick [/system clock get date] 4 6] . ".rsc");
:log info "Creating new Setup Script file...";
/export verbose file=$exportfile;
:delay 2;
:log info "Sending Setup Script file via E-mail...";
/tool e-mail send to=$EMail file=$exportfile \
subject=("$sysname Setup Script Backup (" . [/system clock get date] . \
")") body=("$sysname Setup Script file see in attachment.\nRouterOS \
version: $sysver\nTime and Date stamp: " . [/system clock get time] . " \
" . [/system clock get date]);
:delay 5;
:log info "All System Backups emailed successfully.\nBackuping completed.";
}

для v7.10 и выше немного по-другому, тут date имеет вид YYYY-MM-DD

Код: You are not allowed to view links. Register or Login
{
:log info "Starting Backup Script...";
:local sysname [/system identity get name];
:local sysver [/system package get system version];
:local model [/system routerboard get model];
:delay 2;
:log info "Deleting last Backups...";
:foreach i in=[/file find] do={:if ([:typeof [:find [/file get $i name] "$sysname.backup"]]!="nil") do={/file remove $i}};
:delay 2;
:local EMail "admin@ix-ua.net";
:local backupfile ("(" . [:pick [/system clock get date] 8 10 ] . "." . [:pick [/system clock get date] 5 7] . "." . [:pick [/system clock get date] 0 4] . ")$model-v$sysver.$sysname.backup");
:log info "Creating new Full Backup file...";

/system backup save password=YOURPASS name=$backupfile;  ### <---- set YOURPASS or delete all "password=YOURPASS"
:delay 2;

:log info "Sending Full Backup file via E-mail...";
/tool e-mail send to=$EMail file=$backupfile \
subject=("$sysname Full Backup (" . [/system clock get date] . ")") \
body=("$sysname full Backup file see in attachment.\nRouterOS version: \
$sysver\nTime and Date stamp: " . [/system clock get time] . " " . \
[/system clock get date]);
:delay 5;
:local exportfile ("$sysname-backup-" . \
[:pick [/system clock get date] 7 11] . [:pick [/system \
clock get date] 0 3] . [:pick [/system clock get date] 4 6] . ".rsc");
:log info "Creating new Setup Script file...";
/export verbose file=$exportfile;
:delay 2;
:log info "Sending Setup Script file via E-mail...";
/tool e-mail send to=$EMail file=$exportfile \
subject=("$sysname Setup Script Backup (" . [/system clock get date] . \
")") body=("$sysname Setup Script file see in attachment.\nRouterOS \
version: $sysver\nTime and Date stamp: " . [/system clock get time] . " \
" . [/system clock get date]);
:delay 5;
:log info "All System Backups emailed successfully.\nBackuping completed.";
}

Бекапы Микротика в текстовом виде
Так же можно делать и универсальные бекапы в текстовом виде, командами терминала:

Экспортируем сначала так:
Код: You are not allowed to view links. Register or Login
ip firewall  export file=ip-firewall.rsc
ip pool export file=ip-pool.rsc
ip route export file=ip-route.rsc

Потом на другом роутере импортируем:
Код: You are not allowed to view links. Register or Login
import file=ip-firewall.rsc
import file=ip-pool.rsc
import file=ip-route.rsc

Сливаем наши бекапы на FTP сервера
Делаем бекап конфигов микрота и отправляем на удаленный FTP сервер скриптом BackupsToFTP:
Код: You are not allowed to view links. Register or Login
{
local username "никнейм"
#ftp account
local ftphost "имя сервера"
local ftpuser "логин"
local ftppassword "пароль"
local ftppath "/uploads/Administrators/mikrotik-backups"

#create full system backup files
/system backup save name="$username.backup"
:delay 30s;

#create config export files
/export compact file="$username.rsc"
:delay 30s;

# upload the system backup
:log info message="Uploading system backup"
/tool fetch address="$ftphost" src-path="$username.backup" user="$ftpuser" mode=ftp password="$ftppassword" dst-path="$ftppath/$username.backup" upload=yes
:delay 30s;

# upload the config export
:log info message="Uploading config export"
/tool fetch address="$ftphost" src-path="$username.rsc" user="$ftpuser" mode=ftp password="$ftppassword" dst-path="$ftppath/$username.rsc" upload=yes
:delay 30s;

# find file name $username- then remove
:foreach i in=[/file find] do={ :if ([:typeof [:find [/file get $i name] "$username"]]!="nil") do={/file remove $i}; }
:log info message="Configuration backup finished.";
}

И добавляем его в расписание на каждый день :
Код: You are not allowed to view links. Register or Login
/system script run BackupsToFTP
« Последнее редактирование: Июня 30, 2023, 01:29:04 pm от Дмитрий »


  • 1o1o1@jabber.fr
Contact You are not allowed to view links. Register or Login