s4:samba_dnsupdate Add a 'file based' mode to samba_dnsupdate
[Samba/kamenim.git] / source4 / scripting / bin / samba_dnsupdate
blob4fdd10de0ac692d83e704e42c4714522c36d549a
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 fcntl
24 import sys
25 import tempfile
27 # ensure we get messages out immediately, so they get in the samba logs,
28 # and don't get swallowed by a timeout
29 os.putenv('PYTHONUNBUFFERED', '1')
31 # Find right directory when running from source tree
32 sys.path.insert(0, "bin/python")
34 import samba
35 import optparse
36 from samba import getopt as options, Ldb
37 from ldb import SCOPE_SUBTREE, SCOPE_BASE, LdbError
38 import ldb
39 from samba import glue
40 from samba.auth import system_session
41 from samba.samdb import SamDB
42 import samba.external
44 resolver = samba.external.samba_external_dns_resolver()
46 default_ttl = 900
48 parser = optparse.OptionParser("samba_dnsupdate")
49 sambaopts = options.SambaOptions(parser)
50 parser.add_option_group(sambaopts)
51 parser.add_option_group(options.VersionOptions(parser))
52 parser.add_option("--verbose", action="store_true")
53 parser.add_option("--all-interfaces", action="store_true")
54 parser.add_option("--use-file", type="string", help="Use a file, rather than real DNS calls")
56 creds = None
57 ccachename = None
59 opts, args = parser.parse_args()
61 if len(args) != 0:
62 parser.print_usage()
63 sys.exit(1)
65 lp = sambaopts.get_loadparm()
67 domain = lp.get("realm")
68 host = lp.get("netbios name")
69 if opts.all_interfaces:
70 all_interfaces = True
71 else:
72 all_interfaces = False
74 IPs = glue.interface_ips(lp, all_interfaces)
75 nsupdate_cmd = lp.get('nsupdate command')
77 if len(IPs) == 0:
78 print "No IP interfaces - skipping DNS updates"
79 sys.exit(0)
83 ########################################################
84 # get credentials if we haven't got them already
85 def get_credentials(lp):
86 from samba.credentials import Credentials
87 global ccachename, creds
88 if creds is not None:
89 return
90 creds = Credentials()
91 creds.guess(lp)
92 try:
93 creds.set_machine_account(lp)
94 except:
95 print "Failed to set machine account"
96 raise
98 (tmp_fd, ccachename) = tempfile.mkstemp()
99 creds.get_named_ccache(lp, ccachename)
102 #############################################
103 # an object to hold a parsed DNS line
104 class dnsobj(object):
105 def __init__(self, string_form):
106 list = string_form.split()
107 self.dest = None
108 self.port = None
109 self.ip = None
110 self.existing_port = None
111 self.existing_weight = None
112 self.type = list[0]
113 self.name = list[1]
114 if self.type == 'SRV':
115 self.dest = list[2]
116 self.port = list[3]
117 elif self.type == 'A':
118 self.ip = list[2] # usually $IP, which gets replaced
119 elif self.type == 'CNAME':
120 self.dest = list[2]
121 else:
122 print "Received unexpected DNS reply of type %s" % self.type
123 raise
125 def __str__(self):
126 if d.type == "A": return "%s %s %s" % (self.type, self.name, self.ip)
127 if d.type == "SRV": return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
128 if d.type == "CNAME": return "%s %s %s" % (self.type, self.name, self.dest)
131 ################################################
132 # parse a DNS line from
133 def parse_dns_line(line, sub_vars):
134 subline = samba.substitute_var(line, sub_vars)
135 d = dnsobj(subline)
136 return d
138 ############################################
139 # see if two hostnames match
140 def hostname_match(h1, h2):
141 h1 = str(h1)
142 h2 = str(h2)
143 return h1.lower().rstrip('.') == h2.lower().rstrip('.')
146 ############################################
147 # check that a DNS entry exists
148 def check_dns_name(d):
149 normalised_name = d.name.rstrip('.') + '.'
150 if opts.verbose:
151 print "Looking for DNS entry %s as %s" % (d, normalised_name)
153 if opts.use_file is not None:
154 try:
155 dns_file = open(opts.use_file, "r")
156 except IOError:
157 return False
159 line = dns_file.readline()
160 while line:
161 line = line.rstrip().lstrip()
162 if line[0] == "#":
163 line = dns_file.readline()
164 continue
165 if line.lower() == str(d).lower():
166 return True
167 line = dns_file.readline()
168 return False
170 try:
171 ans = resolver.query(normalised_name, d.type)
172 except resolver.NXDOMAIN:
173 return False
174 if d.type == 'A':
175 # we need to be sure that our IP is there
176 for rdata in ans:
177 if str(rdata) == str(d.ip):
178 return True
179 if d.type == 'CNAME':
180 for i in range(len(ans)):
181 if hostname_match(ans[i].target, d.dest):
182 return True
183 if d.type == 'SRV':
184 for rdata in ans:
185 if opts.verbose:
186 print "Checking %s against %s" % (rdata, d)
187 if hostname_match(rdata.target, d.dest):
188 if str(rdata.port) == str(d.port):
189 return True
190 else:
191 d.existing_port = str(rdata.port)
192 d.existing_weight = str(rdata.weight)
193 if opts.verbose:
194 print "Failed to find DNS entry %s" % d
196 return False
199 ###########################################
200 # get the list of substitution vars
201 def get_subst_vars():
202 global lp
203 vars = {}
205 samdb = SamDB(url=lp.get("sam database"), session_info=system_session(), lp=lp)
207 vars['DNSDOMAIN'] = lp.get('realm').lower()
208 vars['HOSTNAME'] = lp.get('netbios name').lower() + "." + vars['DNSDOMAIN']
209 vars['NTDSGUID'] = samdb.get_ntds_GUID()
210 vars['SITE'] = samdb.server_site_name()
211 res = samdb.search(base=None, scope=SCOPE_BASE, attrs=["objectGUID"])
212 guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
213 vars['DOMAINGUID'] = guid
214 return vars
217 ############################################
218 # call nsupdate for an entry
219 def call_nsupdate(d):
220 global ccachename, nsupdate_cmd
222 if opts.verbose:
223 print "Calling nsupdate for %s" % d
225 if opts.use_file is not None:
226 wfile = open(opts.use_file, 'a')
227 fcntl.lockf(wfile, fcntl.LOCK_EX)
228 wfile.write(str(d)+"\n")
229 fcntl.lockf(wfile, fcntl.LOCK_UN)
230 return
232 (tmp_fd, tmpfile) = tempfile.mkstemp()
233 f = os.fdopen(tmp_fd, 'w')
234 if d.type == "A":
235 f.write("update add %s %u A %s\n" % (d.name, default_ttl, d.ip))
236 if d.type == "SRV":
237 if d.existing_port is not None:
238 f.write("update delete %s SRV 0 %s %s %s\n" % (d.name, d.existing_weight,
239 d.existing_port, d.dest))
240 f.write("update add %s %u SRV 0 100 %s %s\n" % (d.name, default_ttl, d.port, d.dest))
241 if d.type == "CNAME":
242 f.write("update add %s %u CNAME %s\n" % (d.name, default_ttl, d.dest))
243 if opts.verbose:
244 f.write("show\n")
245 f.write("send\n")
246 f.close()
248 os.putenv("KRB5CCNAME", ccachename)
249 os.system("%s %s" % (nsupdate_cmd, tmpfile))
250 os.unlink(tmpfile)
253 # get the list of DNS entries we should have
254 dns_update_list = lp.private_path('dns_update_list')
256 file = open(dns_update_list, "r")
258 # get the substitution dictionary
259 sub_vars = get_subst_vars()
261 # build up a list of update commands to pass to nsupdate
262 update_list = []
263 dns_list = []
265 # read each line, and check that the DNS name exists
266 line = file.readline()
267 while line:
268 line = line.rstrip().lstrip()
269 if line[0] == "#":
270 line = file.readline()
271 continue
272 d = parse_dns_line(line, sub_vars)
273 dns_list.append(d)
274 line = file.readline()
276 # now expand the entries, if any are A record with ip set to $IP
277 # then replace with multiple entries, one for each interface IP
278 for d in dns_list:
279 if d.type == 'A' and d.ip == "$IP":
280 d.ip = IPs[0]
281 for i in range(len(IPs)-1):
282 d2 = d
283 d2.ip = IPs[i+1]
284 dns_list.append(d2)
286 # now check if the entries already exist on the DNS server
287 for d in dns_list:
288 if not check_dns_name(d):
289 update_list.append(d)
291 if len(update_list) == 0:
292 if opts.verbose:
293 print "No DNS updates needed"
294 sys.exit(0)
296 # get our krb5 creds
297 get_credentials(lp)
299 # ask nsupdate to add entries as needed
300 for d in update_list:
301 call_nsupdate(d)
303 # delete the ccache if we created it
304 if ccachename is not None:
305 os.unlink(ccachename)