Merge 2610c05b5b95cc7036b3d6dfb894c6cfbdb68483 as Samba-4.0alpha16
[metze/samba/wip.git] / source4 / scripting / python / samba / netcmd / drs.py
1 #!/usr/bin/env python
2 #
3 # implement samba_tool drs commands
4 #
5 # Copyright Andrew Tridgell 2010
6 #
7 # based on C implementation by Kamen Mazdrashki <kamen.mazdrashki@postpath.com>
8 #
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 #
22
23 import samba.getopt as options
24 import ldb
25
26 from samba.auth import system_session
27 from samba.netcmd import (
28     Command,
29     CommandError,
30     Option,
31     SuperCommand,
32     )
33 from samba.samdb import SamDB
34 from samba import drs_utils, nttime2string, dsdb
35 from samba.dcerpc import drsuapi, misc
36 import common
37
38 def drsuapi_connect(ctx):
39     '''make a DRSUAPI connection to the server'''
40     binding_options = "seal"
41     if int(ctx.lp.get("log level")) >= 5:
42         binding_options += ",print"
43     binding_string = "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options)
44     try:
45         ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds)
46         (ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drs_DsBind(ctx.drsuapi)
47     except Exception, e:
48         raise CommandError("DRS connection to %s failed" % ctx.server, e)
49
50
51 def samdb_connect(ctx):
52     '''make a ldap connection to the server'''
53     try:
54         ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
55                           session_info=system_session(),
56                           credentials=ctx.creds, lp=ctx.lp)
57     except Exception, e:
58         raise CommandError("LDAP connection to %s failed" % ctx.server, e)
59
60
61 def drs_errmsg(werr):
62     '''return "was successful" or an error string'''
63     (ecode, estring) = werr
64     if ecode == 0:
65         return "was successful"
66     return "failed, result %u (%s)" % (ecode, estring)
67
68
69 def attr_default(msg, attrname, default):
70     '''get an attribute from a ldap msg with a default'''
71     if attrname in msg:
72         return msg[attrname][0]
73     return default
74
75
76 def drs_parse_ntds_dn(ntds_dn):
77     '''parse a NTDS DN returning a site and server'''
78     a = ntds_dn.split(',')
79     if a[0] != "CN=NTDS Settings" or a[2] != "CN=Servers" or a[4] != 'CN=Sites':
80         raise RuntimeError("bad NTDS DN %s" % ntds_dn)
81     server = a[1].split('=')[1]
82     site   = a[3].split('=')[1]
83     return (site, server)
84
85
86 def get_dsServiceName(samdb):
87     '''get the NTDS DN from the rootDSE'''
88     res = samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
89     return res[0]["dsServiceName"][0]
90
91
92 class cmd_drs_showrepl(Command):
93     """show replication status"""
94
95     synopsis = "%prog drs showrepl <DC>"
96
97     takes_optiongroups = {
98         "sambaopts": options.SambaOptions,
99         "versionopts": options.VersionOptions,
100         "credopts": options.CredentialsOptions,
101     }
102
103     takes_args = ["DC?"]
104
105     def print_neighbour(self, n):
106         '''print one set of neighbour information'''
107         self.message("%s" % n.naming_context_dn)
108         try:
109             (site, server) = drs_parse_ntds_dn(n.source_dsa_obj_dn)
110             self.message("\t%s\%s via RPC" % (site, server))
111         except RuntimeError:
112             self.message("\tNTDS DN: %s" % n.source_dsa_obj_dn)
113         self.message("\t\tDSA object GUID: %s" % n.source_dsa_obj_guid)
114         self.message("\t\tLast attempt @ %s %s" % (nttime2string(n.last_attempt),
115                                                    drs_errmsg(n.result_last_attempt)))
116         self.message("\t\t%u consecutive failure(s)." % n.consecutive_sync_failures)
117         self.message("\t\tLast success @ %s" % nttime2string(n.last_success))
118         self.message("")
119
120     def drsuapi_ReplicaInfo(ctx, info_type):
121         '''call a DsReplicaInfo'''
122
123         req1 = drsuapi.DsReplicaGetInfoRequest1()
124         req1.info_type = info_type
125         try:
126             (info_type, info) = ctx.drsuapi.DsReplicaGetInfo(ctx.drsuapi_handle, 1, req1)
127         except Exception, e:
128             raise CommandError("DsReplicaGetInfo of type %u failed" % info_type, e)
129         return (info_type, info)
130
131
132     def run(self, DC=None, sambaopts=None,
133             credopts=None, versionopts=None, server=None):
134
135         self.lp = sambaopts.get_loadparm()
136         if DC is None:
137             DC = common.netcmd_dnsname(self.lp)
138         self.server = DC
139         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
140
141         drsuapi_connect(self)
142         samdb_connect(self)
143
144         # show domain information
145         ntds_dn = get_dsServiceName(self.samdb)
146         server_dns = self.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])[0]['dnsHostName'][0]
147
148         (site, server) = drs_parse_ntds_dn(ntds_dn)
149         try:
150             ntds = self.samdb.search(base=ntds_dn, scope=ldb.SCOPE_BASE, attrs=['options', 'objectGUID', 'invocationId'])
151         except Exception, e:
152             raise CommandError("Failed to search NTDS DN %s" % ntds_dn)
153         conn = self.samdb.search(base=ntds_dn, expression="(objectClass=nTDSConnection)")
154
155         self.message("%s\\%s" % (site, server))
156         self.message("DSA Options: 0x%08x" % int(attr_default(ntds[0], "options", 0)))
157         self.message("DSA object GUID: %s" % self.samdb.schema_format_value("objectGUID", ntds[0]["objectGUID"][0]))
158         self.message("DSA invocationId: %s\n" % self.samdb.schema_format_value("objectGUID", ntds[0]["invocationId"][0]))
159
160         self.message("==== INBOUND NEIGHBORS ====\n")
161         (info_type, info) = self.drsuapi_ReplicaInfo(drsuapi.DRSUAPI_DS_REPLICA_INFO_NEIGHBORS)
162         for n in info.array:
163             self.print_neighbour(n)
164
165
166         self.message("==== OUTBOUND NEIGHBORS ====\n")
167         (info_type, info) = self.drsuapi_ReplicaInfo(drsuapi.DRSUAPI_DS_REPLICA_INFO_REPSTO)
168         for n in info.array:
169             self.print_neighbour(n)
170
171         reasons = ['NTDSCONN_KCC_GC_TOPOLOGY',
172                    'NTDSCONN_KCC_RING_TOPOLOGY',
173                    'NTDSCONN_KCC_MINIMIZE_HOPS_TOPOLOGY',
174                    'NTDSCONN_KCC_STALE_SERVERS_TOPOLOGY',
175                    'NTDSCONN_KCC_OSCILLATING_CONNECTION_TOPOLOGY',
176                    'NTDSCONN_KCC_INTERSITE_GC_TOPOLOGY',
177                    'NTDSCONN_KCC_INTERSITE_TOPOLOGY',
178                    'NTDSCONN_KCC_SERVER_FAILOVER_TOPOLOGY',
179                    'NTDSCONN_KCC_SITE_FAILOVER_TOPOLOGY',
180                    'NTDSCONN_KCC_REDUNDANT_SERVER_TOPOLOGY']
181
182         self.message("==== KCC CONNECTION OBJECTS ====\n")
183         for c in conn:
184             self.message("Connection --")
185             self.message("\tConnection name: %s" % c['name'][0])
186             self.message("\tEnabled        : %s" % attr_default(c, 'enabledConnection', 'TRUE'))
187             self.message("\tServer DNS name : %s" % server_dns)
188             self.message("\tServer DN name  : %s" % c['fromServer'][0])
189             self.message("\t\tTransportType: RPC")
190             self.message("\t\toptions: 0x%08X" % int(attr_default(c, 'options', 0)))
191             if not 'mS-DS-ReplicatesNCReason' in c:
192                 self.message("Warning: No NC replicated for Connection!")
193                 continue
194             for r in c['mS-DS-ReplicatesNCReason']:
195                 a = str(r).split(':')
196                 self.message("\t\tReplicatesNC: %s" % a[3])
197                 self.message("\t\tReason: 0x%08x" % int(a[2]))
198                 for s in reasons:
199                     if getattr(dsdb, s, 0) & int(a[2]):
200                         self.message("\t\t\t%s" % s)
201
202
203 class cmd_drs_kcc(Command):
204     """trigger knowledge consistency center run"""
205
206     synopsis = "%prog drs kcc <DC>"
207
208     takes_optiongroups = {
209         "sambaopts": options.SambaOptions,
210         "versionopts": options.VersionOptions,
211         "credopts": options.CredentialsOptions,
212     }
213
214     takes_args = ["DC?"]
215
216     def run(self, DC=None, sambaopts=None,
217             credopts=None, versionopts=None, server=None):
218
219         self.lp = sambaopts.get_loadparm()
220         if DC is None:
221             DC = common.netcmd_dnsname(self.lp)
222         self.server = DC
223
224         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
225
226         drsuapi_connect(self)
227
228         req1 = drsuapi.DsExecuteKCC1()
229         try:
230             self.drsuapi.DsExecuteKCC(self.drsuapi_handle, 1, req1)
231         except Exception, e:
232             raise CommandError("DsExecuteKCC failed", e)
233         self.message("Consistency check on %s successful." % DC)
234
235
236 def drs_local_replicate(self, SOURCE_DC, NC):
237     '''replicate from a source DC to the local SAM'''
238     self.server = SOURCE_DC
239     drsuapi_connect(self)
240
241     self.local_samdb = SamDB(session_info=system_session(), url=None,
242                              credentials=self.creds, lp=self.lp)
243
244     self.samdb = SamDB(url="ldap://%s" % self.server,
245                        session_info=system_session(),
246                        credentials=self.creds, lp=self.lp)
247
248     # work out the source and destination GUIDs
249     res = self.local_samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
250     self.ntds_dn = res[0]["dsServiceName"][0]
251
252     res = self.local_samdb.search(base=self.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
253     self.ntds_guid = misc.GUID(self.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
254
255
256     source_dsa_invocation_id = misc.GUID(self.samdb.get_invocation_id())
257     destination_dsa_guid = self.ntds_guid
258
259     self.samdb.transaction_start()
260     repl = drs_utils.drs_Replicate("ncacn_ip_tcp:%s[seal]" % self.server, self.lp,
261                                    self.creds, self.local_samdb)
262     try:
263         repl.replicate(NC, source_dsa_invocation_id, destination_dsa_guid)
264     except Exception, e:
265         raise CommandError("Error replicating DN %s" % NC, e)
266     self.samdb.transaction_commit()
267
268
269
270 class cmd_drs_replicate(Command):
271     """replicate a naming context between two DCs"""
272
273     synopsis = "%prog drs replicate <DEST_DC> <SOURCE_DC> <NC>"
274
275     takes_optiongroups = {
276         "sambaopts": options.SambaOptions,
277         "versionopts": options.VersionOptions,
278         "credopts": options.CredentialsOptions,
279     }
280
281     takes_args = ["DEST_DC", "SOURCE_DC", "NC"]
282
283     takes_options = [
284         Option("--add-ref", help="use ADD_REF to add to repsTo on source", action="store_true"),
285         Option("--sync-forced", help="use SYNC_FORCED to force inbound replication", action="store_true"),
286         Option("--local", help="pull changes directly into the local database (destination DC is ignored)", action="store_true"),
287         ]
288
289     def run(self, DEST_DC, SOURCE_DC, NC, add_ref=False, sync_forced=False, local=False,
290             sambaopts=None,
291             credopts=None, versionopts=None, server=None):
292
293         self.server = DEST_DC
294         self.lp = sambaopts.get_loadparm()
295
296         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
297
298         if local:
299             drs_local_replicate(self, SOURCE_DC, NC)
300             return
301
302         drsuapi_connect(self)
303         samdb_connect(self)
304
305         # we need to find the NTDS GUID of the source DC
306         msg = self.samdb.search(base=self.samdb.get_config_basedn(),
307                                 expression="(&(objectCategory=server)(|(name=%s)(dNSHostName=%s)))" % (SOURCE_DC,
308                                                                                                        SOURCE_DC),
309                                 attrs=[])
310         if len(msg) == 0:
311             raise CommandError("Failed to find source DC %s" % SOURCE_DC)
312         server_dn = msg[0]['dn']
313
314         msg = self.samdb.search(base=server_dn, scope=ldb.SCOPE_ONELEVEL,
315                                 expression="(|(objectCategory=nTDSDSA)(objectCategory=nTDSDSARO))",
316                                 attrs=['objectGUID', 'options'])
317         if len(msg) == 0:
318             raise CommandError("Failed to find source NTDS DN %s" % SOURCE_DC)
319         source_dsa_guid = msg[0]['objectGUID'][0]
320         options = int(attr_default(msg, 'options', 0))
321
322         nc = drsuapi.DsReplicaObjectIdentifier()
323         nc.dn = NC
324
325         req1 = drsuapi.DsReplicaSyncRequest1()
326         req1.naming_context = nc;
327         req1.options = 0
328         if not (options & dsdb.DS_NTDSDSA_OPT_DISABLE_OUTBOUND_REPL):
329             req1.options |= drsuapi.DRSUAPI_DRS_WRIT_REP
330         if add_ref:
331             req1.options |= drsuapi.DRSUAPI_DRS_ADD_REF
332         if sync_forced:
333             req1.options |= drsuapi.DRSUAPI_DRS_SYNC_FORCED
334         req1.source_dsa_guid = misc.GUID(source_dsa_guid)
335
336         try:
337             self.drsuapi.DsReplicaSync(self.drsuapi_handle, 1, req1)
338         except Exception, estr:
339             raise CommandError("DsReplicaSync failed", estr)
340         self.message("Replicate from %s to %s was successful." % (SOURCE_DC, DEST_DC))
341
342
343
344 class cmd_drs_bind(Command):
345     """show DRS capabilities of a server"""
346
347     synopsis = "%prog drs bind <DC>"
348
349     takes_optiongroups = {
350         "sambaopts": options.SambaOptions,
351         "versionopts": options.VersionOptions,
352         "credopts": options.CredentialsOptions,
353     }
354
355     takes_args = ["DC?"]
356
357     def run(self, DC=None, sambaopts=None,
358             credopts=None, versionopts=None, server=None):
359
360         self.lp = sambaopts.get_loadparm()
361         if DC is None:
362             DC = common.netcmd_dnsname(self.lp)
363         self.server = DC
364         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
365
366         drsuapi_connect(self)
367         samdb_connect(self)
368
369         bind_info = drsuapi.DsBindInfoCtr()
370         bind_info.length = 28
371         bind_info.info = drsuapi.DsBindInfo28()
372         (info, handle) = self.drsuapi.DsBind(misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID), bind_info)
373
374         optmap = [
375             ("DRSUAPI_SUPPORTED_EXTENSION_BASE" ,                       "DRS_EXT_BASE"),
376             ("DRSUAPI_SUPPORTED_EXTENSION_ASYNC_REPLICATION" ,          "DRS_EXT_ASYNCREPL"),
377             ("DRSUAPI_SUPPORTED_EXTENSION_REMOVEAPI" ,                  "DRS_EXT_REMOVEAPI"),
378             ("DRSUAPI_SUPPORTED_EXTENSION_MOVEREQ_V2" ,                 "DRS_EXT_MOVEREQ_V2"),
379             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHG_COMPRESS" ,            "DRS_EXT_GETCHG_DEFLATE"),
380             ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V1" ,                  "DRS_EXT_DCINFO_V1"),
381             ("DRSUAPI_SUPPORTED_EXTENSION_RESTORE_USN_OPTIMIZATION" ,   "DRS_EXT_RESTORE_USN_OPTIMIZATION"),
382             ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY" ,                   "DRS_EXT_ADDENTRY"),
383             ("DRSUAPI_SUPPORTED_EXTENSION_KCC_EXECUTE" ,                "DRS_EXT_KCC_EXECUTE"),
384             ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY_V2" ,                "DRS_EXT_ADDENTRY_V2"),
385             ("DRSUAPI_SUPPORTED_EXTENSION_LINKED_VALUE_REPLICATION" ,   "DRS_EXT_LINKED_VALUE_REPLICATION"),
386             ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V2" ,                  "DRS_EXT_DCINFO_V2"),
387             ("DRSUAPI_SUPPORTED_EXTENSION_INSTANCE_TYPE_NOT_REQ_ON_MOD","DRS_EXT_INSTANCE_TYPE_NOT_REQ_ON_MOD"),
388             ("DRSUAPI_SUPPORTED_EXTENSION_CRYPTO_BIND" ,                "DRS_EXT_CRYPTO_BIND"),
389             ("DRSUAPI_SUPPORTED_EXTENSION_GET_REPL_INFO" ,              "DRS_EXT_GET_REPL_INFO"),
390             ("DRSUAPI_SUPPORTED_EXTENSION_STRONG_ENCRYPTION" ,          "DRS_EXT_STRONG_ENCRYPTION"),
391             ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V01" ,                 "DRS_EXT_DCINFO_VFFFFFFFF"),
392             ("DRSUAPI_SUPPORTED_EXTENSION_TRANSITIVE_MEMBERSHIP" ,      "DRS_EXT_TRANSITIVE_MEMBERSHIP"),
393             ("DRSUAPI_SUPPORTED_EXTENSION_ADD_SID_HISTORY" ,            "DRS_EXT_ADD_SID_HISTORY"),
394             ("DRSUAPI_SUPPORTED_EXTENSION_POST_BETA3" ,                 "DRS_EXT_POST_BETA3"),
395             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V5" ,               "DRS_EXT_GETCHGREQ_V5"),
396             ("DRSUAPI_SUPPORTED_EXTENSION_GET_MEMBERSHIPS2" ,           "DRS_EXT_GETMEMBERSHIPS2"),
397             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V6" ,               "DRS_EXT_GETCHGREQ_V6"),
398             ("DRSUAPI_SUPPORTED_EXTENSION_NONDOMAIN_NCS" ,              "DRS_EXT_NONDOMAIN_NCS"),
399             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8" ,               "DRS_EXT_GETCHGREQ_V8"),
400             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V5" ,             "DRS_EXT_GETCHGREPLY_V5"),
401             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V6" ,             "DRS_EXT_GETCHGREPLY_V6"),
402             ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRYREPLY_V3" ,           "DRS_EXT_WHISTLER_BETA3"),
403             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V7" ,             "DRS_EXT_WHISTLER_BETA3"),
404             ("DRSUAPI_SUPPORTED_EXTENSION_VERIFY_OBJECT" ,              "DRS_EXT_WHISTLER_BETA3"),
405             ("DRSUAPI_SUPPORTED_EXTENSION_XPRESS_COMPRESS" ,            "DRS_EXT_W2K3_DEFLATE"),
406             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V10" ,              "DRS_EXT_GETCHGREQ_V10"),
407             ("DRSUAPI_SUPPORTED_EXTENSION_RESERVED_PART2" ,             "DRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART2"),
408             ("DRSUAPI_SUPPORTED_EXTENSION_RESERVED_PART3" ,             "DRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART3")
409             ]
410
411         optmap_ext = [
412             ("DRSUAPI_SUPPORTED_EXTENSION_ADAM",                        "DRS_EXT_ADAM"),
413             ("DRSUAPI_SUPPORTED_EXTENSION_LH_BETA2",                    "DRS_EXT_LH_BETA2"),
414             ("DRSUAPI_SUPPORTED_EXTENSION_RECYCLE_BIN",                 "DRS_EXT_RECYCLE_BIN")]
415
416         self.message("Bind to %s succeeded." % DC)
417         self.message("Extensions supported:")
418         for (opt, str) in optmap:
419             optval = getattr(drsuapi, opt, 0)
420             if info.info.supported_extensions & optval:
421                 yesno = "Yes"
422             else:
423                 yesno = "No "
424             self.message("  %-60s: %s (%s)" % (opt, yesno, str))
425
426         if isinstance(info.info, drsuapi.DsBindInfo48):
427             self.message("\nExtended Extensions supported:")
428             for (opt, str) in optmap_ext:
429                 optval = getattr(drsuapi, opt, 0)
430                 if info.info.supported_extensions_ext & optval:
431                     yesno = "Yes"
432                 else:
433                     yesno = "No "
434                 self.message("  %-60s: %s (%s)" % (opt, yesno, str))
435
436         self.message("\nSite GUID: %s" % info.info.site_guid)
437         self.message("Repl epoch: %u" % info.info.repl_epoch)
438         if isinstance(info.info, drsuapi.DsBindInfo48):
439             self.message("Forest GUID: %s" % info.info.config_dn_guid)
440
441
442
443 class cmd_drs_options(Command):
444     """query or change 'options' for NTDS Settings object of a domain controller"""
445
446     synopsis = ("%prog drs options <DC>"
447                 " [--dsa-option={+|-}IS_GC | {+|-}DISABLE_INBOUND_REPL"
448                 " |{+|-}DISABLE_OUTBOUND_REPL | {+|-}DISABLE_NTDSCONN_XLATE]")
449
450     takes_optiongroups = {
451         "sambaopts": options.SambaOptions,
452         "versionopts": options.VersionOptions,
453         "credopts": options.CredentialsOptions,
454     }
455
456     takes_args = ["DC?"]
457
458     takes_options = [
459         Option("--dsa-option", help="DSA option to enable/disable", type="str"),
460         ]
461
462     option_map = {"IS_GC": 0x00000001,
463                   "DISABLE_INBOUND_REPL": 0x00000002,
464                   "DISABLE_OUTBOUND_REPL": 0x00000004,
465                   "DISABLE_NTDSCONN_XLATE": 0x00000008}
466
467     def run(self, DC=None, dsa_option=None,
468             sambaopts=None, credopts=None, versionopts=None):
469
470         self.lp = sambaopts.get_loadparm()
471         if DC is None:
472             DC = common.netcmd_dnsname(self.lp)
473         self.server = DC
474         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
475
476         samdb_connect(self)
477
478         ntds_dn = get_dsServiceName(self.samdb)
479         res = self.samdb.search(base=ntds_dn, scope=ldb.SCOPE_BASE, attrs=["options"])
480         dsa_opts = int(res[0]["options"][0])
481
482         # print out current DSA options
483         cur_opts = [x for x in self.option_map if self.option_map[x] & dsa_opts]
484         self.message("Current DSA options: " + ", ".join(cur_opts))
485
486         # modify options
487         if dsa_option:
488             if dsa_option[:1] not in ("+", "-"):
489                 raise CommandError("Unknown option %s" % dsa_option)
490             flag = dsa_option[1:]
491             if flag not in self.option_map.keys():
492                 raise CommandError("Unknown option %s" % dsa_option)
493             if dsa_option[:1] == "+":
494                 dsa_opts |= self.option_map[flag]
495             else:
496                 dsa_opts &= ~self.option_map[flag]
497             #save new options
498             m = ldb.Message()
499             m.dn = ldb.Dn(self.samdb, ntds_dn)
500             m["options"]= ldb.MessageElement(str(dsa_opts), ldb.FLAG_MOD_REPLACE, "options")
501             self.samdb.modify(m)
502             # print out new DSA options
503             cur_opts = [x for x in self.option_map if self.option_map[x] & dsa_opts]
504             self.message("New DSA options: " + ", ".join(cur_opts))
505
506
507 class cmd_drs(SuperCommand):
508     """DRS commands"""
509
510     subcommands = {}
511     subcommands["bind"] = cmd_drs_bind()
512     subcommands["kcc"] = cmd_drs_kcc()
513     subcommands["replicate"] = cmd_drs_replicate()
514     subcommands["showrepl"] = cmd_drs_showrepl()
515     subcommands["options"] = cmd_drs_options()