Уведомления о неудачных входах на MikroTik — Notifications about failed logins(Aliert send email) to MikroTik

В условиях роста кибератак на сетевую инфраструктуру особенно важно контролировать попытки несанкционированного доступа к пограничным маршрутизаторам. MikroTik RouterOS — одно из самых популярных решений на российском рынке, и именно оно чаще всего становится целью брутфорс-атак. Своевременное получение информации о неудачных входах позволяет быстро реагировать на инциденты. Почему именно почтовые уведомления сейчас являются оптимальным выбором?

Преимущества почтовых уведомлений для российских компаний

Независимость от внешних сервисов Многие используют Telegram-ботов или Slack-вебхуки. Однако эти сервисы могут блокироваться, требовать постоянного обновления API или работать через недоступные из-за санкций зарубежные хосты. E‑mail‑серверы, особенно внутренние (Exchange, VK WorkMail, Яндекс360), всегда доступны и не зависят от геополитической ситуации.

Стабильность доставки внутри РФ

Почтовые протоколы (SMTP) работают через стандартные порты, которые открыты в любых корпоративных сетях. Регуляторы (ФСТЭК, Минцифры) рекомендуют использовать отечественные почтовые системы, и такая схема легко вписывается в требования по импортозамещению.

Простота настройки и низкий порог входа

На MikroTik достаточно указать SMTP-сервер и один адрес получателя. Не нужно регистрировать ботов, получать токены или поддерживать внешние прокси. Это снижает риск ошибок конфигурации.

Офлайн-хранение и аудит

Письма автоматически сохраняются в почтовом ящике. Логи неудачных входов можно централизованно архивировать, не тратя ресурсы самого маршрутизатора. При расследовании инцидентов электронная переписка является легитимным доказательством.

Полный контроль над данными

В отличие от облачных мессенджеров, вы сами решаете, где хранить уведомления — на своём сервере или у доверенного провайдера. Это критично для объектов КИИ, персональных данных и гостайн.

Почему полезно получать информацию о попытках неудачного входа

Раннее обнаружение атаки – серия неудачных логинов почти всегда предшествует взлому. Вы узнаете об этом в реальном времени и сможете заблокировать IP-адрес.

Анализ векторов атак – по времени, частоте и пользователям (admin, root, user) можно понять, используется ли словарный подбор или атака направленная.

Своевременная смена политик – если неудачные попытки идут с внутренних адресов, возможно, скомпрометирован ПК сотрудника. Вы успеете отозвать учётные данные.

Соблюдение требований к аудиту – многие стандарты (PCI DSS, 152-ФЗ) требуют регистрации событий аутентификации. Email-уведомления становятся простейшей формой такого аудита.

Психологический эффект – администратор, получающий оповещения, начинает внимательнее относиться к настройкам безопасности, быстрее обновляет прошивки и меняет пароли.

Готовый скрипт для MikroTik с отправкой email-уведомлений, добавьте так же его в планировщик задач с интервалом в 3-5 минуты. Так же не забудьте настроить учётную запись почты в разделе tool > e-mail.

:local Time [/system clock get time];
:local Date [/system clock get date];
:local EmailBodyText "";
:global ParseLogAccountEndArrayID;
:local IDsEventsAccount [/log find where topics ~ "critical"];
:local LenArrayIDs [:len $IDsEventsAccount];
:local StartArrayID [:find $IDsEventsAccount $ParseLogAccountEndArrayID];
:local EndArrayID ($IDsEventsAccount -> ($LenArrayIDs-1));
:if ($EndArrayID != $ParseLogAccountEndArrayID and [:tobool $ParseLogAccountEndArrayID]) do={
    :local StartArray [:find $IDsEventsAccount $ParseLogAccountLastRunID];
    :for KeyArray from=($StartArrayID+1) to=($LenArrayIDs-1) do={
        :local IDMessage ($IDsEventsAccount ->$KeyArray);
        :set EmailBodyText "$EmailBodyText\n  $[/log get number=$IDMessage time] - $[/log get number=$IDMessage message];";
    }
    :local Subject "RouterOS: AUTH FAILED on $DeviceName";
    :local Body "$DeviceName\nTime: $Time\nDate: $Date\n\nEvents:$EmailBodyText";
    /tool e-mail send to="vashemail@email.ru" subject="$Subject" body="$Body"
}
:set ParseLogAccountEndArrayID $EndArrayID;


