I've written a script to update dns when dhcp server issues a lease.
It consists of 3 parts:
* script executed by dhcp server
* two additional script used for mapping of the host name: conversion to lower case and replacement of forbidden characters
The two auxiliary scripts should be loaded on system level, preferably by scheduler on start-up.
Code: Select all
:global mapHostName do={
# param: name
# max length = 63
# allowed chars a-z,0-9,-
:local allowedChars "abcdefghijklmnopqrstuvwxyz0123456789-";
:local numChars [:len $name];
:if ($numChars > 63) do={:set numChars 63};
:local result "";
:for i from=0 to=($numChars - 1) do={
:local char [:pick $name $i];
:if ([:find $allowedChars $char] < 0) do={:set char "-"};
:set result ($result . $char);
}
:return $result;
}
:global lowerCase do={
# param: entry
:local lower "abcdefghijklmnopqrstuvwxyz";
:local upper "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
:local result "";
:for i from=0 to=([:len $entry] - 1) do={
:local char [:pick $entry $i];
:local pos [:find $upper $char];
:if ($pos > -1) do={:set char [:pick $lower $pos]};
:set result ($result . $char);
}
:return $result;
}
The dhcp server script needs to associated with the server definition. Do replace your home domain name with your value:
Code: Select all
{
:global lowerCase;
:global mapHostName;
:local parent ".your.domain.com";
:do {
:if ([/ip dhcp-server lease get value-name=dynamic [find mac-address=$leaseActMAC]]) do={
:if ($leaseBound = 1) do={
:local host [/ip dhcp-server lease get value-name=host-name [find mac-address=$leaseActMAC ]];
:if ([:len $host] = 0) do={:error "Error: no hostname for $leaseActMAC"};
:set host [$lowerCase entry=$host];
:set host [$mapHostName name=$host];
:local fqdn ($host . $parent);
:do {
/ip dns static remove [find address=$leaseActIP];
/ip dns static add address=$leaseActIP name=$fqdn;
} on-error={:log error message="Failure during dns registration of $fqdn with $leaseActIP"}
} else={
/ip dns static remove [find address=$leaseActIP];
}
}
} on-error={:log error message="Look-up by MAC failed: $leaseActMAC"}
}
Additional note: the script only manages dynamic leases. For lease which are made static/fixed, dns should be managed manually.
If you wish to keep it simple and in one location place the auxiliary scripts in the dhcp server script and replace ":global xxxxx" by ":local xxxxx". This will make these scripts private for dhcp script only.
Cheers
Updated:
* take care of corner case "no/emtpy hostname for mac"
* clean-up preexisting assignment