Community discussions

MikroTik App
 
globalmedia
newbie
Topic Author
Posts: 30
Joined: Mon Mar 20, 2023 11:09 pm

DHCP lease script

Mon Jun 17, 2024 11:37 pm

Dear community,

What exactly is wrong with this script?

I am using RouteOS V7 and get this script from wiki page.
# Domain to be added to your DHCP-clients hostname
:local topdomain;
:set topdomain “localdomain”;

# Use ttl to distinguish dynamic added DNS records
:local ttl;
:set ttl "00:59:59";

# Set variables to use
:local hostname;
:local hostip;
:local free;

# Remove all dynamic records
/ip dns static;
:foreach a in=[find] do={
  :if ([get $a ttl] = $ttl) do={
    :put ("Removing: " . [get $a name] . " : " . [get $a address]);
    remove $a;
  }
}

/ip dhcp-server lease ;
:foreach i in=[find] do={
  /ip dhcp-server lease ;
  :if ([:len [get $i host-name]] > 0) do={
    :set free "true";
    :set hostname ([get $i host-name] . "." . $topdomain);
    :set hostip [get $i address];
    /ip dns static ;
# Check if entry already exist
    :foreach di in [find] do={
      :if ([get $di name] = $hostname) do={
        :set free "false";
        :put ("Not adding already existing entry: " . $hostname);
      }
    }
    :if ($free = true) do={
      :put ("Adding: " . $hostname . " : " . $hostip ) ;
      /ip dns static add name=$hostname address=$hostip ttl=$ttl;
    }
  }
}
I am always getting this error on logs: executing script from dhcp failed, please check it manually.
 
User avatar
rextended
Forum Guru
Forum Guru
Posts: 12652
Joined: Tue Feb 25, 2014 12:49 pm
Location: Italy
Contact:

Re: DHCP lease script

Tue Jun 18, 2024 2:35 pm

for example, right from the start it was wrong...

:set topdomain localdomain;
 
SuperMario81
just joined
Posts: 1
Joined: Mon Jun 12, 2023 12:56 pm

Re: DHCP lease script

Wed Jun 19, 2024 2:41 pm

Hi, I´m using this and works very good, please check (maybe there is a way to make it better)
(paste it under DHCP Server Script section
:local ttl 3600s
:local GetDomain do={
    :local ipaddr [:toip $1]
    /ip dhcp-server network
    :foreach network in [find] do={
        :local netblock [get value-name=address $network]
        :if ($ipaddr in $netblock) do={
            :return [get value-name=domain $network]
        }
    }
}

:local IsValidFQDN do={
    :local string [:tostr $1]
    :return ($string~"^(([a-zA-Z0-9][a-zA-Z0-9-]{0,61}){0,1}[a-zA-Z0-9]\\.){1,9}[a-zA-Z][a-zA-Z0-9-]{0,28}[a-zA-Z0-9]\$")

}

/ip dns static
:if ($leaseBound = 1) do={
    :local FQDN "$($"lease-hostname").$[$GetDomain $leaseActIP]"
    :if ([$IsValidFQDN $FQDN]) do={
        remove numbers=[find where name=$FQDN]
        add name=$FQDN address=$leaseActIP ttl=$ttl
    }
} else={
    remove numbers=[find where address=$leaseActIP ttl=$ttl]
}