MikroTik Script: Device Login Notification

The script will send a notification about the successful login and end of the user’s session on the MikroTik device. The notification is sent to email or Telegram.

There are many scripts on the Internet that allow you to parse the MikroTik device log, but they are all huge and difficult to understand. I [Yun Sergey] wrote a simple script to solve this problem.

The script looks for “account” events in the MikroTik device log since it was last run. Creates a message listing all events that have occurred since the last start.

The script creates and uses the global variable ParseLogAccountEndArrayID, stores the ID of the last element from the array of records with the subject “account“.

The following functions are used to send notifications:

Sample messages:

  • user USER logged in from E4:6F:13:AA:58:2D via winbox – user is logged in to the device using WinBox;
  • user USER logged in via local – user logged in to the device using the device’s MAC address;
  • user USER logged in from 192.168.1.9 via telnet – user launched MikroTik internal terminal.

Example of email message:

Email notification when user login MikroTik device

Telegram message example:

Telegram message - notification of user login to MikroTik device

Article in other languages:
🇪🇸 – MikroTik Script: Notificación de inicio de sesión del dispositivo
🇷🇺 – MikroTik Скрипт: Уведомление о входе на устройство
🇫🇷 – Script MikroTik: Notification de connexion de l’appareil
🇩🇪 – MikroTik-Script: Benachrichtigung über die Geräteanmeldung
🇳🇱 – MikroTik-script: Melding apparaat aanmelding

Create script

The following permissions are required to run the script: read, write, test, policy.

[System] -> [Scripts] -> [+] -> [Name: ParseLogAccountEvents] -> [Policy: read, write, test, policy]

Script code:

:local DeviceName [/system identity get name];
:local Time [/system clock get time];
:local Date [/system clock get date];
:local EmailMessageText;
:local TelegramMessageText;

:global ParseLogAccountEndArrayID;

:local IDsEventsAccount [/log find where  topics ~ "account"];

:local LenArrayIDs [:len $IDsEventsAccount];
:local StartArrayID [:find $IDsEventsAccount $ParseLogAccountEndArrayID];
:local EndArrayID ($IDsEventsAccount -> ($LenArrayIDs-1));

:if ($EndArrayID != $ParseLogAccountEndArrayID and [:tobool $ParseLogAccountEndArrayID] ) do={

    :for KeyArray from=($StartArrayID+1) to=($LenArrayIDs-1) do={
        :local IDMessage ($IDsEventsAccount ->$KeyArray );
        :set EmailMessageText "$EmailMessageText \n\r  $[/log get number=$IDMessage time] - $[/log get number=$IDMessage message];";
        :set TelegramMessageText "$TelegramMessageText %0D%0A  $[/log get number=$IDMessage time] - $[/log get number=$IDMessage message];";
        }

    # START SEND EMAIL
    :local SendTo "notify@mhelp.pro";
    :local Subject "\F0\9F\94\93 AUTH: $DeviceName [$Date $Time]";
    :local MessageText "$EmailMessageText";
    :local FileName "";
    :local SendEmail [:parse [/system script get SendEmailFunction source]];
    $SendEmail SendTo=$SendTo TextMail=$MessageText Subject=$Subject FileName=$FileName;
    # END SEND EMAIL

    # START SEND TELEGRAM
    :local MessageText "\F0\9F\94\93 <b>$DeviceName: AUTH</b> $TelegramMessageText";
    :local SendTelegramMessage [:parse [/system script  get MyTGBotSendMessage source]];
    $SendTelegramMessage MessageText=$MessageText;
    # END SEND TELEGRAM
}

:set ParseLogAccountEndArrayID $EndArrayID;
# YunSergey [MHelp.pro]
MikroTik Script: Device Login Notification

Add script to Scheduler

The following permissions are required to run the script: read, write, test, policy.

[System] -> [Schedule] -> [+] -> [Name: ParseLogAccountEvents] —>  [Interval: 00:05:00] -> [Policy: read, write, policy, test]

Or run in terminal:

/system scheduler add name=ParseLogAccountEvents policy=read,write,policy,test on-event="/system script run ParseLogAccountEvents" interval=5m comment="Analyze the log account and send login / logout events"
Add script "user login notification" to MikroTik scheduler

You can now increase control over your MikroTik devices – by controlling the login and logout times of device administrators. And also configure the execution of actions when the user logs in, for example, create a backup copy of the settings or create a copy of the device configuration.


🟢 How to create a script – notification of user login to MikroTik device and sending notification by email or Telegram message, was discussed in this article. I hope that now you can improve control over MikroTik devices by tracking the successful logins of administrators to the device or by detecting the actions of an intruder in time. However, if you run into any problems while configuring the script, feel free to write in the comments. I will try to help.

✅ The script is checked: hAP ac lite [RouterBOARD 952Ui-5ac2nD], RouterOS 6.47.8 (stable).

📒 When copying materials from the site, you must indicate the author (Yun Sergey) and a hyperlink to the source (MHelp.pro).

Comments 2

  • Т.е. данный скрипт показывает список всех логинов за день?
    У меня приходят сообщения и о последнем входе, и о предыдущих. И раз в 5 минут он мне присылает список дневных логинов.

    • Здравствуйте, нет. Скрипт показывает список логинов только с момента последней проверки. Интервал проверки вы задаете сами. На русском языке лучше продолжить – здесь.

Leave a Reply

Your email address will not be published. Required fields are marked *