s4-dns: use samba.external to pull in the dns.resolver library
[Samba/kamenim.git] / source4 / scripting / bin / samba_dnsupdate
blob2e9c469adff8733ea49cfeebc40f0e68836f8ebc
1 #!/usr/bin/python
3 # update our DNS names using TSIG-GSS
5 # Copyright (C) Andrew Tridgell 2010
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 import getopt
22 import os
23 import sys
24 import tempfile
26 # ensure we get messages out immediately, so they get in the samba logs,
27 # and don't get swallowed by a timeout
28 os.putenv('PYTHONUNBUFFERED', '1')
30 # Find right directory when running from source tree
31 sys.path.insert(0, "bin/python")
33 import samba
34 import optparse
35 from samba import getopt as options, Ldb
36 from ldb import SCOPE_SUBTREE, SCOPE_BASE, LdbError
37 import ldb
38 from samba import glue
39 from samba.auth import system_session
40 from samba.samdb import SamDB
41 import samba.external
43 resolver = samba.external.samba_external_dns_resolver()
45 default_ttl = 900
47 parser = optparse.OptionParser("samba_dnsupdate")
48 sambaopts = options.SambaOptions(parser)
49 parser.add_option_group(sambaopts)
50 parser.add_option_group(options.VersionOptions(parser))
51 parser.add_option("--verbose", action="store_true")
53 creds = None
54 ccachename = None
56 opts, args = parser.parse_args()
58 if len(args) != 0:
59 parser.print_usage()
60 sys.exit(1)
62 lp = sambaopts.get_loadparm()
64 domain = lp.get("realm")
65 host = lp.get("netbios name")
66 IPs = glue.interface_ips(lp)
67 nsupdate_cmd = lp.get('nsupdate command')
69 if len(IPs) == 0:
70 print "No IP interfaces - skipping DNS updates"
71 sys.exit(0)
75 ########################################################
76 # get credentials if we haven't got them already
77 def get_credentials(lp):
78 from samba.credentials import Credentials
79 global ccachename, creds
80 if creds is not None:
81 return
82 creds = Credentials()
83 creds.guess(lp)
84 try:
85 creds.set_machine_account(lp)
86 except:
87 print "Failed to set machine account"
88 raise
90 (tmp_fd, ccachename) = tempfile.mkstemp()
91 creds.get_named_ccache(lp, ccachename)
94 #############################################
95 # an object to hold a parsed DNS line
96 class dnsobj(object):
97 def __init__(self):
98 self.type = None
99 self.name = None
100 self.dest = None
101 self.port = None
102 self.ip = None
103 self.existing_port = None
104 self.existing_weight = None
105 def __str__(self):
106 if d.type == "A": return "%s:%s:%s" % (self.type, self.name, self.ip)
107 if d.type == "SRV": return "%s:%s:%s:%s" % (self.type, self.name, self.dest, self.port)
108 if d.type == "CNAME": return "%s:%s:%s" % (self.type, self.name, self.dest)
111 ################################################
112 # parse a DNS line from
113 def parse_dns_line(line, sub_vars):
114 d = dnsobj()
115 subline = samba.substitute_var(line, sub_vars)
116 list = subline.split()
117 d.type = list[0]
118 d.name = list[1]
119 if d.type == 'SRV':
120 d.dest = list[2]
121 d.port = list[3]
122 elif d.type == 'A':
123 d.ip = list[2] # usually $IP, which gets replaced
124 elif d.type == 'CNAME':
125 d.dest = list[2]
126 else:
127 print "Received unexpected DNS reply of type %s" % d.type
128 raise
129 return d
131 ############################################
132 # see if two hostnames match
133 def hostname_match(h1, h2):
134 h1 = str(h1)
135 h2 = str(h2)
136 return h1.lower().rstrip('.') == h2.lower().rstrip('.')
139 ############################################
140 # check that a DNS entry exists
141 def check_dns_name(d):
142 normalised_name = d.name.rstrip('.') + '.'
143 if opts.verbose:
144 print "Looking for DNS entry %s as %s" % (d, normalised_name)
145 try:
146 ans = resolver.query(normalised_name, d.type)
147 except resolver.NXDOMAIN:
148 return False
149 if d.type == 'A':
150 # we need to be sure that our IP is there
151 for rdata in ans:
152 if str(rdata) == str(d.ip):
153 return True
154 if d.type == 'CNAME':
155 for i in range(len(ans)):
156 if hostname_match(ans[i].target, d.dest):
157 return True
158 if d.type == 'SRV':
159 for rdata in ans:
160 if opts.verbose:
161 print "Checking %s against %s" % (rdata, d)
162 if hostname_match(rdata.target, d.dest):
163 if str(rdata.port) == str(d.port):
164 return True
165 else:
166 d.existing_port = str(rdata.port)
167 d.existing_weight = str(rdata.weight)
168 if opts.verbose:
169 print "Failed to find DNS entry %s" % d
170 return False
173 ###########################################
174 # get the list of substitution vars
175 def get_subst_vars():
176 global lp
177 vars = {}
179 samdb = SamDB(url=lp.get("sam database"), session_info=system_session(), lp=lp)
181 vars['DNSDOMAIN'] = lp.get('realm').lower()
182 vars['HOSTNAME'] = lp.get('netbios name').lower() + "." + vars['DNSDOMAIN']
183 vars['NTDSGUID'] = samdb.get_ntds_GUID()
184 vars['SITE'] = samdb.server_site_name()
185 res = samdb.search(base=None, scope=SCOPE_BASE, attrs=["objectGUID"])
186 guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
187 vars['DOMAINGUID'] = guid
188 return vars
191 ############################################
192 # call nsupdate for an entry
193 def call_nsupdate(d):
194 global ccachename, nsupdate_cmd
196 if opts.verbose:
197 print "Calling nsupdate for %s" % d
198 (tmp_fd, tmpfile) = tempfile.mkstemp()
199 f = os.fdopen(tmp_fd, 'w')
200 if d.type == "A":
201 f.write("update add %s %u A %s\n" % (d.name, default_ttl, d.ip))
202 if d.type == "SRV":
203 if d.existing_port is not None:
204 f.write("update delete %s SRV 0 %s %s %s\n" % (d.name, d.existing_weight,
205 d.existing_port, d.dest))
206 f.write("update add %s %u SRV 0 100 %s %s\n" % (d.name, default_ttl, d.port, d.dest))
207 if d.type == "CNAME":
208 f.write("update add %s %u CNAME %s\n" % (d.name, default_ttl, d.dest))
209 if opts.verbose:
210 f.write("show\n")
211 f.write("send\n")
212 f.close()
214 os.putenv("KRB5CCNAME", ccachename)
215 os.system("%s %s" % (nsupdate_cmd, tmpfile))
216 os.unlink(tmpfile)
219 # get the list of DNS entries we should have
220 dns_update_list = lp.private_path('dns_update_list')
222 file = open(dns_update_list, "r")
224 # get the substitution dictionary
225 sub_vars = get_subst_vars()
227 # build up a list of update commands to pass to nsupdate
228 update_list = []
229 dns_list = []
231 # read each line, and check that the DNS name exists
232 line = file.readline()
233 while line:
234 line = line.rstrip().lstrip()
235 if line[0] == "#":
236 line = file.readline()
237 continue
238 d = parse_dns_line(line, sub_vars)
239 dns_list.append(d)
240 line = file.readline()
242 # now expand the entries, if any are A record with ip set to $IP
243 # then replace with multiple entries, one for each interface IP
244 for d in dns_list:
245 if d.type == 'A' and d.ip == "$IP":
246 d.ip = IPs[0]
247 for i in range(len(IPs)-1):
248 d2 = d
249 d2.ip = IPs[i+1]
250 dns_list.append(d2)
252 # now check if the entries already exist on the DNS server
253 for d in dns_list:
254 if not check_dns_name(d):
255 update_list.append(d)
257 if len(update_list) == 0:
258 if opts.verbose:
259 print "No DNS updates needed"
260 sys.exit(0)
262 # get our krb5 creds
263 get_credentials(lp)
265 # ask nsupdate to add entries as needed
266 for d in update_list:
267 call_nsupdate(d)
269 # delete the ccache if we created it
270 if ccachename is not None:
271 os.unlink(ccachename)