This repository has been archived by the owner on Jul 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync_dhcp_zone.sh
79 lines (70 loc) · 1.91 KB
/
sync_dhcp_zone.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/bin/bash
IPA_SERVERS="""172.16.1.10
172.16.1.11
NONE"""
OUTPUT_FILE=/etc/dhcp/dhcpd.auto.conf
# find the first available ipa server
for ipa_server in $IPA_SERVERS; do
if [[ $ipa_server == "NONE" ]]; then
echo 'No IPA Servers found.' >&2
exit 1
fi
echo "trying $ipa_server."
if dig @$ipa_server +time=1 +tries=1 dhcp. &>/dev/null; then
break
fi;
echo "$ipa_server not reachable."
done;
echo "using $ipa_server."
# clear output tmp file
echo """
# This file has been autogenerated from the records defined in
# the dhcp DNS zone. Please modify these records on the IPA
# servers.
""" > $OUTPUT_FILE.new
# lookup all the host records defined in the dhcp zone
record_names=$(dig axfr @$ipa_server dhcp. +answer | \
egrep -v '(^;|^$)' | \
egrep '(IN\s+A\s|IN\s+TXT\s)' | \
awk '{ print $1 }' | \
sort -u)
# lookup details for all host records
for record in $record_names; do
# find first ip address in a record
ip_addr=$(dig A @$ipa_server $record +noauthority +noadditional | \
egrep -v '(^;|^$)' | \
awk '{ print $5 }' | \
egrep '^([0-9]{1,3}\.){3}([0-9]{1,3})$' | \
head -n 1)
# find first mac address in txt record
mac_addr=$(dig TXT @$ipa_server $record +noauthority +noadditional | \
egrep -v '(^;|^$)' | \
tr -d '"' | \
awk '{ print $5 }' | \
egrep '^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$' | \
head -n 1)
if [ ! -z "$record" ] && [ ! -z $ip_addr ] && [ ! -z $mac_addr ]; then
echo """
host $record {
hardware ethernet $mac_addr;
fixed-address $ip_addr;
}
""" >> $OUTPUT_FILE.new
fi
done
# check if an update is required
if ! diff $OUTPUT_FILE $OUTPUT_FILE.new &>/dev/null; then
# update the reservations
cp $OUTPUT_FILE $OUTPUT_FILE.last
cp $OUTPUT_FILE.new $OUTPUT_FILE
if dhcpd -t &> /dev/null; then
rm $OUTPUT_FILE.new
systemctl restart dhcpd
echo "Reservations have been updated."
else
echo "Invalid DHCP config file at $OUTPUT_FILE.new" >&2
exit 2
fi
else
echo "No update."
fi