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