Automating user management on MikroTik RouterOS

Share your Config Push presets or discuss automation in general
Post Reply
User avatar
Tomas
Posts: 1206
Joined: Sat Jun 25, 2016 12:33 pm

Wed Dec 18, 2019 10:48 pm

Just a small script you can use to automate user management on RouterOS.
This script is idempotent - meaning it won't cause any issues if ran multiple times, or if some users it declares are already present.

Code: Select all

{
:local users {"username1"="passwd1"; "user2"="pwd2"; "mary"="lamb"}

/user
:foreach uname,pwd in=$users do={
  :if ([:len [find name=$uname]] = 0) do={
    add name=$uname password=$pwd group=full
  }
}
}
This script has multiple obvious issues:
1) it will not remove users which are no longer specified in the script
2) it will not change passwords for users that already exist
3) it keeps passwords in clear-text as part of the script

Issues 1 and 2 can be solved by removing all non-active users before adding:

Code: Select all

{
/user
:foreach u in=[find] do={
  :local shouldRemove true

  :foreach au in=[active find] do={
    :if ([get $u name] = [active get $au name]) do={
      :set shouldRemove false
    }
  }

  :if ($shouldRemove) do={
    remove $u
  }
}
}
Issue 3 can be worked around by multiple ways:
1) host the passwords in a file on a HTTPS (TLS) webserver, pull it and load it in the scripts (this has it's own drawbacks)
2) use SSH keys

As a side-note:
While doing user management this way is entirely functional, if you are doing user management this way on a large network, it would be worth it considering using Radius instead.
Post Reply