Skip to content

Instantly share code, notes, and snippets.

@zealic

zealic/ROS.md Secret

Last active February 25, 2019 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zealic/3b8e8b112338b96fa83f156d42bb64e5 to your computer and use it in GitHub Desktop.
Save zealic/3b8e8b112338b96fa83f156d42bb64e5 to your computer and use it in GitHub Desktop.
ROS
:local ttl "00:05:00"
:local zone "lan"
:local hostname
:local ip
:local dnsip
:local dhcpip
:local dnsnode
:local dhcpnode
/ip dns static;
:foreach i in=[find where name ~ (".*\\.".$zone) ] do={
:local nodettl
:set hostname [ get $i name ];
:set hostname [ :pick $hostname 0 ( [ :len $hostname ] - ( [ :len $zone ] + 1 ) ) ];
:set nodettl [get $i ttl];
/ip dhcp-server lease;
:set dhcpnode [ find where host-name=$hostname ];
:if ( [ :len $dhcpnode ] > 0) do={
:log debug ("Lease for ".$hostname." still exists. Not deleting.");
} else={
# there's no lease by that name. Maybe this mac has a static name.
:local found false
/system script environment
:foreach n in=[ find where name ~ "shost[0-9A-F]+" ] do={
:if ( [ get $n value ] = $hostname ) do={
:set found true;
}
}
:if ( found ) do={
:log debug ("Hostname ".$hostname." is static");
} else={
:if ( $nodettl = $ttl ) do={
:log info ("Lease expired for ".$hostname.", deleting DNS entry.");
/ip dns static remove $i;
}
}
}
}
/ip dhcp-server lease;
:foreach i in=[find] do={
:set hostname ""
:local mac
:set dhcpip [ get $i address ];
:set mac [ get $i mac-address ];
:while ($mac ~ ":") do={
:local pos [ :find $mac ":" ];
:set mac ( [ :pick $mac 0 $pos ] . [ :pick $mac ($pos + 1) 999 ] );
};
:foreach n in=[ /system script environment find where name=("shost" . $mac) ] do={
:set hostname [ /system script environment get $n value ];
}
:if ( [ :len $hostname ] = 0) do={
:set hostname [ get $i host-name ];
}
:if ( [ :len $hostname ] > 0) do={
:set hostname ( $hostname . "." . $zone );
/ip dns static;
:set dnsnode [ find where name=$hostname ];
:if ( [ :len $dnsnode ] > 0 ) do={
# it exists. Is its IP the same
:set dnsip [ get $dnsnode address ];
:if ( $dnsip = $dhcpip ) do={
:log debug ("DNS entry for " . $hostname . " does not need updating.");
} else={
:log info ("Replacing DNS entry for " . $hostname);
/ip dns static remove $dnsnode;
/ip dns static add name=$hostname address=$dhcpip ttl=$ttl;
}
} else={
# it doesn't exist. Add it
:log info ("Adding new DNS entry for " . $hostname);
/ip dns static add name=$hostname address=$dhcpip ttl=$ttl;
}
}
}

for RouterOS scripts

  • dhcpHostToDNS.script
    自动更新 DHCP 到静态路由,会比较 TTL 是否为默认的的 TTL,只有不是默认的 TTL 静态 DNS 才会被删除。
    这样就能更好的支持手动静态 DNS。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment