1 # implement samba_tool drs commands
3 # Copyright Andrew Tridgell 2010
4 # Copyright Andrew Bartlett 2017
6 # based on C implementation by Kamen Mazdrashki <kamen.mazdrashki@postpath.com>
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
22 import samba.getopt as options
27 from samba.auth import system_session
28 from samba.netcmd import (
34 from samba.samdb import SamDB
35 from samba import drs_utils, nttime2string, dsdb
36 from samba.dcerpc import drsuapi, misc
37 from samba.join import join_clone
38 from samba.ndr import ndr_unpack
39 from samba.dcerpc import drsblobs
41 def drsuapi_connect(ctx):
42 '''make a DRSUAPI connection to the server'''
44 (ctx.drsuapi, ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drsuapi_connect(ctx.server, ctx.lp, ctx.creds)
46 raise CommandError("DRS connection to %s failed" % ctx.server, e)
48 def samdb_connect(ctx):
49 '''make a ldap connection to the server'''
51 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
52 session_info=system_session(),
53 credentials=ctx.creds, lp=ctx.lp)
55 raise CommandError("LDAP connection to %s failed" % ctx.server, e)
58 '''return "was successful" or an error string'''
59 (ecode, estring) = werr
61 return "was successful"
62 return "failed, result %u (%s)" % (ecode, estring)
66 def attr_default(msg, attrname, default):
67 '''get an attribute from a ldap msg with a default'''
69 return msg[attrname][0]
74 def drs_parse_ntds_dn(ntds_dn):
75 '''parse a NTDS DN returning a site and server'''
76 a = ntds_dn.split(',')
77 if a[0] != "CN=NTDS Settings" or a[2] != "CN=Servers" or a[4] != 'CN=Sites':
78 raise RuntimeError("bad NTDS DN %s" % ntds_dn)
79 server = a[1].split('=')[1]
80 site = a[3].split('=')[1]
87 class cmd_drs_showrepl(Command):
88 """Show replication status."""
90 synopsis = "%prog [<DC>] [options]"
92 takes_optiongroups = {
93 "sambaopts": options.SambaOptions,
94 "versionopts": options.VersionOptions,
95 "credopts": options.CredentialsOptions,
100 def print_neighbour(self, n):
101 '''print one set of neighbour information'''
102 self.message("%s" % n.naming_context_dn)
104 (site, server) = drs_parse_ntds_dn(n.source_dsa_obj_dn)
105 self.message("\t%s\%s via RPC" % (site, server))
107 self.message("\tNTDS DN: %s" % n.source_dsa_obj_dn)
108 self.message("\t\tDSA object GUID: %s" % n.source_dsa_obj_guid)
109 self.message("\t\tLast attempt @ %s %s" % (nttime2string(n.last_attempt),
110 drs_errmsg(n.result_last_attempt)))
111 self.message("\t\t%u consecutive failure(s)." % n.consecutive_sync_failures)
112 self.message("\t\tLast success @ %s" % nttime2string(n.last_success))
115 def drsuapi_ReplicaInfo(ctx, info_type):
116 '''call a DsReplicaInfo'''
118 req1 = drsuapi.DsReplicaGetInfoRequest1()
119 req1.info_type = info_type
121 (info_type, info) = ctx.drsuapi.DsReplicaGetInfo(ctx.drsuapi_handle, 1, req1)
123 raise CommandError("DsReplicaGetInfo of type %u failed" % info_type, e)
124 return (info_type, info)
126 def run(self, DC=None, sambaopts=None,
127 credopts=None, versionopts=None, server=None):
129 self.lp = sambaopts.get_loadparm()
131 DC = common.netcmd_dnsname(self.lp)
133 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
135 drsuapi_connect(self)
138 # show domain information
139 ntds_dn = self.samdb.get_dsServiceName()
140 server_dns = self.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])[0]['dnsHostName'][0]
142 (site, server) = drs_parse_ntds_dn(ntds_dn)
144 ntds = self.samdb.search(base=ntds_dn, scope=ldb.SCOPE_BASE, attrs=['options', 'objectGUID', 'invocationId'])
146 raise CommandError("Failed to search NTDS DN %s" % ntds_dn)
147 conn = self.samdb.search(base=ntds_dn, expression="(objectClass=nTDSConnection)")
149 self.message("%s\\%s" % (site, server))
150 self.message("DSA Options: 0x%08x" % int(attr_default(ntds[0], "options", 0)))
151 self.message("DSA object GUID: %s" % self.samdb.schema_format_value("objectGUID", ntds[0]["objectGUID"][0]))
152 self.message("DSA invocationId: %s\n" % self.samdb.schema_format_value("objectGUID", ntds[0]["invocationId"][0]))
154 self.message("==== INBOUND NEIGHBORS ====\n")
155 (info_type, info) = self.drsuapi_ReplicaInfo(drsuapi.DRSUAPI_DS_REPLICA_INFO_NEIGHBORS)
157 self.print_neighbour(n)
160 self.message("==== OUTBOUND NEIGHBORS ====\n")
161 (info_type, info) = self.drsuapi_ReplicaInfo(drsuapi.DRSUAPI_DS_REPLICA_INFO_REPSTO)
163 self.print_neighbour(n)
165 reasons = ['NTDSCONN_KCC_GC_TOPOLOGY',
166 'NTDSCONN_KCC_RING_TOPOLOGY',
167 'NTDSCONN_KCC_MINIMIZE_HOPS_TOPOLOGY',
168 'NTDSCONN_KCC_STALE_SERVERS_TOPOLOGY',
169 'NTDSCONN_KCC_OSCILLATING_CONNECTION_TOPOLOGY',
170 'NTDSCONN_KCC_INTERSITE_GC_TOPOLOGY',
171 'NTDSCONN_KCC_INTERSITE_TOPOLOGY',
172 'NTDSCONN_KCC_SERVER_FAILOVER_TOPOLOGY',
173 'NTDSCONN_KCC_SITE_FAILOVER_TOPOLOGY',
174 'NTDSCONN_KCC_REDUNDANT_SERVER_TOPOLOGY']
176 self.message("==== KCC CONNECTION OBJECTS ====\n")
178 self.message("Connection --")
180 c_rdn, sep, c_server_dn = c['fromServer'][0].partition(',')
182 c_server_res = self.samdb.search(base=c_server_dn, scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
183 c_server_dns = c_server_res[0]["dnsHostName"][0]
184 except ldb.LdbError, (errno, _):
185 if errno == ldb.ERR_NO_SUCH_OBJECT:
186 self.message("\tWARNING: Connection to DELETED server!")
191 self.message("\tConnection name: %s" % c['name'][0])
192 self.message("\tEnabled : %s" % attr_default(c, 'enabledConnection', 'TRUE'))
193 self.message("\tServer DNS name : %s" % c_server_dns)
194 self.message("\tServer DN name : %s" % c['fromServer'][0])
195 self.message("\t\tTransportType: RPC")
196 self.message("\t\toptions: 0x%08X" % int(attr_default(c, 'options', 0)))
197 if not 'mS-DS-ReplicatesNCReason' in c:
198 self.message("Warning: No NC replicated for Connection!")
200 for r in c['mS-DS-ReplicatesNCReason']:
201 a = str(r).split(':')
202 self.message("\t\tReplicatesNC: %s" % a[3])
203 self.message("\t\tReason: 0x%08x" % int(a[2]))
205 if getattr(dsdb, s, 0) & int(a[2]):
206 self.message("\t\t\t%s" % s)
210 class cmd_drs_kcc(Command):
211 """Trigger knowledge consistency center run."""
213 synopsis = "%prog [<DC>] [options]"
215 takes_optiongroups = {
216 "sambaopts": options.SambaOptions,
217 "versionopts": options.VersionOptions,
218 "credopts": options.CredentialsOptions,
223 def run(self, DC=None, sambaopts=None,
224 credopts=None, versionopts=None, server=None):
226 self.lp = sambaopts.get_loadparm()
228 DC = common.netcmd_dnsname(self.lp)
231 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
233 drsuapi_connect(self)
235 req1 = drsuapi.DsExecuteKCC1()
237 self.drsuapi.DsExecuteKCC(self.drsuapi_handle, 1, req1)
239 raise CommandError("DsExecuteKCC failed", e)
240 self.message("Consistency check on %s successful." % DC)
244 def drs_local_replicate(self, SOURCE_DC, NC, full_sync=False):
245 '''replicate from a source DC to the local SAM'''
247 self.server = SOURCE_DC
248 drsuapi_connect(self)
250 self.local_samdb = SamDB(session_info=system_session(), url=None,
251 credentials=self.creds, lp=self.lp)
253 self.samdb = SamDB(url="ldap://%s" % self.server,
254 session_info=system_session(),
255 credentials=self.creds, lp=self.lp)
257 # work out the source and destination GUIDs
258 res = self.local_samdb.search(base="", scope=ldb.SCOPE_BASE,
259 attrs=["dsServiceName"])
260 self.ntds_dn = res[0]["dsServiceName"][0]
262 res = self.local_samdb.search(base=self.ntds_dn, scope=ldb.SCOPE_BASE,
263 attrs=["objectGUID"])
264 self.ntds_guid = misc.GUID(self.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
266 source_dsa_invocation_id = misc.GUID(self.samdb.get_invocation_id())
267 dest_dsa_invocation_id = misc.GUID(self.local_samdb.get_invocation_id())
268 destination_dsa_guid = self.ntds_guid
270 # If we can't find an upToDateVector, replicate fully
271 hwm = drsuapi.DsReplicaHighWaterMark()
272 hwm.tmp_highest_usn = 0
278 res = self.local_samdb.search(base=NC, scope=ldb.SCOPE_BASE,
280 if "repsFrom" in res[0]:
281 for reps_from_packed in res[0]["repsFrom"]:
282 reps_from_obj = ndr_unpack(drsblobs.repsFromToBlob, reps_from_packed)
283 if reps_from_obj.ctr.source_dsa_invocation_id == source_dsa_invocation_id:
284 hwm = reps_from_obj.ctr.highwatermark
286 udv = drsuapi.DsReplicaCursorCtrEx()
292 cursors_v2 = dsdb._dsdb_load_udv_v2(self.local_samdb,
293 self.local_samdb.get_default_basedn())
294 for cursor_v2 in cursors_v2:
295 cursor_v1 = drsuapi.DsReplicaCursor()
296 cursor_v1.source_dsa_invocation_id = cursor_v2.source_dsa_invocation_id
297 cursor_v1.highest_usn = cursor_v2.highest_usn
298 cursors_v1.append(cursor_v1)
300 udv.cursors = cursors_v1
301 udv.count = len(cursors_v1)
303 self.samdb.transaction_start()
304 repl = drs_utils.drs_Replicate("ncacn_ip_tcp:%s[seal]" % self.server, self.lp,
305 self.creds, self.local_samdb, dest_dsa_invocation_id)
307 # Work out if we are an RODC, so that a forced local replicate
308 # with the admin pw does not sync passwords
309 rodc = self.local_samdb.am_rodc()
311 (num_objects, num_links) = repl.replicate(NC,
312 source_dsa_invocation_id, destination_dsa_guid,
313 rodc=rodc, highwatermark=hwm, udv=udv)
315 raise CommandError("Error replicating DN %s" % NC, e)
316 self.samdb.transaction_commit()
319 self.message("Full Replication of all %d objects and %d links from %s to %s was successful."
320 % (num_objects, num_links, SOURCE_DC, self.local_samdb.url))
322 self.message("Incremental replication of %d objects and %d links from %s to %s was successful."
323 % (num_objects, num_links, SOURCE_DC, self.local_samdb.url))
326 class cmd_drs_replicate(Command):
327 """Replicate a naming context between two DCs."""
329 synopsis = "%prog <destinationDC> <sourceDC> <NC> [options]"
331 takes_optiongroups = {
332 "sambaopts": options.SambaOptions,
333 "versionopts": options.VersionOptions,
334 "credopts": options.CredentialsOptions,
337 takes_args = ["DEST_DC", "SOURCE_DC", "NC"]
340 Option("--add-ref", help="use ADD_REF to add to repsTo on source", action="store_true"),
341 Option("--sync-forced", help="use SYNC_FORCED to force inbound replication", action="store_true"),
342 Option("--sync-all", help="use SYNC_ALL to replicate from all DCs", action="store_true"),
343 Option("--full-sync", help="resync all objects", action="store_true"),
344 Option("--local", help="pull changes directly into the local database (destination DC is ignored)", action="store_true"),
345 Option("--local-online", help="pull changes into the local database (destination DC is ignored) as a normal online replication", action="store_true"),
346 Option("--async-op", help="use ASYNC_OP for the replication", action="store_true"),
349 def run(self, DEST_DC, SOURCE_DC, NC,
350 add_ref=False, sync_forced=False, sync_all=False, full_sync=False,
351 local=False, local_online=False, async_op=False,
352 sambaopts=None, credopts=None, versionopts=None, server=None):
354 self.server = DEST_DC
355 self.lp = sambaopts.get_loadparm()
357 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
360 drs_local_replicate(self, SOURCE_DC, NC, full_sync=full_sync)
364 server_bind = drsuapi.drsuapi("irpc:dreplsrv", lp_ctx=self.lp)
365 server_bind_handle = misc.policy_handle()
367 drsuapi_connect(self)
368 server_bind = self.drsuapi
369 server_bind_handle = self.drsuapi_handle
372 # Give the sync replication 5 minutes time
373 server_bind.request_timeout = 5 * 60
377 # we need to find the NTDS GUID of the source DC
378 msg = self.samdb.search(base=self.samdb.get_config_basedn(),
379 expression="(&(objectCategory=server)(|(name=%s)(dNSHostName=%s)))" % (
380 ldb.binary_encode(SOURCE_DC),
381 ldb.binary_encode(SOURCE_DC)),
384 raise CommandError("Failed to find source DC %s" % SOURCE_DC)
385 server_dn = msg[0]['dn']
387 msg = self.samdb.search(base=server_dn, scope=ldb.SCOPE_ONELEVEL,
388 expression="(|(objectCategory=nTDSDSA)(objectCategory=nTDSDSARO))",
389 attrs=['objectGUID', 'options'])
391 raise CommandError("Failed to find source NTDS DN %s" % SOURCE_DC)
392 source_dsa_guid = msg[0]['objectGUID'][0]
393 dsa_options = int(attr_default(msg, 'options', 0))
397 if not (dsa_options & dsdb.DS_NTDSDSA_OPT_DISABLE_OUTBOUND_REPL):
398 req_options |= drsuapi.DRSUAPI_DRS_WRIT_REP
400 req_options |= drsuapi.DRSUAPI_DRS_ADD_REF
402 req_options |= drsuapi.DRSUAPI_DRS_SYNC_FORCED
404 req_options |= drsuapi.DRSUAPI_DRS_SYNC_ALL
406 req_options |= drsuapi.DRSUAPI_DRS_FULL_SYNC_NOW
408 req_options |= drsuapi.DRSUAPI_DRS_ASYNC_OP
411 drs_utils.sendDsReplicaSync(server_bind, server_bind_handle, source_dsa_guid, NC, req_options)
412 except drs_utils.drsException, estr:
413 raise CommandError("DsReplicaSync failed", estr)
415 self.message("Replicate from %s to %s was started." % (SOURCE_DC, DEST_DC))
417 self.message("Replicate from %s to %s was successful." % (SOURCE_DC, DEST_DC))
421 class cmd_drs_bind(Command):
422 """Show DRS capabilities of a server."""
424 synopsis = "%prog [<DC>] [options]"
426 takes_optiongroups = {
427 "sambaopts": options.SambaOptions,
428 "versionopts": options.VersionOptions,
429 "credopts": options.CredentialsOptions,
434 def run(self, DC=None, sambaopts=None,
435 credopts=None, versionopts=None, server=None):
437 self.lp = sambaopts.get_loadparm()
439 DC = common.netcmd_dnsname(self.lp)
441 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
443 drsuapi_connect(self)
445 bind_info = drsuapi.DsBindInfoCtr()
446 bind_info.length = 28
447 bind_info.info = drsuapi.DsBindInfo28()
448 (info, handle) = self.drsuapi.DsBind(misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID), bind_info)
451 ("DRSUAPI_SUPPORTED_EXTENSION_BASE", "DRS_EXT_BASE"),
452 ("DRSUAPI_SUPPORTED_EXTENSION_ASYNC_REPLICATION", "DRS_EXT_ASYNCREPL"),
453 ("DRSUAPI_SUPPORTED_EXTENSION_REMOVEAPI", "DRS_EXT_REMOVEAPI"),
454 ("DRSUAPI_SUPPORTED_EXTENSION_MOVEREQ_V2", "DRS_EXT_MOVEREQ_V2"),
455 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHG_COMPRESS", "DRS_EXT_GETCHG_DEFLATE"),
456 ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V1", "DRS_EXT_DCINFO_V1"),
457 ("DRSUAPI_SUPPORTED_EXTENSION_RESTORE_USN_OPTIMIZATION", "DRS_EXT_RESTORE_USN_OPTIMIZATION"),
458 ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY", "DRS_EXT_ADDENTRY"),
459 ("DRSUAPI_SUPPORTED_EXTENSION_KCC_EXECUTE", "DRS_EXT_KCC_EXECUTE"),
460 ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY_V2", "DRS_EXT_ADDENTRY_V2"),
461 ("DRSUAPI_SUPPORTED_EXTENSION_LINKED_VALUE_REPLICATION", "DRS_EXT_LINKED_VALUE_REPLICATION"),
462 ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V2", "DRS_EXT_DCINFO_V2"),
463 ("DRSUAPI_SUPPORTED_EXTENSION_INSTANCE_TYPE_NOT_REQ_ON_MOD","DRS_EXT_INSTANCE_TYPE_NOT_REQ_ON_MOD"),
464 ("DRSUAPI_SUPPORTED_EXTENSION_CRYPTO_BIND", "DRS_EXT_CRYPTO_BIND"),
465 ("DRSUAPI_SUPPORTED_EXTENSION_GET_REPL_INFO", "DRS_EXT_GET_REPL_INFO"),
466 ("DRSUAPI_SUPPORTED_EXTENSION_STRONG_ENCRYPTION", "DRS_EXT_STRONG_ENCRYPTION"),
467 ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V01", "DRS_EXT_DCINFO_VFFFFFFFF"),
468 ("DRSUAPI_SUPPORTED_EXTENSION_TRANSITIVE_MEMBERSHIP", "DRS_EXT_TRANSITIVE_MEMBERSHIP"),
469 ("DRSUAPI_SUPPORTED_EXTENSION_ADD_SID_HISTORY", "DRS_EXT_ADD_SID_HISTORY"),
470 ("DRSUAPI_SUPPORTED_EXTENSION_POST_BETA3", "DRS_EXT_POST_BETA3"),
471 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V5", "DRS_EXT_GETCHGREQ_V5"),
472 ("DRSUAPI_SUPPORTED_EXTENSION_GET_MEMBERSHIPS2", "DRS_EXT_GETMEMBERSHIPS2"),
473 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V6", "DRS_EXT_GETCHGREQ_V6"),
474 ("DRSUAPI_SUPPORTED_EXTENSION_NONDOMAIN_NCS", "DRS_EXT_NONDOMAIN_NCS"),
475 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8", "DRS_EXT_GETCHGREQ_V8"),
476 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V5", "DRS_EXT_GETCHGREPLY_V5"),
477 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V6", "DRS_EXT_GETCHGREPLY_V6"),
478 ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRYREPLY_V3", "DRS_EXT_WHISTLER_BETA3"),
479 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V7", "DRS_EXT_WHISTLER_BETA3"),
480 ("DRSUAPI_SUPPORTED_EXTENSION_VERIFY_OBJECT", "DRS_EXT_WHISTLER_BETA3"),
481 ("DRSUAPI_SUPPORTED_EXTENSION_XPRESS_COMPRESS", "DRS_EXT_W2K3_DEFLATE"),
482 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V10", "DRS_EXT_GETCHGREQ_V10"),
483 ("DRSUAPI_SUPPORTED_EXTENSION_RESERVED_PART2", "DRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART2"),
484 ("DRSUAPI_SUPPORTED_EXTENSION_RESERVED_PART3", "DRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART3")
488 ("DRSUAPI_SUPPORTED_EXTENSION_ADAM", "DRS_EXT_ADAM"),
489 ("DRSUAPI_SUPPORTED_EXTENSION_LH_BETA2", "DRS_EXT_LH_BETA2"),
490 ("DRSUAPI_SUPPORTED_EXTENSION_RECYCLE_BIN", "DRS_EXT_RECYCLE_BIN")]
492 self.message("Bind to %s succeeded." % DC)
493 self.message("Extensions supported:")
494 for (opt, str) in optmap:
495 optval = getattr(drsuapi, opt, 0)
496 if info.info.supported_extensions & optval:
500 self.message(" %-60s: %s (%s)" % (opt, yesno, str))
502 if isinstance(info.info, drsuapi.DsBindInfo48):
503 self.message("\nExtended Extensions supported:")
504 for (opt, str) in optmap_ext:
505 optval = getattr(drsuapi, opt, 0)
506 if info.info.supported_extensions_ext & optval:
510 self.message(" %-60s: %s (%s)" % (opt, yesno, str))
512 self.message("\nSite GUID: %s" % info.info.site_guid)
513 self.message("Repl epoch: %u" % info.info.repl_epoch)
514 if isinstance(info.info, drsuapi.DsBindInfo48):
515 self.message("Forest GUID: %s" % info.info.config_dn_guid)
519 class cmd_drs_options(Command):
520 """Query or change 'options' for NTDS Settings object of a Domain Controller."""
522 synopsis = "%prog [<DC>] [options]"
524 takes_optiongroups = {
525 "sambaopts": options.SambaOptions,
526 "versionopts": options.VersionOptions,
527 "credopts": options.CredentialsOptions,
533 Option("--dsa-option", help="DSA option to enable/disable", type="str",
534 metavar="{+|-}IS_GC | {+|-}DISABLE_INBOUND_REPL | {+|-}DISABLE_OUTBOUND_REPL | {+|-}DISABLE_NTDSCONN_XLATE" ),
537 option_map = {"IS_GC": 0x00000001,
538 "DISABLE_INBOUND_REPL": 0x00000002,
539 "DISABLE_OUTBOUND_REPL": 0x00000004,
540 "DISABLE_NTDSCONN_XLATE": 0x00000008}
542 def run(self, DC=None, dsa_option=None,
543 sambaopts=None, credopts=None, versionopts=None):
545 self.lp = sambaopts.get_loadparm()
547 DC = common.netcmd_dnsname(self.lp)
549 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
553 ntds_dn = self.samdb.get_dsServiceName()
554 res = self.samdb.search(base=ntds_dn, scope=ldb.SCOPE_BASE, attrs=["options"])
555 dsa_opts = int(res[0]["options"][0])
557 # print out current DSA options
558 cur_opts = [x for x in self.option_map if self.option_map[x] & dsa_opts]
559 self.message("Current DSA options: " + ", ".join(cur_opts))
563 if dsa_option[:1] not in ("+", "-"):
564 raise CommandError("Unknown option %s" % dsa_option)
565 flag = dsa_option[1:]
566 if flag not in self.option_map.keys():
567 raise CommandError("Unknown option %s" % dsa_option)
568 if dsa_option[:1] == "+":
569 dsa_opts |= self.option_map[flag]
571 dsa_opts &= ~self.option_map[flag]
574 m.dn = ldb.Dn(self.samdb, ntds_dn)
575 m["options"]= ldb.MessageElement(str(dsa_opts), ldb.FLAG_MOD_REPLACE, "options")
577 # print out new DSA options
578 cur_opts = [x for x in self.option_map if self.option_map[x] & dsa_opts]
579 self.message("New DSA options: " + ", ".join(cur_opts))
582 class cmd_drs_clone_dc_database(Command):
583 """Replicate an initial clone of domain, but DO NOT JOIN it."""
585 synopsis = "%prog <dnsdomain> [options]"
587 takes_optiongroups = {
588 "sambaopts": options.SambaOptions,
589 "versionopts": options.VersionOptions,
590 "credopts": options.CredentialsOptions,
594 Option("--server", help="DC to join", type=str),
595 Option("--targetdir", help="where to store provision (required)", type=str),
596 Option("--quiet", help="Be quiet", action="store_true"),
597 Option("--include-secrets", help="Also replicate secret values", action="store_true"),
598 Option("--verbose", help="Be verbose", action="store_true")
601 takes_args = ["domain"]
603 def run(self, domain, sambaopts=None, credopts=None,
604 versionopts=None, server=None, targetdir=None,
605 quiet=False, verbose=False, include_secrets=False):
606 lp = sambaopts.get_loadparm()
607 creds = credopts.get_credentials(lp)
609 logger = self.get_logger()
611 logger.setLevel(logging.DEBUG)
613 logger.setLevel(logging.WARNING)
615 logger.setLevel(logging.INFO)
617 if targetdir is None:
618 raise CommandError("--targetdir option must be specified")
621 join_clone(logger=logger, server=server, creds=creds, lp=lp, domain=domain,
622 targetdir=targetdir, include_secrets=include_secrets)
625 class cmd_drs(SuperCommand):
626 """Directory Replication Services (DRS) management."""
629 subcommands["bind"] = cmd_drs_bind()
630 subcommands["kcc"] = cmd_drs_kcc()
631 subcommands["replicate"] = cmd_drs_replicate()
632 subcommands["showrepl"] = cmd_drs_showrepl()
633 subcommands["options"] = cmd_drs_options()
634 subcommands["clone-dc-database"] = cmd_drs_clone_dc_database()