Tuesday, March 10, 2009

Functionalness

An object that has no function does not exist.

Saturday, March 7, 2009

Auto adding DHCP host names to DNS (MaraDNS)

Ever wonder why a host that you offer a DHCP lease to just does not automagicly appear in your non recursive DNS server's zone file. Well, it should! Using this "glue" code, it will be a snap to update your zone files whenever a new host joins the network. In this example, I am using MaraDNS and dhcpd.

Overall concept:

dhcpd --> lease file --> cron script --> ruby script --> DNS zone file

Cron entry (/etc/cron.d/update_dns):

*/5 * * * * root sh /usr/local/bin/parse_leases_add_to_dns.sh

parse_leases_add_to_dns.sh:

#!/bin/bash

#check modification time
if [ ! -f /tmp/leases_mod_time ]; then
touch /tmp/leases_mod_time
fi

#see if the last check time is less than mod time
if [ /tmp/leases_mod_time -ot /var/lib/dhcp/dhcpd.leases ]; then
/usr/local/bin/ruby add_hosts.rb
touch /tmp/leases_mod_time
fi


add_hosts.rb:


leases = open('/var/lib/dhcp/dhcpd.leases')
dns = open('/etc/maradns/kleetus.1337.foo', 'w')

leases_string = leases.read
lease = ""
client_hostname = ""

leases_string.each do |line|
next if line[0..0]=="#"
unless (line =~ /lease/).nil?
lease = line.split[1].gsub("\"","").gsub(";","")
end
unless (line =~ /client-hostname/).nil?
client_hostname = line.split[1].gsub("\"","").gsub(";","")
end
if client_hostname!="" and lease!=""
w_string = "#{client_hostname}.% #{lease}"
dns.write("#{w_string}\n")
lease = ""
client_hostname = ""
end
end

statics = ["myth-test.% 10.20.10.120", "*.% 10.20.10.100"]

statics.each do |line|
dns.write("#{line}\n")
end

dns.close

load=`/etc/init.d/maradns force-reload`


So why are you using a ruby script, can't you just do it all with bash/awk?

Sure, but the ruby script is more fun to write and maintain; if you feel the need to use bash, then this is possible too.