OpenWrt Forum Archive

Topic: [Howto] Dynamic to static DHCP lease

The content of this topic has been archived on 4 Apr 2018. There are no obvious gaps in this topic, but there may still be some posts missing at the end.

Hi there,
when setup a new network you might generate a bunch of static DHCP lease. But doing that using luci is a pain. I solved that using this script:

The script checks the uci-dhcp section if the MAC already exists. If not, the lease is added to the config.

As the dhcp-script option isn't included in the UCI-options, I had to add it into the dnsmasq.conf (as stated in the openwrt-wiki).

grep -q "dhcp-script" /etc/dnsmasq.conf || echo "dhcp-script=/etc/" >> /etc/dnsmasq.conf

cat > /etc/ << 'EOF'


# Is the MAC already known?
if uci show dhcp | grep -q "${mac}"; then
    logger -s " MAC ${mac} already exists in config"

# in case you want only to record a specific IP range:
# if echo ${ip} | egrep -q -v '10\.0\.(19|23)\.'; then
#     logger -s " IP ${ip} ignored"
#     exit
# fi

logger -s " Adding static lease ${ip} for ${mac} ${hostname}"
uci add dhcp host
uci set dhcp.@host[-1].ip=${ip}
uci set dhcp.@host[-1].mac=${mac}

# If a hostname has been supplied we also set it:
[ -n "$hostname" ] && uci set dhcp.@host[-1].name="$hostname"

uci commit dhcp

chmod a+x /etc/
/etc/init.d/dnsmasq restart

Thanks to ruzickap, I used some hits in his code to solve this task!

(Last edited by joky on 10 Feb 2017, 09:05)

Great job.
AFAIK no need to escape each $ in the script if you do:

cat << 'EOF' > /etc/

Also IMHO one-liner

[ -n "$hostname" ] && uci set dhcp.@host[-1].name="$hostname"

is neater wink

PS. Does it work well with existing leases? For some reason I was under impression that you'd need to delete /var/dhcp.leases before restarting dnsmasq to force renewals.

(Last edited by stangri on 10 Feb 2017, 08:27)

Hi stangri,
thanks your your input!

As I don't evaluate $1 (command = new/old/.. whatever) the script adds the new/old/.. lease to the config.

The dhcp-script is executed for every DHCP-lease on restart so every (active?) lease is getting added to the dhcp-config after first restart.


(Last edited by joky on 10 Feb 2017, 09:07)

The discussion might have continued from here.