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