#!/bin/bash if [ -z "$RAINBOW_STATEDIR" ]; then echo "ERROR: Required configuration is missing. Please check configuraiton file." exit 1 fi DHCP_LEASES_FILE=${DHCP_LEASES_FILE:-/var/lib/dhcpd/dhcpd.leases} DHCP_CONFIG_FILE=${DHCP_CONFIG_FILE:-/etc/dhcp/dhcpd.conf} DHCP_PARSED_CACHE=$RAINBOW_STATEDIR/dhcp.cache regex_lease="lease[[:space:]]+([0-9.]+)[[:space:]]+\{" regex_starts="starts[[:space:]][0-9][[:space:]](.*)\;" regex_ends="ends[[:space:]][0-9][[:space:]](.*)\;" regex_hwaddr="hardware[[:space:]]ethernet[[:space:]](.*)\;" regex_fixedaddr="fixed-address[[:space:]](.*)\;" regex_blockstart="\{" regex_blockend="\}" dhcp_parse_leases () { local cachefile="${DHCP_PARSED_CACHE}-leases" if [ "$cachefile" -nt "$DHCP_LEASES_FILE" ]; then cat $cachefile return 0 fi cat "$DHCP_LEASES_FILE" | \ while read line; do [[ "$line" =~ $regex_lease ]] && \ leased_ip="${BASH_REMATCH[1]}" [[ "$line" =~ $regex_starts ]] && \ starts_date=$( export TZ=UTC; date +%s --date "${BASH_REMATCH[1]}" ) [[ "$line" =~ $regex_ends ]] && \ ends_date=$( export TZ=UTC; date +%s --date "${BASH_REMATCH[1]}" ) [[ "$line" =~ $regex_hwaddr ]] && \ lladdr="${BASH_REMATCH[1]}" if [[ "$line" =~ $regex_blockend ]]; then if [ -n "$leased_ip" ]; then current_date=$(date +%s) [ "$current_date" -lt "$ends_date" ] && echo "${lladdr//:/} $leased_ip" fi unset starts_date ends_date lladdr leased_ip fi done > $cachefile cat $cachefile } dhcp_parse_config () { local cachefile="${DHCP_PARSED_CACHE}-config" if [ "$cachefile" -nt "$DHCP_CONFIG_FILE" ]; then cat $cachefile return 0 fi cat "$DHCP_CONFIG_FILE" | sed -e 's/{/ {\n/g' -e 's/}/ }\n/g' -e 's/;/;\n/g' | \ while read line; do if [[ "$line" =~ $regex_blockstart ]]; then [[ "$line" =~ host ]] && hostentry=1 || hostentry=0 fi [[ "$line" =~ $regex_hwaddr ]] && \ hwether="${BASH_REMATCH[1]}" [[ "$line" =~ $regex_fixedaddr ]] && \ fixedaddr="${BASH_REMATCH[1]}" if [[ "$line" =~ $regex_blockend ]]; then if [ "$hostentry" = "1" ]; then [ -n "$hwether" -a -n "$fixedaddr" ] && echo "${hwether//:/} $fixedaddr" unset hwether fixedaddr fi fi done > $cachefile cat $cachefile } dhcp_mac2ip_mapping () { dhcp_parse_config dhcp_parse_leases } mac_colons () { echo $@ | sed 's/\(..\)/\1:/g' | sed 's/:$//' } get_dhcp_ip () { local macaddr=$1 macaddr=${macaddr//:/} dhcp_mac2ip_mapping | while read lmac lip; do if [ "$lmac" = $macaddr ]; then echo $lip return 0 fi done }