MikroTik RouterOS DHCP Delivery Script

Matt Glosson Updated by Matt Glosson

This script will try and retry to deliver a new DHCP assignment to your Sonar instance. Simply change the url and apikey variables to match your instance. Optionally, change the max variable to set a number of retries in case of failure.

For a full explanation on how you would leverage a DHCP MikroTik script, see these articles:

# Set these values
:global url "instance.sonar.software"
:global apikey "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
:global max 10

# Leave these as-is
:global attempts 0
:global success 0

:do {
:set attempts ($attempts+1);
:if ($leaseBound = 0) do {
/tool fetch url="https://$url/api/dhcp?ip_address=$leaseActIP&mac_address=$leaseActMAC&expired=1&api_key=$apikey" mode=https as-value output=user;
} else {
:delay 1s;
# see note below
:local remoteID [/ip dhcp-server lease get [find where address=$leaseActIP] agent-remote-id];
:do {
/tool fetch duration=2s url="https://$url/api/dhcp?ip_address=$leaseActIP&mac_address=$leaseActMAC&remote_id=$remoteID&expired=0&api_key=$apikey" mode=https as-value output=user;
:set success 1;
} on-error={
:log error "DHCP FAILED to send to $url on attempt $attempts out of $max for $leaseActMAC / $leaseActIP";
:delay 1s;
}
}
:if ($success) do {
:log info "DHCP successfully sent $leaseActMAC / $leaseActIP to $url";
:set attempts $max; # break out of the do..while loop
}
} while ( $attempts < $max );
Regarding the # see note below text in the script above: Different relay agents may use different fields. For example, Ubiquiti uses agent-circuit-id instead of agent-remote-id, so update as needed for your particular device.

How did we do?

Sonar IP Addressing

Automating IP Assignments, Data Rates, and Network Access in Sonar

Contact