Pejman Moghadam / Scripts

Making bind zone files based on dhcpd config file

Public domain


Run this script from crontab every minute.

#!/bin/bash

# Configuration
DHCPDCONF="/etc/dhcpd.conf"
DOMAIN="example.net"
REVIP="0.168.192"
FORWARD="/var/named/${DOMAIN}/${DOMAIN}.fwd"
REVERSE="/var/named/${DOMAIN}/${DOMAIN}.rev"

# Forward zone header records
FW_HEADER="\$TTL 1D
\$ORIGIN ${DOMAIN}.
@ SOA ns hostmaster 2011073000 1H 10M 1W 3H
   NS  ns
ns A 192.168.0.10
"

# Reverse zone header records
RV_HEADER="\$TTL 1D
\$ORIGIN ${REVIP}.in-addr.arpa.
@ SOA ns.${DOMAIN}. hostmaster.${DOMAIN}. 2011073000 1H 10M 1W 3H
   NS ns.${DOMAIN}.
10 PTR ns.${DOMAIN}.
"

# Making new dns zone files

echo "${FW_HEADER}" > ${FORWARD}
echo "${RV_HEADER}" > ${REVERSE}

cat "${DHCPDCONF}" | while read line; do
  if $(echo "$line" | grep -q 'host') && $(echo "$line" | grep -q '{'); then
      HOST=$(echo $line | sed -e 's,.*host *,,' -e 's, *{.*,,')
  fi
  if $(echo "$line" | grep -q 'hardware ethernet'); then
   MAC=$(echo $line | sed -e 's,.*hardware ethernet *,,' -e 's,;.*,,')
  fi
  if $(echo "$line" | grep -q 'fixed-address'); then
   IP=$(echo $line | sed -e 's,.*fixed-address *,,' -e 's,;.*,,')
  fi
  if [ "$HOST" != "" ] && [ "$MAC" != "" ] && [ "$IP" != "" ]; then
    # $HOST $MAC $IP
    LAST=$(echo $IP | sed -e 's,.*\.,,g')
    echo "$HOST A $IP" >> ${FORWARD}
    echo "$LAST PTR $HOST.${DOMAIN}." >> ${REVERSE}
    HOST=""
    MAC=""
    IP=""
  fi
done

# Reload new zones
/usr/sbin/rndc reload

dhcpd.conf example

ddns-update-style none;
subnet 192.168.0.0 netmask 255.255.255.0 {
  option routers                192.168.0.1;
  option subnet-mask            255.255.255.0;
  option domain-name-servers    8.8.8.8, 8.8.4.4;
  default-lease-time 60;
  max-lease-time 600;

  host sysop {
    hardware ethernet 6c:f0:49:45:e9:ba; 
    fixed-address 192.168.0.11;
  }

  host station01 {
    hardware ethernet 00:11:2f:4b:63:1b;
    fixed-address 192.168.0.12;
  }

  host station02 {
    hardware ethernet 00:14:85:ee:92:3a;
    fixed-address 192.168.0.13;
  }

  host station03 {
    hardware ethernet 1c:af:f7:10:56:8b; 
    fixed-address 192.168.0.14;
  }
}

BY: Pejman Moghadam
TAG: bind, dhcpd, bash-script, bash
DATE: 2011-07-30 01:12:59


Pejman Moghadam / Scripts [ TXT ]