]> git.sthu.org Git - shutils.git/blob - nsd/nsd-dynipwatch
bfdb8407bad273f34f3cf78b7d3e5038be28a69d
[shutils.git] / nsd / nsd-dynipwatch
1 #!/bin/bash
2
3 logfile=
4 watchfile=
5
6 while true; do
7 case $1 in
8 --log) logfile=$2; shift ;;
9 --watchfile) watchfile=$2; shift ;;
10 -h|--help)
11 echo "$0 [--log logfile] [--watchfile /tmp/\${host}.ip] zonefile host"
12 exit 0
13 ;;
14 *) break ;;
15 esac
16 shift
17 done
18
19
20 zonefile=$1
21 host=$2
22 [ -z "${watchfile}" ] && watchfile=/tmp/${host}.ip
23 [ -z "${logfile}" ] && logfile="/var/log/nsd-dynipwatch-${host}.log"
24
25
26 echo "Watch ${watchfile} for host ${host} and update ${zonefile}. Logfile: ${logfile}"
27
28
29 function getAddrFromZonefile # <host> <zonefile>
30 {
31 egrep "^$1\\s.*\\sA\\s.*" $2 | egrep -o "([0-9]+\\.)+[0-9]+"
32 }
33
34 function setAddrInZonefile # <host> <zonefile> <addr>
35 {
36 sed -i -e "s_^\\($1\\s.*A\\s.*\\s\\)\\([0-9]\\+\\.\\)\\+[0-9]\\+_\\1$3_g" "$2"
37 }
38
39 function getSerialFromZonefile # <zonefile>
40 {
41 awk '/; serial/{print$1}' "$1"
42 }
43
44 function setSerialInZonefile # <zonefile> <serial>
45 {
46 sed -i -e "s_^\\(.*\\s\\)[0-9]\+\\(\\s\\+; serial.*\\)_\\1$2\\2_g" "$1"
47 }
48
49 function run()
50 {
51 while true; do
52 inotifywait -q -t 30 -e close_write "${watchfile}" > /dev/null
53 ret=$?
54 [ "$ret" = "0" ] || continue
55
56 oldip=`getAddrFromZonefile "${host}" "${zonefile}"`
57 newip=`cat ${watchfile}`
58 echo "`date '+%a %F %T'` :: ${oldip} => ${newip}."
59
60 if ! echo "${newip}" | egrep -q "^([0-9]+\\.)+[0-9]+$" ; then
61 echo "Wrong format of new IP address."
62 continue
63 fi
64
65 if ! [ "${oldip}" = "${newip}" ]; then
66 serial=`getSerialFromZonefile "${zonefile}"`
67 serial=$(( $serial + 1))
68 echo " Update IP address. New serial ${serial}."
69 setAddrInZonefile "${host}" "${zonefile}" "${newip}"
70 setSerialInZonefile "${zonefile}" "${serial}"
71 nsdc rebuild && nsdc reload && nsdc notify
72 fi
73 done
74 }
75
76
77 run >> $logfile
78