build: Change bin/default/python -> bin/python symlink to bin/default/python_modules
[bbaumbach/samba-autobuild/.git] / source4 / scripting / python / samba / netcmd / group.py
1 # Adds a new user to a Samba4 server
2 # Copyright Jelmer Vernooij 2008
3 #
4 # Based on the original in EJS:
5 # Copyright Andrew Tridgell 2005
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 import samba.getopt as options
21 from samba.netcmd import Command, SuperCommand, CommandError, Option
22 import ldb
23 from samba.ndr import ndr_unpack
24 from samba.dcerpc import security
25
26 from getpass import getpass
27 from samba.auth import system_session
28 from samba.samdb import SamDB
29 from samba.dsdb import (
30     GTYPE_SECURITY_DOMAIN_LOCAL_GROUP,
31     GTYPE_SECURITY_GLOBAL_GROUP,
32     GTYPE_SECURITY_UNIVERSAL_GROUP,
33     GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP,
34     GTYPE_DISTRIBUTION_GLOBAL_GROUP,
35     GTYPE_DISTRIBUTION_UNIVERSAL_GROUP,
36 )
37
38 security_group = dict({"Domain": GTYPE_SECURITY_DOMAIN_LOCAL_GROUP, "Global": GTYPE_SECURITY_GLOBAL_GROUP, "Universal": GTYPE_SECURITY_UNIVERSAL_GROUP})
39 distribution_group = dict({"Domain": GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP, "Global": GTYPE_DISTRIBUTION_GLOBAL_GROUP, "Universal": GTYPE_DISTRIBUTION_UNIVERSAL_GROUP})
40
41
42 class cmd_group_add(Command):
43     """Creates a new AD group.
44
45 This command creates a new Active Directory group.  The groupname specified on the command is a unique sAMAccountName.
46
47 An Active Directory group may contain user and computer accounts as well as other groups.  An administrator creates a group and adds members to that group so they can be managed as a single entity.  This helps to simplify security and system administration.
48
49 Groups may also be used to establish email distribution lists, using --group-type=Distribution.
50
51 Groups are located in domains in organizational units (OUs).  The group's scope is a characteristic of the group that designates the extent to which the group is applied within the domain tree or forest.
52
53 The group location (OU), type (security or distribution) and scope may all be specified on the samba-tool command when the group is created.
54
55 The command may be run from the root userid or another authorized userid.  The
56 -H or --URL= option can be used to execute the command on a remote server.
57
58 Example1:
59 samba-tool group add Group1 -H ldap://samba.samdom.example.com --description='Simple group'
60
61 Example1 adds a new group with the name Group1 added to the Users container on a remote LDAP server.  The -U parameter is used to pass the userid and password of a user that exists on the remote server and is authorized to issue the command on that server.  It defaults to the security type and global scope.
62
63 Example2:
64 sudo samba-tool group add Group2 --group-type=Distribution
65
66 Example2 adds a new distribution group to the local server.  The command is run under root using the sudo command.
67 """
68
69     synopsis = "%prog <groupname> [options]"
70
71     takes_optiongroups = {
72         "sambaopts": options.SambaOptions,
73         "versionopts": options.VersionOptions,
74         "credopts": options.CredentialsOptions,
75     }
76
77     takes_options = [
78         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
79                metavar="URL", dest="H"),
80         Option("--groupou",
81            help="Alternative location (without domainDN counterpart) to default CN=Users in which new user object will be created",
82            type=str),
83         Option("--group-scope", type="choice", choices=["Domain", "Global", "Universal"],
84             help="Group scope (Domain | Global | Universal)"),
85         Option("--group-type", type="choice", choices=["Security", "Distribution"],
86             help="Group type (Security | Distribution)"),
87         Option("--description", help="Group's description", type=str),
88         Option("--mail-address", help="Group's email address", type=str),
89         Option("--notes", help="Groups's notes", type=str),
90     ]
91
92     takes_args = ["groupname"]
93
94     def run(self, groupname, credopts=None, sambaopts=None,
95             versionopts=None, H=None, groupou=None, group_scope=None,
96             group_type=None, description=None, mail_address=None, notes=None):
97
98         if (group_type or "Security") == "Security":
99             gtype = security_group.get(group_scope, GTYPE_SECURITY_GLOBAL_GROUP)
100         else:
101             gtype = distribution_group.get(group_scope, GTYPE_DISTRIBUTION_GLOBAL_GROUP)
102
103         lp = sambaopts.get_loadparm()
104         creds = credopts.get_credentials(lp, fallback_machine=True)
105
106         try:
107             samdb = SamDB(url=H, session_info=system_session(),
108                           credentials=creds, lp=lp)
109             samdb.newgroup(groupname, groupou=groupou, grouptype = gtype,
110                           description=description, mailaddress=mail_address, notes=notes)
111         except Exception, e:
112             # FIXME: catch more specific exception
113             raise CommandError('Failed to create group "%s"' % groupname, e)
114         self.outf.write("Added group %s\n" % groupname)
115
116
117 class cmd_group_delete(Command):
118     """Deletes an AD group.
119
120 The command deletes an existing AD group from the Active Directory domain.  The groupname specified on the command is the sAMAccountName.
121
122 Deleting a group is a permanent operation.  When a group is deleted, all permissions and rights that users in the group had inherited from the group account are deleted as well.
123
124 The command may be run from the root userid or another authorized userid.  The -H or --URL option can be used to execute the command on a remote server.
125
126 Example1:
127 samba-tool group delete Group1 -H ldap://samba.samdom.example.com -Uadministrator%passw0rd
128
129 Example1 shows how to delete an AD group from a remote LDAP server.  The -U parameter is used to pass the userid and password of a user that exists on the remote server and is authorized to issue the command on that server.
130
131 Example2:
132 sudo samba-tool group delete Group2
133
134 Example2 deletes group Group2 from the local server.  The command is run under root using the sudo command.
135 """
136
137     synopsis = "%prog <groupname> [options]"
138
139     takes_optiongroups = {
140         "sambaopts": options.SambaOptions,
141         "versionopts": options.VersionOptions,
142         "credopts": options.CredentialsOptions,
143     }
144
145     takes_options = [
146         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
147                metavar="URL", dest="H"),
148     ]
149
150     takes_args = ["groupname"]
151
152     def run(self, groupname, credopts=None, sambaopts=None, versionopts=None, H=None):
153
154         lp = sambaopts.get_loadparm()
155         creds = credopts.get_credentials(lp, fallback_machine=True)
156
157         try:
158             samdb = SamDB(url=H, session_info=system_session(),
159                           credentials=creds, lp=lp)
160             samdb.deletegroup(groupname)
161         except Exception, e:
162             # FIXME: catch more specific exception
163             raise CommandError('Failed to remove group "%s"' % groupname, e)
164         self.outf.write("Deleted group %s\n" % groupname)
165
166
167 class cmd_group_add_members(Command):
168     """Add members to an AD group.
169
170 This command adds one or more members to an existing Active Directory group.  The command accepts one or more group member names seperated by commas.  A group member may be a user or computer account or another Active Directory group.
171
172 When a member is added to a group the member may inherit permissions and rights from the group.  Likewise, when permission or rights of a group are changed, the changes may reflect in the members through inheritance.
173
174 Example1:
175 samba-tool group addmembers supergroup Group1,Group2,User1 -H ldap://samba.samdom.example.com -Uadministrator%passw0rd
176
177 Example1 shows how to add two groups, Group1 and Group2 and one user account, User1, to the existing AD group named supergroup.  The command will be run on a remote server specified with the -H.  The -U parameter is used to pass the userid and password of a user authorized to issue the command on the remote server.
178
179 Example2:
180 sudo samba-tool group addmembers supergroup User2
181
182 Example2 shows how to add a single user account, User2, to the supergroup AD group.  It uses the sudo command to run as root when issuing the command.
183 """
184
185     synopsis = "%prog <groupname> <listofmembers> [options]"
186
187     takes_optiongroups = {
188         "sambaopts": options.SambaOptions,
189         "versionopts": options.VersionOptions,
190         "credopts": options.CredentialsOptions,
191     }
192
193     takes_options = [
194         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
195                metavar="URL", dest="H"),
196     ]
197
198     takes_args = ["groupname", "listofmembers"]
199
200     def run(self, groupname, listofmembers, credopts=None, sambaopts=None,
201             versionopts=None, H=None):
202
203         lp = sambaopts.get_loadparm()
204         creds = credopts.get_credentials(lp, fallback_machine=True)
205
206         try:
207             samdb = SamDB(url=H, session_info=system_session(),
208                           credentials=creds, lp=lp)
209             groupmembers = listofmembers.split(',')
210             samdb.add_remove_group_members(groupname, groupmembers,
211                     add_members_operation=True)
212         except Exception, e:
213             # FIXME: catch more specific exception
214             raise CommandError('Failed to add members "%s" to group "%s"' % (
215                 listofmembers, groupname), e)
216         self.outf.write("Added members to group %s\n" % groupname)
217
218
219 class cmd_group_remove_members(Command):
220     """Remove members from an AD group.
221
222 This command removes one or more members from an existing Active Directory group.  The command accepts one or more group member names seperated by commas.  A group member may be a user or computer account or another Active Directory group that is a member of the group specified on the command.
223
224 When a member is removed from a group, inherited permissions and rights will no longer apply to the member.
225
226 Example1:
227 samba-tool group removemembers supergroup Group1 -H ldap://samba.samdom.example.com -Uadministrator%passw0rd
228
229 Example1 shows how to remove Group1 from supergroup.  The command will run on the remote server specified on the -H parameter.  The -U parameter is used to pass the userid and password of a user authorized to issue the command on the remote server.
230
231 Example2:
232 sudo samba-tool group removemembers supergroup User1
233
234 Example2 shows how to remove a single user account, User2, from the supergroup AD group.  It uses the sudo command to run as root when issuing the command.
235 """
236
237     synopsis = "%prog <groupname> <listofmembers> [options]"
238
239     takes_optiongroups = {
240         "sambaopts": options.SambaOptions,
241         "versionopts": options.VersionOptions,
242         "credopts": options.CredentialsOptions,
243     }
244
245     takes_options = [
246         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
247                metavar="URL", dest="H"),
248     ]
249
250     takes_args = ["groupname", "listofmembers"]
251
252     def run(self, groupname, listofmembers, credopts=None, sambaopts=None,
253             versionopts=None, H=None):
254
255         lp = sambaopts.get_loadparm()
256         creds = credopts.get_credentials(lp, fallback_machine=True)
257
258         try:
259             samdb = SamDB(url=H, session_info=system_session(),
260                           credentials=creds, lp=lp)
261             samdb.add_remove_group_members(groupname, listofmembers.split(","),
262                     add_members_operation=False)
263         except Exception, e:
264             # FIXME: Catch more specific exception
265             raise CommandError('Failed to remove members "%s" from group "%s"' % (listofmembers, groupname), e)
266         self.outf.write("Removed members from group %s\n" % groupname)
267
268
269 class cmd_group_list(Command):
270     """List all groups."""
271
272     synopsis = "%prog [options]"
273
274     takes_options = [
275         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
276                metavar="URL", dest="H"),
277         ]
278
279     takes_optiongroups = {
280         "sambaopts": options.SambaOptions,
281         "credopts": options.CredentialsOptions,
282         "versionopts": options.VersionOptions,
283         }
284
285     def run(self, sambaopts=None, credopts=None, versionopts=None, H=None):
286         lp = sambaopts.get_loadparm()
287         creds = credopts.get_credentials(lp, fallback_machine=True)
288
289         samdb = SamDB(url=H, session_info=system_session(),
290             credentials=creds, lp=lp)
291
292         domain_dn = samdb.domain_dn()
293         res = samdb.search(domain_dn, scope=ldb.SCOPE_SUBTREE,
294                     expression=("(objectClass=group)"),
295                     attrs=["samaccountname"])
296         if (len(res) == 0):
297             return
298
299         for msg in res:
300             self.outf.write("%s\n" % msg.get("samaccountname", idx=0))
301
302
303 class cmd_group_list_members(Command):
304     """List all members of an AD group.
305
306 This command lists members from an existing Active Directory group. The command accepts one group name.
307
308 Example1:
309 samba-tool group listmembers \"Domain Users\" -H ldap://samba.samdom.example.com -Uadministrator%passw0rd
310 """
311
312     synopsis = "%prog <groupname> [options]"
313
314     takes_options = [
315         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
316                metavar="URL", dest="H"),
317         ]
318
319     takes_optiongroups = {
320         "sambaopts": options.SambaOptions,
321         "credopts": options.CredentialsOptions,
322         "versionopts": options.VersionOptions,
323         }
324
325     takes_args = ["groupname"]
326
327     def run(self, groupname, credopts=None, sambaopts=None, versionopts=None, H=None):
328         lp = sambaopts.get_loadparm()
329         creds = credopts.get_credentials(lp, fallback_machine=True)
330
331         try:
332             samdb = SamDB(url=H, session_info=system_session(),
333                           credentials=creds, lp=lp)
334
335             search_filter = "(&(objectClass=group)(samaccountname=%s))" % groupname
336             res = samdb.search(samdb.domain_dn(), scope=ldb.SCOPE_SUBTREE,
337                                expression=(search_filter),
338                                attrs=["objectSid"])
339
340             if (len(res) != 1):
341                 return
342
343             group_dn = res[0].get('dn', idx=0)
344             object_sid = res[0].get('objectSid', idx=0)
345
346             object_sid = ndr_unpack(security.dom_sid, object_sid)
347             (group_dom_sid, rid) = object_sid.split()
348
349             search_filter = "(|(primaryGroupID=%s)(memberOf=%s))" % (rid, group_dn)
350             res = samdb.search(samdb.domain_dn(), scope=ldb.SCOPE_SUBTREE,
351                                expression=(search_filter),
352                                attrs=["samAccountName", "cn"])
353
354             if (len(res) == 0):
355                 return
356
357             for msg in res:
358                 member_name = msg.get("samAccountName", idx=0)
359                 if member_name is None:
360                     member_name = msg.get("cn", idx=0)
361                 self.outf.write("%s\n" % member_name)
362
363         except Exception, e:
364             raise CommandError('Failed to list members of "%s" group ' % groupname, e)
365
366
367 class cmd_group(SuperCommand):
368     """Group management."""
369
370     subcommands = {}
371     subcommands["add"] = cmd_group_add()
372     subcommands["delete"] = cmd_group_delete()
373     subcommands["addmembers"] = cmd_group_add_members()
374     subcommands["removemembers"] = cmd_group_remove_members()
375     subcommands["list"] = cmd_group_list()
376     subcommands["listmembers"] = cmd_group_list_members()