MikroTik Service Access List management script

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

Mon Feb 13, 2023 4:19 pm

This is a small script that will let you automate service ("/ip service") access list management on MikroTik RouterOS.

You can drop this into a Config Push preset and push it to your entire network at any time (or on schedule) to make sure access lists are standardized across your network.

There are 2 variants of this script. Variant 1 simply replaces what is in the current access lists by specified values:

Code: Select all

:do {
  :local services {"api"; "www"}
  :local addresses {"1.1.1.1/32"; "2.2.2.2/32"}

  /ip service
  :foreach s in=$services do={
    :local sid [find name=$s]

    :if ([:len $sid] = 0) do={
      :put "Service '$s' doesn't exist!"
    } else={
      set $sid address=$addresses
    }
  }
} on-error={
  :put "Error occured!"
}
You specify which services you want to set access lists for, and what addresses should be allowed.

This 2nd variant will make sure the addresses you specify are present in the address list, but will not remove anything extra that was already there:

Code: Select all

:do {
  :local services {"api"; "www"}
  :local addresses {"1.1.1.1/32"; "2.2.2.2/32"}

  /ip service
  :foreach s in=$services do={
    :local sid [find name=$s]

    :if ([:len $sid] = 0) do={
      :put "Service '$s' doesn't exist!"
    } else={
      :foreach a in=$addresses do={
        :if ([:len [:find [get $sid address] $a]] = 0) do={
          :put "Inserting $a into $[get $sid name]"
          set $sid address=([get $sid address] + $a)
        }
      }
    }
  }
} on-error={
  :put "Error occured!"
}
Note: it is very important to insert full addresses (in "ip/prefix" form) into the script above. Otherwise entries in service access list might be duplicated.
Post Reply