PEP8: fix E303: too many blank lines (2)
[samba.git] / python / samba / netcmd / rodc.py
1 # rodc related commands
2 #
3 # Copyright Andrew Tridgell 2010
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 #
18
19 from samba.netcmd import Command, CommandError, Option, SuperCommand
20 import samba.getopt as options
21 from samba.samdb import SamDB
22 from samba.auth import system_session
23 import ldb
24 from samba.dcerpc import misc, drsuapi
25 from samba.drs_utils import drs_Replicate
26 import sys
27
28
29 class RODCException(Exception):
30     def __init__(self, value):
31         self.value = value
32
33     def __str__(self):
34         return "%s: %s" % (self.__class__.__name__, self.value)
35
36
37 class NamingError(RODCException):
38     pass
39
40
41 class ReplicationError(RODCException):
42     pass
43
44
45 class cmd_rodc_preload(Command):
46     """Preload accounts for an RODC.  Multiple accounts may be requested."""
47
48     synopsis = "%prog (<SID>|<DN>|<accountname>)+ ... [options]"
49
50     takes_optiongroups = {
51         "sambaopts": options.SambaOptions,
52         "versionopts": options.VersionOptions,
53         "credopts": options.CredentialsOptions,
54     }
55
56     takes_options = [
57         Option("--server", help="DC to use", type=str),
58         Option("--file", help="Read account list from a file, or - for stdin (one per line)", type=str),
59         Option("--ignore-errors", help="When preloading multiple accounts, skip any failing accounts", action="store_true"),
60     ]
61
62     takes_args = ["account*"]
63
64     def get_dn(self, samdb, account):
65         '''work out what DN they meant'''
66
67         # we accept the account in SID, accountname or DN form
68         if account[0:2] == 'S-':
69             res = samdb.search(base="<SID=%s>" % account,
70                                expression="objectclass=user",
71                                scope=ldb.SCOPE_BASE, attrs=[])
72         elif account.find('=') >= 0:
73             res = samdb.search(base=account,
74                                expression="objectclass=user",
75                                scope=ldb.SCOPE_BASE, attrs=[])
76         else:
77             res = samdb.search(expression="(&(samAccountName=%s)(objectclass=user))" % ldb.binary_encode(account),
78                                scope=ldb.SCOPE_SUBTREE, attrs=[])
79         if len(res) != 1:
80             raise NamingError("Failed to find account '%s'" % account)
81         return str(res[0]["dn"])
82
83     def run(self, *accounts, **kwargs):
84         sambaopts = kwargs.get("sambaopts")
85         credopts = kwargs.get("credopts")
86         versionpts = kwargs.get("versionopts")
87         server = kwargs.get("server")
88         accounts_file = kwargs.get("file")
89         ignore_errors = kwargs.get("ignore_errors")
90
91         if server is None:
92             raise Exception("You must supply a server")
93
94         if accounts_file is not None:
95             accounts = []
96             if accounts_file == "-":
97                 for line in sys.stdin:
98                     accounts.append(line.strip())
99             else:
100                 for line in open(accounts_file, 'r'):
101                     accounts.append(line.strip())
102
103         lp = sambaopts.get_loadparm()
104
105         creds = credopts.get_credentials(lp, fallback_machine=True)
106
107         # connect to the remote and local SAMs
108         samdb = SamDB(url="ldap://%s" % server,
109                       session_info=system_session(),
110                       credentials=creds, lp=lp)
111
112         local_samdb = SamDB(url=None, session_info=system_session(),
113                             credentials=creds, lp=lp)
114
115         destination_dsa_guid = misc.GUID(local_samdb.get_ntds_GUID())
116
117         binding_options = "seal"
118         if lp.log_level() >= 9:
119             binding_options += ",print"
120         repl = drs_Replicate("ncacn_ip_tcp:%s[%s]" % (server, binding_options),
121                              lp, creds,
122                              local_samdb, destination_dsa_guid)
123
124         errors = []
125         for account in accounts:
126             # work out the source and destination GUIDs
127             dc_ntds_dn = samdb.get_dsServiceName()
128             res = samdb.search(base=dc_ntds_dn, scope=ldb.SCOPE_BASE, attrs=["invocationId"])
129             source_dsa_invocation_id = misc.GUID(local_samdb.schema_format_value("objectGUID", res[0]["invocationId"][0]))
130
131             try:
132                 dn = self.get_dn(samdb, account)
133             except RODCException as e:
134                 if not ignore_errors:
135                     raise CommandError(str(e))
136                 errors.append(e)
137                 continue
138
139             self.outf.write("Replicating DN %s\n" % dn)
140
141             local_samdb.transaction_start()
142             try:
143                 repl.replicate(dn, source_dsa_invocation_id, destination_dsa_guid,
144                                exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
145             except Exception as e:
146                 local_samdb.transaction_cancel()
147                 if not ignore_errors:
148                     raise CommandError("Error replicating DN %s" % dn)
149                 errors.append(ReplicationError("Error replicating DN %s" % dn))
150                 continue
151
152             local_samdb.transaction_commit()
153
154         if len(errors) > 0:
155             self.message("\nPreload encountered problematic users:")
156             for error in errors:
157                 self.message("    %s" % error)
158
159
160 class cmd_rodc(SuperCommand):
161     """Read-Only Domain Controller (RODC) management."""
162
163     subcommands = {}
164     subcommands["preload"] = cmd_rodc_preload()