Eng: With cyber attacks on the network infrastructure on the rise, it is especially important to monitor unauthorized access attempts to edge routers. MikroTik RouterOS is one of the most popular solutions on the Russian market, and it is this solution that most often becomes the target of brute force attacks. Timely receipt of information about unsuccessful entries allows you to quickly respond to incidents. Why are email notifications the best choice right now?


Advantages of email notifications for Russian companies

Independence from external services Many people use Telegram bots or Slack webhooks. However, these services may be blocked, require constant API updates, or work through foreign hosts that are unavailable due to sanctions. E‑mail servers, especially internal ones (Exchange, VK WorkMail, Yandex 360), are always available and do not depend on the geopolitical situation.


Stability of delivery within the Russian Federation

Mail protocols (SMTP) work through standard ports that are open on any corporate network. Regulators (FSTEC, Ministry of Finance) recommend using domestic postal systems, and such a scheme easily fits into the requirements for import substitution.


Easy to set up and low entry threshold

On MikroTik, it is enough to specify an SMTP server and one recipient address. You don't need to register bots, receive tokens, or maintain external proxies. This reduces the risk of configuration errors.


Offline storage and auditing

Emails are automatically saved in the mailbox. Logs of failed logins can be archived centrally, without wasting the resources of the router itself. When investigating incidents, electronic correspondence is legitimate evidence.


Full control over the data

Unlike cloud messengers, you decide where to store notifications — on your server or with a trusted provider. This is critical for CII facilities, personal data, and state secrets.


Why is it useful to receive information about failed login attempts

Early detection of an attack – a series of failed logins almost always precedes hacking. You will find out about this in real time and will be able to block the IP address.


Attack vector analysis – based on time, frequency, and users (admin, root, user), it is possible to understand whether vocabulary selection is being used or a targeted attack.


Timely policy change – if unsuccessful attempts come from internal addresses, the employee's PC may be compromised. You will have time to revoke your credentials.


Compliance with audit requirements – Many standards (PCI DSS, 152-FZ) require registration of authentication events. Email notifications are becoming the simplest form of such an audit.


Psychological effect – the administrator who receives alerts begins to pay more attention to the security settings, updates the firmware faster and changes passwords.


A ready-made script for MikroTik with sending email notifications, add it to the task scheduler with an interval of 3-5 minutes. Also, do not forget to set up an email account in the tool > e-mail section.


:local Time [/system clock get time];
:local Date [/system clock get date];
:local EmailBodyText "";
:global ParseLogAccountEndArrayID;
:local IDsEventsAccount [/log find where topics ~ "critical"];
:local LenArrayIDs [:len $IDsEventsAccount];
:local StartArrayID [:find $IDsEventsAccount $ParseLogAccountEndArrayID];
:local EndArrayID ($IDsEventsAccount -> ($LenArrayIDs-1));
:if ($EndArrayID != $ParseLogAccountEndArrayID and [:tobool $ParseLogAccountEndArrayID]) do={
    :local StartArray [:find $IDsEventsAccount $ParseLogAccountLastRunID];
    :for KeyArray from=($StartArrayID+1) to=($LenArrayIDs-1) do={
        :local IDMessage ($IDsEventsAccount ->$KeyArray);
        :set EmailBodyText "$EmailBodyText\n  $[/log get number=$IDMessage time] - $[/log get number=$IDMessage message];";
    }
    :local Subject "RouterOS: AUTH FAILED on $DeviceName";
    :local Body "$DeviceName\nTime: $Time\nDate: $Date\n\nEvents:$EmailBodyText";
    /tool e-mail send to="vashemail@email.ru" subject="$Subject" body="$Body"
}
:set ParseLogAccountEndArrayID $EndArrayID;