s4-samba-tool: fixed exception handling in subcommands
[metze/samba/wip.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 #
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 from samba.netcmd import Command, CommandError, Option, SuperCommand
22 import samba.getopt as options
23 from samba.samdb import SamDB
24 from samba.auth import system_session
25 import ldb
26 from samba.dcerpc import misc, drsuapi
27 from samba.credentials import Credentials
28 from samba.drs_utils import drs_Replicate
29
30 class cmd_rodc_preload(Command):
31     """Preload one account for an RODC"""
32
33     synopsis = "%prog rodc preload <SID|DN|accountname>"
34
35     takes_optiongroups = {
36         "sambaopts": options.SambaOptions,
37         "versionopts": options.VersionOptions,
38         "credopts": options.CredentialsOptions,
39     }
40
41     takes_options = [
42         Option("--server", help="DC to use", type=str),
43         ]
44
45     takes_args = ["account"]
46
47     def get_dn(self, samdb, account):
48         '''work out what DN they meant'''
49
50         # we accept the account in SID, accountname or DN form
51         if account[0:2] == 'S-':
52             res = samdb.search(base="<SID=%s>" % account,
53                                expression="objectclass=user",
54                                scope=ldb.SCOPE_BASE, attrs=[])
55         elif account.find('=') >= 0:
56             res = samdb.search(base=account,
57                                expression="objectclass=user",
58                                scope=ldb.SCOPE_BASE, attrs=[])
59         else:
60             res = samdb.search(expression="(&(samAccountName=%s)(objectclass=user))" % account,
61                                scope=ldb.SCOPE_SUBTREE, attrs=[])
62         if len(res) != 1:
63             raise Exception("Failed to find account '%s'" % account)
64         return str(res[0]["dn"])
65
66
67     def get_dsServiceName(self, samdb):
68         res = samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
69         return res[0]["dsServiceName"][0]
70
71
72     def run(self, account, sambaopts=None,
73             credopts=None, versionopts=None, server=None):
74
75         if server is None:
76             raise Exception("You must supply a server")
77
78         lp = sambaopts.get_loadparm()
79
80         creds = credopts.get_credentials(lp)
81         if not creds.authentication_requested():
82             print "Using machine account"
83             creds.set_machine_account(lp)
84
85
86         # connect to the remote and local SAMs
87         samdb = SamDB(url="ldap://%s" % server,
88                       session_info=system_session(),
89                       credentials=creds, lp=lp)
90
91         local_samdb = SamDB(url=None, session_info=system_session(),
92                             credentials=creds, lp=lp)
93
94         # work out the source and destination GUIDs
95         dc_ntds_dn = self.get_dsServiceName(samdb)
96         res = samdb.search(base=dc_ntds_dn, scope=ldb.SCOPE_BASE, attrs=["invocationId"])
97         source_dsa_invocation_id = misc.GUID(local_samdb.schema_format_value("objectGUID", res[0]["invocationId"][0]))
98
99         dn = self.get_dn(samdb, account)
100         print "Replicating DN %s" % dn
101
102         destination_dsa_guid = misc.GUID(local_samdb.get_ntds_GUID())
103
104         local_samdb.transaction_start()
105         repl = drs_Replicate("ncacn_ip_tcp:%s[seal,print]" % server, lp, creds, local_samdb)
106         try:
107             repl.replicate(dn, source_dsa_invocation_id, destination_dsa_guid,
108                            exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
109         except Exception, e:
110             raise CommandError("Error replicating DN %s" % dn, e)
111         local_samdb.transaction_commit()
112
113
114
115 class cmd_rodc(SuperCommand):
116     """RODC commands"""
117
118     subcommands = {}
119     subcommands["preload"] = cmd_rodc_preload()