Skip to content

Instantly share code, notes, and snippets.

@infloop
Forked from SmartFinn/dhcp-leases-to-dns.rsc
Created March 24, 2020 15:52
Show Gist options
  • Save infloop/7970654daca76828249a763a5186e6cb to your computer and use it in GitHub Desktop.
Save infloop/7970654daca76828249a763a5186e6cb to your computer and use it in GitHub Desktop.
MikroTik (RouterOS) script for automatically setting DNS records for clients when they obtain a DHCP lease
# MikroTik (RouterOS) script for automatically setting DNS records
# for clients when they obtain a DHCP lease.
#
# author SmartFinn <https://gist.github.com/SmartFinn>
# based on https://github.com/karrots/ROS-DDNS
:local domain;
:local fqdn;
:local hostname;
:local safeHostname;
:local token "$leaseServerName-$leaseActMAC";
:local ttl [/ip dhcp-server get $leaseServerName lease-time];
# Getting the domain name from DHCP server. If a domain name is not
# specified will use hostname only
/ip dhcp-server network {
:do {
:set domain [get [find where ($leaseActIP in address)] domain];
# Add a dot before domain name
:set domain ("." . $domain);
} on-error={
:set domain "";
};
};
:if ($leaseBound = 1) do={
:log debug "$leaseServerName: Processing bound lease $leaseActMAC ($leaseActIP)";
/ip dhcp-server lease {
:set hostname [get [find active-mac-address=$leaseActMAC] host-name];
};
# Delete unallowed chars from the hostname
:for i from=0 to=([:len $hostname]-1) do={
:local char [:pick $hostname $i];
:if ($char~"[a-zA-Z0-9-]") do={
:set safeHostname ($safeHostname . $char);
};
};
:if ([:len $safeHostname] > 0) do={
:set fqdn ($safeHostname . $domain);
/ip dns static {
:local itemId [find name=$fqdn];
:if ($itemId != "") do={
# This DNS entry already exists
:if ([get $itemId comment] = $token) do={
:if ([get $itemId address] != $leaseActIP) do={
set $itemId address=$leaseActIP ttl=$ttl;
:log info "Update DNS entry: $fqdn -> $leaseActIP ($leaseActMAC)";
};
} else={
:log warning "Cannot to add DNS entry. $fqdn already exists";
};
} else={
# Add DNS entry if it does not exist
add name=$fqdn address=$leaseActIP ttl=$ttl comment=$token;
:log info "Add DNS entry: $fqdn -> $leaseActIP ($leaseActMAC)";
};
};
};
} else={
# Remove entry when lease expires ($leaseBound=0)
:log debug "$leaseServerName: Processing deassigned lease $leaseActMAC ($leaseActIP)";
/ip dns static {
:local itemId [find comment=$token];
:if ($itemId != "") do={
:set fqdn ([get $itemId name]);
remove $itemId;
:log info "Remove DNS entry: $fqdn -> $leaseActIP ($leaseActMAC)";
};
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment