Mikrotik RouterOS Scripting – Automatically find unathorized devices and block it on firewall

mikrotik routeros

One of the features I like most in Mikrotik RouterOS is the ability to run custom scripts that will enable you to automate some things on router side. In a workplace where “bring your own device” is practiced, being able to control the registration of these devices on your network is very important especially for mobile devices – laptops, tablets and smartphones.

It’s becoming harder to control these device especially if they are in large number. Smartphone can be just placed inside a bag or pocket while it automatically connect through your access points where wireless key is known to the user and download unnecessary files on the internet thus wasting network bandwidth while increasing network security risk.

Now, if you happen to have a Mikrotik RouterOS in your network and is facing the same dilemma then probably the script below will help you solve it or least get you started on a better solution.


# Written by: Rex Cortez
# Tested to work on RouterOS 5.19

:foreach i in=[/ip dhcp-server lease find dynamic=yes] do={
   :local dynamicIP [/ip dhcp-server lease get $i address];
   :local dynamicMAC [/ip dhcp-server lease get $i mac-address];
   :local dynamicHOST [/ip dhcp-server lease get $i host-name];
   :local macfound [/ip firewall filter find src-mac-address=$dynamicMAC];

    :if ($macfound != "") do={
        :log info ($dynamicMAC. " already filtered")
    } else= {
        /ip firewall filter add chain=forward src-mac-address=$dynamicMAC action=drop comment=($dynamicHOST . " - " . $dynamicMAC . " Unregistered device")
        :log info ("Added " . $dynamicMAC. " to firewall filter")

Basically, the script will look for dynamic ip addresses inside the dhcp server leases table and search their mac address in the firewall filter table. If it’s not yet blocked then it will create an entry blocking the mac address to prevent it from sending traffic through your network.

To automatically execute the script periodically, you will need to add it on the scheduler, see example below:

/system scheduler add comment="Find unauthorized devices and block" disabled=no interval=5m \ name=block_unauthorized_devices on-event=block_unauthorized_devices policy=read,write,test

You should be able to see on your log what devices are being blocked as the script finds one.

Leave a Reply

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