Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!rsc by RouterOS
- # RouterOS script: dhcp2dns
- # Copyright (c) 2022 Uco Mesdag <uco@mesd.ag>
- ###
- # Settings
- :local dhcpTag "#DHCP";
- :local dnsTTL "1d 00:00:00";
- # Normalize hostname (e.g. "-= My Phone =-" -> "My-Phone")
- # - truncate length to 63 chars
- # - substitute disallowed chars with a hyphen
- # param: name
- :local normalizeHostname do={
- :local result;
- :local isInvalidChar true;
- :for i from=0 to=([:len $name]-1) do={
- :local char [:pick $name $i];
- :if ($i < 63) do={
- :if ($char~"[a-zA-Z0-9]") do={
- :set result ($result . $char);
- :set isInvalidChar false;
- } else={
- :if (!$isInvalidChar) do={
- :set result ($result . "-");
- :set isInvalidChar true;
- };
- };
- };
- };
- # Delete trailing hyphen
- :if ($isInvalidChar) do={
- :set result [:pick $result 0 ([:len $result]-1)];
- }
- :return $result;
- };
- ###
- # Script entry point
- :foreach leaseId in=[ /ip/dhcp-server/lease/find ] do={
- :local leaseActIP [ /ip/dhcp-server/lease/get $leaseId address ];
- :local leaseActMAC [ /ip/dhcp-server/lease/get $leaseId mac-address ];
- :local leaseServerName [ /ip/dhcp-server/lease/get $leaseId server ];
- :local hostname [ /ip/dhcp-server/lease/get $leaseId host-name ];
- :local ttl [ /ip/dhcp-server/get [ /ip/dhcp-server/find name=$leaseServerName ] lease-time ];
- :local domain [ /ip/dhcp-server/network/get [ /ip/dhcp-server/network/find $leaseActIP in address ] domain ];
- :local comment [ /ip/dhcp-server/lease/get $leaseId comment ];
- # Normalize the hostname and delete all disallowed chars from it
- :set hostname [ $normalizeHostname name=$hostname ];
- # Set the host name to comment field value if set
- :if ( [ :len $comment ] != 0 ) do={
- :set hostname [ $normalizeHostname name=$comment ];
- };
- # Use MAC address as a hostname if the hostname is missing or contains only disallowed chars
- :if ( [ :len $hostname ] = 0 ) do={
- :set hostname [ $normalizeHostname name=$leaseActMAC ];
- };
- # Set ttl to script settings if enabled
- :if ( [ :len $dnsTTL ] != 0) do={
- :set ttl $dnsTTL;
- };
- # Check if we have a network domain name
- :if ( [ :len $domain ] <= 0 ) do={
- :log error "DHCP2DNS: not registering domain name for address $leaseActIP because of empty network domain name";
- };
- # Set the fqdn
- :local fqdn "$hostname.$domain";
- # Atempt to register the lease
- :if ( [ :len [ /ip/dns/static/find name=$fqdn and address=$leaseActIP and disabled=no ] ] = 0 ) do={
- :log info "DHCP2DNS: registering static domain name $fqdn for address $leaseActIP with ttl $ttl";
- /ip/dns/static/add address=$leaseActIP name=$fqdn ttl=$ttl comment=$dhcpTag disabled=no;
- } else={
- :log error "DHCP2DNS: not registering domain name $fqdn for address $leaseActIP because of existing active static DNS entry with this name or address";
- };
- };
Add Comment
Please, Sign In to add comment