Last active
January 16, 2024 22:42
-
-
Save tsvetkovv/909402fcc5a255eef7c4a50358bccd77 to your computer and use it in GitHub Desktop.
routeros mikrotik set static hostname for DHCP lease (whiltelist)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# RouterOS 7.11.2 | |
:global hostnames {"hostname1"; "hostname2"}; | |
:global domain "home"; | |
# Function to check if hostname is in the array | |
:local isInArray do={ | |
:local result false; | |
:foreach item in=$hostnames do={ | |
if ($item = $leaseHost) do={ :set result true; } | |
} | |
:return $result; | |
}; | |
# Function to check if static entry exists and matches IP | |
:local isStaticMatch do={ | |
:local result false; | |
:local staticIP [/ip dns static get [find name=$hostname] address]; | |
if ($staticIP = $leaseIP) do={ | |
:set result true; | |
} | |
:return $result; | |
}; | |
# Iterate through DHCP leases | |
:foreach lease in=[/ip dhcp-server lease find] do={ | |
:local leaseHost [/ip dhcp-server lease get $lease host-name]; | |
:local leaseIP [/ip dhcp-server lease get $lease address]; | |
# Check if the hostname is in the array | |
:if ([$isInArray hostnames=$hostnames leaseHost=$leaseHost] = true) do={ | |
# Check if a static entry already exists and matches the IP | |
:local domainName ($leaseHost . "." . $domain) | |
:if ([/ip dns static find name=$domainName] != "") do={ | |
:if ([$isStaticMatch hostname=$domainName leaseIP=$leaseIP] = true) do={ | |
# :put ("Static entry for " . $domainName . " already exists with matching IP."); | |
} else={ | |
# :put ("Updating static entry for " . $domainName); | |
/ip dns static set [find name=$domainName] address=$leaseIP comment="static-hostname-script" | |
} | |
} else={ | |
# :put ("Adding static entry for " . $domainName); | |
/ip dns static add name=$domainName address=$leaseIP comment="static-hostname-script" | |
} | |
} else={ | |
# :put ("No match for " . $domainName); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment