9c9add84330cb0500cf30a19db7b080f9110d527
[samba.git] / source4 / scripting / python / samba / netcmd / group.py
1 #!/usr/bin/env python
2 #
3 # Adds a new user to a Samba4 server
4 # Copyright Jelmer Vernooij 2008
5 #
6 # Based on the original in EJS:
7 # Copyright Andrew Tridgell 2005
8 # Copyright Giampaolo Lauria 2011 <lauria2@yahoo.com>
9 #
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
14 #
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License
21 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
23 import samba.getopt as options
24 from samba.netcmd import Command, SuperCommand, CommandError, Option
25 import ldb
26
27 from getpass import getpass
28 from samba.auth import system_session
29 from samba.samdb import SamDB
30 from samba.dsdb import (
31     GTYPE_SECURITY_DOMAIN_LOCAL_GROUP,
32     GTYPE_SECURITY_GLOBAL_GROUP,
33     GTYPE_SECURITY_UNIVERSAL_GROUP,
34     GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP,
35     GTYPE_DISTRIBUTION_GLOBAL_GROUP,
36     GTYPE_DISTRIBUTION_UNIVERSAL_GROUP,
37 )
38
39 security_group = dict({"Domain": GTYPE_SECURITY_DOMAIN_LOCAL_GROUP, "Global": GTYPE_SECURITY_GLOBAL_GROUP, "Universal": GTYPE_SECURITY_UNIVERSAL_GROUP})
40 distribution_group = dict({"Domain": GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP, "Global": GTYPE_DISTRIBUTION_GLOBAL_GROUP, "Universal": GTYPE_DISTRIBUTION_UNIVERSAL_GROUP})
41
42
43 class cmd_group_add(Command):
44     """Creates a new AD group
45
46 This command creates a new Active Directory group.  The groupname specified on the command is a unique sAMAccountName.
47
48 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.
49
50 Groups may also be used to establish email distribution lists, using --group-type=Distribution.
51
52 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.
53
54 The group location (OU), type (security or distribution) and scope may all be specified on the samba-tool command when the group is created.
55
56 The command may be run from the root userid or another authorized userid.  The
57 -H or --URL= option can be used to execute the command on a remote server.
58
59 Example1:
60 samba-tool group add Group1 -H ldap://samba.samdom.example.com --description='Simple group'
61
62 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.
63
64 Example2:
65 sudo samba-tool group add Group2 --group-type=Distribution
66
67 Example2 adds a new distribution group to the local server.  The command is run under root using the sudo command.
68 """
69
70     synopsis = "%prog <groupname> [options]"
71
72     takes_options = [
73         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
74                metavar="URL", dest="H"),
75         Option("--groupou",
76            help="Alternative location (without domainDN counterpart) to default CN=Users in which new user object will be created",
77            type=str),
78         Option("--group-scope", type="choice", choices=["Domain", "Global", "Universal"],
79             help="Group scope (Domain | Global | Universal)"),
80         Option("--group-type", type="choice", choices=["Security", "Distribution"],
81             help="Group type (Security | Distribution)"),
82         Option("--description", help="Group's description", type=str),
83         Option("--mail-address", help="Group's email address", type=str),
84         Option("--notes", help="Groups's notes", type=str),
85     ]
86
87     takes_args = ["groupname"]
88
89     def run(self, groupname, credopts=None, sambaopts=None,
90             versionopts=None, H=None, groupou=None, group_scope=None,
91             group_type=None, description=None, mail_address=None, notes=None):
92
93         if (group_type or "Security") == "Security":
94               gtype = security_group.get(group_scope, GTYPE_SECURITY_GLOBAL_GROUP)
95         else:
96               gtype = distribution_group.get(group_scope, GTYPE_DISTRIBUTION_GLOBAL_GROUP)
97
98         lp = sambaopts.get_loadparm()
99         creds = credopts.get_credentials(lp, fallback_machine=True)
100
101         try:
102             samdb = SamDB(url=H, session_info=system_session(),
103                           credentials=creds, lp=lp)
104             samdb.newgroup(groupname, groupou=groupou, grouptype = gtype,
105                           description=description, mailaddress=mail_address, notes=notes)
106         except Exception, e:
107             # FIXME: catch more specific exception
108             raise CommandError('Failed to create group "%s"' % groupname, e)
109         self.outf.write("Added group %s\n" % groupname)
110
111
112 class cmd_group_delete(Command):
113     """Deletes an AD group
114
115 The command deletes an existing AD group from the Active Directory domain.  The groupname specified on the command is the sAMAccountName.
116
117 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.
118
119 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.
120
121 Example1:
122 samba-tool group delete Group1 -H ldap://samba.samdom.example.com -Uadministrator%passw0rd
123
124 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.
125
126 Example2:
127 sudo samba-tool group delete Group2
128
129 Example2 deletes group Group2 from the local server.  The command is run under root using the sudo command.
130 """
131
132     synopsis = "%prog <groupname> [options]"
133
134     takes_options = [
135         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
136                metavar="URL", dest="H"),
137     ]
138
139     takes_args = ["groupname"]
140
141     def run(self, groupname, credopts=None, sambaopts=None, versionopts=None, H=None):
142
143         lp = sambaopts.get_loadparm()
144         creds = credopts.get_credentials(lp, fallback_machine=True)
145
146         try:
147             samdb = SamDB(url=H, session_info=system_session(),
148                           credentials=creds, lp=lp)
149             samdb.deletegroup(groupname)
150         except Exception, e:
151             # FIXME: catch more specific exception
152             raise CommandError('Failed to remove group "%s"' % groupname, e)
153         self.outf.write("Deleted group %s\n" % groupname)
154
155
156 class cmd_group_add_members(Command):
157     """Add members to an AD group
158
159 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.
160
161 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.
162
163 Example1:
164 samba-tool group addmembers supergroup Group1,Group2,User1 -H ldap://samba.samdom.example.com -Uadministrator%passw0rd
165
166 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.
167
168 Example2:
169 sudo samba-tool group addmembers supergroup User2
170
171 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.
172 """
173
174     synopsis = "%prog <groupname> <listofmembers> [options]"
175
176     takes_options = [
177         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
178                metavar="URL", dest="H"),
179     ]
180
181     takes_args = ["groupname", "listofmembers"]
182
183     def run(self, groupname, listofmembers, credopts=None, sambaopts=None,
184             versionopts=None, H=None):
185
186         lp = sambaopts.get_loadparm()
187         creds = credopts.get_credentials(lp, fallback_machine=True)
188
189         try:
190             samdb = SamDB(url=H, session_info=system_session(),
191                           credentials=creds, lp=lp)
192             samdb.add_remove_group_members(groupname, listofmembers, add_members_operation=True)
193         except Exception, e:
194             # FIXME: catch more specific exception
195             raise CommandError('Failed to add members "%s" to group "%s"' % (
196                 listofmembers, groupname), e)
197         self.outf.write("Added members to group %s\n" % groupname)
198
199
200 class cmd_group_remove_members(Command):
201     """Remove members from an AD group
202
203 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.
204
205 When a member is removed from a group, inherited permissions and rights will no longer apply to the member.
206
207 Example1:
208 samba-tool group removemembers supergroup Group1 -H ldap://samba.samdom.example.com -Uadministrator%passw0rd
209
210 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.
211
212 Example2:
213 sudo samba-tool group removemembers supergroup User1
214
215 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.
216 """
217
218     synopsis = "%prog <groupname> <listofmembers> [options]"
219
220     takes_options = [
221         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
222                metavar="URL", dest="H"),
223     ]
224
225     takes_args = ["groupname", "listofmembers"]
226
227     def run(self, groupname, listofmembers, credopts=None, sambaopts=None,
228             versionopts=None, H=None):
229
230         lp = sambaopts.get_loadparm()
231         creds = credopts.get_credentials(lp, fallback_machine=True)
232
233         try:
234             samdb = SamDB(url=H, session_info=system_session(),
235                           credentials=creds, lp=lp)
236             samdb.add_remove_group_members(groupname, listofmembers, add_members_operation=False)
237         except Exception, e:
238             # FIXME: Catch more specific exception
239             raise CommandError('Failed to remove members "%s" from group "%s"' % (listofmembers, groupname), e)
240         self.outf.write("Removed members from group %s\n" % groupname)
241
242
243 class cmd_group(SuperCommand):
244     """Group management"""
245
246     subcommands = {}
247     subcommands["add"] = cmd_group_add()
248     subcommands["delete"] = cmd_group_delete()
249     subcommands["addmembers"] = cmd_group_add_members()
250     subcommands["removemembers"] = cmd_group_remove_members()