s4-samba-tool: use correct object notation ie. obj.method rather than method(obj...
[Samba/gebeck_regimport.git] / source4 / scripting / python / samba / netcmd / dbcheck.py
blobc1321d0f4633d2448d54bd0fd4ca45e366c272a6
1 #!/usr/bin/env python
3 # Samba4 AD database checker
5 # Copyright (C) Andrew Tridgell 2011
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 samba, ldb, sys
22 import samba.getopt as options
23 from samba.auth import system_session
24 from samba.samdb import SamDB
25 from samba.dcerpc import security
26 from samba.netcmd import (
27 Command,
28 CommandError,
29 Option
32 def confirm(self, msg):
33 '''confirm an action with the user'''
34 if self.yes:
35 print("%s [YES]" % msg)
36 return True
37 v = raw_input(msg + ' [y/N] ')
38 return v.upper() in ['Y', 'YES']
40 class cmd_dbcheck(Command):
41 """check local AD database for errors"""
42 synopsis = "dbcheck <DN> [options]"
44 takes_optiongroups = {
45 "sambaopts": options.SambaOptions,
46 "versionopts": options.VersionOptions,
47 "credopts": options.CredentialsOptionsDouble,
50 takes_args = ["DN?"]
52 takes_options = [
53 Option("--scope", dest="scope", default="SUB",
54 help="Pass search scope that builds DN list. Options: SUB, ONE, BASE"),
55 Option("--fix", dest="fix", default=False, action='store_true',
56 help='Fix any errors found'),
57 Option("--yes", dest="yes", default=False, action='store_true',
58 help="don't confirm changes, just do them all"),
59 Option("--cross-ncs", dest="cross_ncs", default=False, action='store_true',
60 help="cross naming context boundaries"),
61 Option("-v", "--verbose", dest="verbose", action="store_true", default=False,
62 help="Print more details of checking"),
65 def run(self, DN=None, verbose=False, fix=False, yes=False, cross_ncs=False,
66 scope="SUB", credopts=None, sambaopts=None, versionopts=None):
67 self.lp = sambaopts.get_loadparm()
68 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
70 self.samdb = SamDB(session_info=system_session(), url=None,
71 credentials=self.creds, lp=self.lp)
72 self.verbose = verbose
73 self.fix = fix
74 self.yes = yes
76 scope_map = { "SUB": ldb.SCOPE_SUBTREE, "BASE":ldb.SCOPE_BASE, "ONE":ldb.SCOPE_ONELEVEL }
77 scope = scope.upper()
78 if not scope in scope_map:
79 raise CommandError("Unknown scope %s" % scope)
80 self.search_scope = scope_map[scope]
82 controls = []
83 if cross_ncs:
84 controls.append("search_options:1:2")
86 res = self.samdb.search(base=DN, scope=self.search_scope, attrs=['dn'], controls=controls)
87 print('Checking %u objects' % len(res))
88 error_count = 0
89 for object in res:
90 error_count += self.check_object(object.dn)
91 if error_count != 0 and not self.fix:
92 print("Please use --fix to fix these errors")
93 print('Checked %u objects (%u errors)' % (len(res), error_count))
94 if error_count != 0:
95 sys.exit(1)
97 def empty_attribute(self, dn, attrname):
98 '''fix empty attributes'''
99 print("ERROR: Empty attribute %s in %s" % (attrname, dn))
100 if not self.fix:
101 return
102 if not confirm(self, 'Remove empty attribute %s from %s?' % (attrname, dn)):
103 print("Not fixing empty attribute %s" % attrname)
104 return
106 m = ldb.Message()
107 m.dn = dn
108 m[attrname] = ldb.MessageElement('', ldb.FLAG_MOD_DELETE, attrname)
109 try:
110 self.samdb.modify(m, controls=["relax:0"], validate=False)
111 except Exception, msg:
112 print("Failed to remove empty attribute %s : %s" % (attrname, msg))
113 return
114 print("Removed empty attribute %s" % attrname)
116 def check_object(self, dn):
117 '''check one object'''
118 if self.verbose:
119 print("Checking object %s" % dn)
120 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, controls=["extended_dn:1:1"], attrs=['*', 'ntSecurityDescriptor'])
121 if len(res) != 1:
122 print("Object %s disappeared during check" % dn)
123 return 1
124 obj = res[0]
125 error_count = 0
126 for attrname in obj:
127 if attrname == 'dn':
128 continue
130 # check for empty attributes
131 for val in obj[attrname]:
132 if val == '':
133 self.empty_attribute(dn, attrname)
134 error_count += 1
135 continue
137 # check for incorrectly normalised attributes
138 for val in obj[attrname]:
139 normalised = self.samdb.dsdb_normalise_attributes(self.samdb, attrname, [val])
140 if len(normalised) != 1 or normalised[0] != val:
141 self.normalise_mismatch(dn, attrname, obj[attrname])
142 error_count += 1
143 break
144 return error_count
146 def normalise_mismatch(self, dn, attrname, values):
147 '''fix attribute normalisation errors'''
148 print("ERROR: Normalisation error for attribute %s in %s" % (attrname, dn))
149 mod_list = []
150 for val in values:
151 normalised = self.samdb.dsdb_normalise_attributes(self.samdb, attrname, [val])
152 if len(normalised) != 1:
153 print("Unable to normalise value '%s'" % val)
154 mod_list.append((val, ''))
155 elif (normalised[0] != val):
156 print("value '%s' should be '%s'" % (val, normalised[0]))
157 mod_list.append((val, normalised[0]))
158 if not self.fix:
159 return
160 if not self.confirm(self, 'Fix normalisation for %s from %s?' % (attrname, dn)):
161 print("Not fixing attribute %s" % attrname)
162 return
164 m = ldb.Message()
165 m.dn = dn
166 for i in range(0, len(mod_list)):
167 (val, nval) = mod_list[i]
168 m['value_%u' % i] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
169 if nval != '':
170 m['normv_%u' % i] = ldb.MessageElement(nval, ldb.FLAG_MOD_ADD, attrname)
172 try:
173 self.samdb.modify(m, controls=["relax:0"], validate=False)
174 except Exception, msg:
175 print("Failed to normalise attribute %s : %s" % (attrname, msg))
176 return
177 print("Normalised attribute %s" % attrname)