s4:scripting/python/modules.c - fix "asprintf" calls
[Samba/ekacnet.git] / source4 / scripting / bin / samba_dnsupdate
blob70fec25933bfb94027797ac1122bb3f916eeea9e
1 #!/usr/bin/env 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 os
22 import fcntl
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
36 from ldb import SCOPE_BASE
37 from samba.auth import system_session
38 from samba.samdb import SamDB
40 samba.ensure_external_module("dns", "dnspython")
41 import dns.resolver as resolver
43 default_ttl = 900
45 parser = optparse.OptionParser("samba_dnsupdate")
46 sambaopts = options.SambaOptions(parser)
47 parser.add_option_group(sambaopts)
48 parser.add_option_group(options.VersionOptions(parser))
49 parser.add_option("--verbose", action="store_true")
50 parser.add_option("--all-interfaces", action="store_true")
51 parser.add_option("--use-file", type="string", help="Use a file, rather than real DNS calls")
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 if opts.all_interfaces:
67 all_interfaces = True
68 else:
69 all_interfaces = False
71 IPs = samba.interface_ips(lp, all_interfaces)
72 nsupdate_cmd = lp.get('nsupdate command')
74 if len(IPs) == 0:
75 print "No IP interfaces - skipping DNS updates"
76 sys.exit(0)
80 ########################################################
81 # get credentials if we haven't got them already
82 def get_credentials(lp):
83 from samba.credentials import Credentials
84 global ccachename, creds
85 if creds is not None:
86 return
87 creds = Credentials()
88 creds.guess(lp)
89 creds.set_machine_account(lp)
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, string_form):
98 list = string_form.split()
99 self.dest = None
100 self.port = None
101 self.ip = None
102 self.existing_port = None
103 self.existing_weight = None
104 self.type = list[0]
105 self.name = list[1]
106 if self.type == 'SRV':
107 self.dest = list[2]
108 self.port = list[3]
109 elif self.type == 'A':
110 self.ip = list[2] # usually $IP, which gets replaced
111 elif self.type == 'CNAME':
112 self.dest = list[2]
113 else:
114 print "Received unexpected DNS reply of type %s" % self.type
115 raise
117 def __str__(self):
118 if d.type == "A": return "%s %s %s" % (self.type, self.name, self.ip)
119 if d.type == "SRV": return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
120 if d.type == "CNAME": return "%s %s %s" % (self.type, self.name, self.dest)
123 ################################################
124 # parse a DNS line from
125 def parse_dns_line(line, sub_vars):
126 subline = samba.substitute_var(line, sub_vars)
127 d = dnsobj(subline)
128 return d
130 ############################################
131 # see if two hostnames match
132 def hostname_match(h1, h2):
133 h1 = str(h1)
134 h2 = str(h2)
135 return h1.lower().rstrip('.') == h2.lower().rstrip('.')
138 ############################################
139 # check that a DNS entry exists
140 def check_dns_name(d):
141 normalised_name = d.name.rstrip('.') + '.'
142 if opts.verbose:
143 print "Looking for DNS entry %s as %s" % (d, normalised_name)
145 if opts.use_file is not None:
146 try:
147 dns_file = open(opts.use_file, "r")
148 except IOError:
149 return False
151 for line in dns_file:
152 line = line.strip()
153 if line == '' or line[0] == "#":
154 continue
155 if line.lower() == str(d).lower():
156 return True
157 return False
159 try:
160 ans = resolver.query(normalised_name, d.type)
161 except resolver.NXDOMAIN:
162 return False
163 if d.type == 'A':
164 # we need to be sure that our IP is there
165 for rdata in ans:
166 if str(rdata) == str(d.ip):
167 return True
168 if d.type == 'CNAME':
169 for i in range(len(ans)):
170 if hostname_match(ans[i].target, d.dest):
171 return True
172 if d.type == 'SRV':
173 for rdata in ans:
174 if opts.verbose:
175 print "Checking %s against %s" % (rdata, d)
176 if hostname_match(rdata.target, d.dest):
177 if str(rdata.port) == str(d.port):
178 return True
179 else:
180 d.existing_port = str(rdata.port)
181 d.existing_weight = str(rdata.weight)
182 if opts.verbose:
183 print "Failed to find DNS entry %s" % d
185 return False
188 ###########################################
189 # get the list of substitution vars
190 def get_subst_vars():
191 global lp
192 vars = {}
194 samdb = SamDB(url=lp.get("sam database"), session_info=system_session(),
195 lp=lp)
197 vars['DNSDOMAIN'] = lp.get('realm').lower()
198 vars['HOSTNAME'] = lp.get('netbios name').lower() + "." + vars['DNSDOMAIN']
199 vars['NTDSGUID'] = samdb.get_ntds_GUID()
200 vars['SITE'] = samdb.server_site_name()
201 res = samdb.search(base=None, scope=SCOPE_BASE, attrs=["objectGUID"])
202 guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
203 vars['DOMAINGUID'] = guid
204 return vars
207 ############################################
208 # call nsupdate for an entry
209 def call_nsupdate(d):
210 global ccachename, nsupdate_cmd
212 if opts.verbose:
213 print "Calling nsupdate for %s" % d
215 if opts.use_file is not None:
216 wfile = open(opts.use_file, 'a')
217 fcntl.lockf(wfile, fcntl.LOCK_EX)
218 wfile.write(str(d)+"\n")
219 fcntl.lockf(wfile, fcntl.LOCK_UN)
220 return
222 (tmp_fd, tmpfile) = tempfile.mkstemp()
223 f = os.fdopen(tmp_fd, 'w')
224 if d.type == "A":
225 f.write("update add %s %u A %s\n" % (d.name, default_ttl, d.ip))
226 if d.type == "SRV":
227 if d.existing_port is not None:
228 f.write("update delete %s SRV 0 %s %s %s\n" % (d.name, d.existing_weight,
229 d.existing_port, d.dest))
230 f.write("update add %s %u SRV 0 100 %s %s\n" % (d.name, default_ttl, d.port, d.dest))
231 if d.type == "CNAME":
232 f.write("update add %s %u CNAME %s\n" % (d.name, default_ttl, d.dest))
233 if opts.verbose:
234 f.write("show\n")
235 f.write("send\n")
236 f.close()
238 os.putenv("KRB5CCNAME", ccachename)
239 os.system("%s %s" % (nsupdate_cmd, tmpfile))
240 os.unlink(tmpfile)
243 # get the list of DNS entries we should have
244 dns_update_list = lp.private_path('dns_update_list')
246 file = open(dns_update_list, "r")
248 # get the substitution dictionary
249 sub_vars = get_subst_vars()
251 # build up a list of update commands to pass to nsupdate
252 update_list = []
253 dns_list = []
255 # read each line, and check that the DNS name exists
256 for line in file:
257 line = line.strip()
258 if line == '' or line[0] == "#":
259 continue
260 d = parse_dns_line(line, sub_vars)
261 dns_list.append(d)
263 # now expand the entries, if any are A record with ip set to $IP
264 # then replace with multiple entries, one for each interface IP
265 for d in dns_list:
266 if d.type == 'A' and d.ip == "$IP":
267 d.ip = IPs[0]
268 for i in range(len(IPs)-1):
269 d2 = d
270 d2.ip = IPs[i+1]
271 dns_list.append(d2)
273 # now check if the entries already exist on the DNS server
274 for d in dns_list:
275 if not check_dns_name(d):
276 update_list.append(d)
278 if len(update_list) == 0:
279 if opts.verbose:
280 print "No DNS updates needed"
281 sys.exit(0)
283 # get our krb5 creds
284 get_credentials(lp)
286 # ask nsupdate to add entries as needed
287 for d in update_list:
288 call_nsupdate(d)
290 # delete the ccache if we created it
291 if ccachename is not None:
292 os.unlink(ccachename)