samba-tool: Use self.outf in a few more places.
[obnox/samba/samba-obnox.git] / source4 / scripting / python / samba / netcmd / rodc.py
1 #!/usr/bin/env python
2 #
3 # rodc related commands
4 #
5 # Copyright Andrew Tridgell 2010
6 # Copyright Giampaolo Lauria 2011 <lauria2@yahoo.com>
7 #
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.
12 #
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.
17 #
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/>.
20 #
21
22 from samba.netcmd import Command, CommandError, Option, SuperCommand
23 import samba.getopt as options
24 from samba.samdb import SamDB
25 from samba.auth import system_session
26 import ldb
27 from samba.dcerpc import misc, drsuapi
28 from samba.credentials import Credentials
29 from samba.drs_utils import drs_Replicate
30
31
32
33 class cmd_rodc_preload(Command):
34     """Preload one account for an RODC"""
35
36     synopsis = "%prog rodc preload (<SID>|<DN>|<accountname>) [options]"
37
38     takes_options = [
39         Option("--server", help="DC to use", type=str),
40         ]
41
42     takes_args = ["account"]
43
44     def get_dn(self, samdb, account):
45         '''work out what DN they meant'''
46
47         # we accept the account in SID, accountname or DN form
48         if account[0:2] == 'S-':
49             res = samdb.search(base="<SID=%s>" % account,
50                                expression="objectclass=user",
51                                scope=ldb.SCOPE_BASE, attrs=[])
52         elif account.find('=') >= 0:
53             res = samdb.search(base=account,
54                                expression="objectclass=user",
55                                scope=ldb.SCOPE_BASE, attrs=[])
56         else:
57             res = samdb.search(expression="(&(samAccountName=%s)(objectclass=user))" % ldb.binary_encode(account),
58                                scope=ldb.SCOPE_SUBTREE, attrs=[])
59         if len(res) != 1:
60             raise Exception("Failed to find account '%s'" % account)
61         return str(res[0]["dn"])
62
63
64     def get_dsServiceName(self, samdb):
65         res = samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
66         return res[0]["dsServiceName"][0]
67
68
69     def run(self, account, sambaopts=None,
70             credopts=None, versionopts=None, server=None):
71
72         if server is None:
73             raise Exception("You must supply a server")
74
75         lp = sambaopts.get_loadparm()
76
77         creds = credopts.get_credentials(lp, fallback_machine=True)
78
79         # connect to the remote and local SAMs
80         samdb = SamDB(url="ldap://%s" % server,
81                       session_info=system_session(),
82                       credentials=creds, lp=lp)
83
84         local_samdb = SamDB(url=None, session_info=system_session(),
85                             credentials=creds, lp=lp)
86
87         # work out the source and destination GUIDs
88         dc_ntds_dn = self.get_dsServiceName(samdb)
89         res = samdb.search(base=dc_ntds_dn, scope=ldb.SCOPE_BASE, attrs=["invocationId"])
90         source_dsa_invocation_id = misc.GUID(local_samdb.schema_format_value("objectGUID", res[0]["invocationId"][0]))
91
92         dn = self.get_dn(samdb, account)
93         self.outf.write("Replicating DN %s\n" % dn)
94
95         destination_dsa_guid = misc.GUID(local_samdb.get_ntds_GUID())
96
97         local_samdb.transaction_start()
98         repl = drs_Replicate("ncacn_ip_tcp:%s[seal,print]" % server, lp, creds, local_samdb)
99         try:
100             repl.replicate(dn, source_dsa_invocation_id, destination_dsa_guid,
101                            exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
102         except Exception, e:
103             raise CommandError("Error replicating DN %s" % dn, e)
104         local_samdb.transaction_commit()
105
106
107
108 class cmd_rodc(SuperCommand):
109     """Read-Only Domain Controller (RODC) management"""
110
111     subcommands = {}
112     subcommands["preload"] = cmd_rodc_preload()