b13bc0d6066cb7aca879c0e600f64c1ac545c3a4
[amitay/samba.git] / source4 / scripting / python / samba / netcmd / user.py
1 #!/usr/bin/env python
2 #
3 # user management
4 #
5 # Copyright Jelmer Vernooij 2010 <jelmer@samba.org>
6 # Copyright Theresa Halloran 2011 <theresahalloran@gmail.com>
7 # Copyright Giampaolo Lauria 2011 <lauria2@yahoo.com>
8 #
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 #
22
23 import samba.getopt as options
24 import sys
25 from getpass import getpass
26 from samba.auth import system_session
27 from samba.samdb import SamDB
28 from samba import gensec
29 from samba.net import Net
30
31 from samba.netcmd import (
32     Command,
33     CommandError,
34     SuperCommand,
35     Option,
36     )
37
38
39
40 class cmd_user_add(Command):
41     """Creates a new user"""
42
43     synopsis = "%prog user add <username> [<password>] [options]"
44
45     takes_options = [
46         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
47                 metavar="URL", dest="H"),
48         Option("--must-change-at-next-login",
49                 help="Force password to be changed on next login",
50                 action="store_true"),
51         Option("--use-username-as-cn",
52                 help="Force use of username as user's CN",
53                 action="store_true"),
54         Option("--userou",
55                 help="Alternative location (without domainDN counterpart) to default CN=Users in which new user object will be created",
56                 type=str),
57         Option("--surname", help="User's surname", type=str),
58         Option("--given-name", help="User's given name", type=str),
59         Option("--initials", help="User's initials", type=str),
60         Option("--profile-path", help="User's profile path", type=str),
61         Option("--script-path", help="User's logon script path", type=str),
62         Option("--home-drive", help="User's home drive letter", type=str),
63         Option("--home-directory", help="User's home directory path", type=str),
64         Option("--job-title", help="User's job title", type=str),
65         Option("--department", help="User's department", type=str),
66         Option("--company", help="User's company", type=str),
67         Option("--description", help="User's description", type=str),
68         Option("--mail-address", help="User's email address", type=str),
69         Option("--internet-address", help="User's home page", type=str),
70         Option("--telephone-number", help="User's phone number", type=str),
71         Option("--physical-delivery-office", help="User's office location", type=str),
72     ]
73
74     takes_args = ["username", "password?"]
75
76     def run(self, username, password=None, credopts=None, sambaopts=None,
77             versionopts=None, H=None, must_change_at_next_login=None,
78             use_username_as_cn=None, userou=None, surname=None, given_name=None, initials=None,
79             profile_path=None, script_path=None, home_drive=None, home_directory=None,
80             job_title=None, department=None, company=None, description=None,
81             mail_address=None, internet_address=None, telephone_number=None, physical_delivery_office=None):
82
83         while 1:
84             if password is not None and password is not '':
85                 break
86             password = getpass("New Password: ")
87
88         lp = sambaopts.get_loadparm()
89         creds = credopts.get_credentials(lp)
90
91         try:
92             samdb = SamDB(url=H, session_info=system_session(),
93                           credentials=creds, lp=lp)
94             samdb.newuser(username, password,
95                           force_password_change_at_next_login_req=must_change_at_next_login,
96                           useusernameascn=use_username_as_cn, userou=userou, surname=surname, givenname=given_name, initials=initials,
97                           profilepath=profile_path, homedrive=home_drive, scriptpath=script_path, homedirectory=home_directory,
98                           jobtitle=job_title, department=department, company=company, description=description,
99                           mailaddress=mail_address, internetaddress=internet_address,
100                           telephonenumber=telephone_number, physicaldeliveryoffice=physical_delivery_office)
101         except Exception, e:
102             raise CommandError("Failed to add user '%s': " % username, e)
103
104         print("User '%s' created successfully" % username)
105
106
107
108 class cmd_user_delete(Command):
109     """Delete a user."""
110
111     synopsis = "%prog user delete <username> [options]"
112
113     takes_args = ["name"]
114
115     def run(self, name, credopts=None, sambaopts=None, versionopts=None):
116         lp = sambaopts.get_loadparm()
117         creds = credopts.get_credentials(lp, fallback_machine=True)
118         net = Net(creds, lp, server=credopts.ipaddress)
119         try:
120             net.delete_user(name)
121         except RuntimeError, msg:
122             raise CommandError("Failed to delete user '%s': %s" % (name, msg))
123
124
125
126 class cmd_user_enable(Command):
127     """Enables a user"""
128
129     synopsis = "%prog user enable (<username>|--filter <filter>) [options]"
130
131     takes_options = [
132         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
133                metavar="URL", dest="H"),
134         Option("--filter", help="LDAP Filter to set password on", type=str),
135         ]
136
137     takes_args = ["username?"]
138
139     def run(self, username=None, sambaopts=None, credopts=None,
140             versionopts=None, filter=None, H=None):
141         if username is None and filter is None:
142             raise CommandError("Either the username or '--filter' must be specified!")
143
144         if filter is None:
145             filter = "(&(objectClass=user)(sAMAccountName=%s))" % (username)
146
147         lp = sambaopts.get_loadparm()
148         creds = credopts.get_credentials(lp, fallback_machine=True)
149
150         samdb = SamDB(url=H, session_info=system_session(),
151             credentials=creds, lp=lp)
152         try:
153             samdb.enable_account(filter)
154         except Exception, msg:
155             raise CommandError("Failed to enable user '%s': %s" % (username or filter, msg))
156         print("Enabled user '%s'" % (username or filter))
157
158
159
160 class cmd_user_setexpiry(Command):
161     """Sets the expiration of a user account"""
162
163     synopsis = "%prog user setexpiry (<username>|--filter <filter>) [options]"
164
165     takes_options = [
166         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
167                metavar="URL", dest="H"),
168         Option("--filter", help="LDAP Filter to set password on", type=str),
169         Option("--days", help="Days to expiry", type=int, default=0),
170         Option("--noexpiry", help="Password does never expire", action="store_true", default=False),
171     ]
172
173     takes_args = ["username?"]
174
175     def run(self, username=None, sambaopts=None, credopts=None,
176             versionopts=None, H=None, filter=None, days=None, noexpiry=None):
177         if username is None and filter is None:
178             raise CommandError("Either the username or '--filter' must be specified!")
179
180         if filter is None:
181             filter = "(&(objectClass=user)(sAMAccountName=%s))" % (username)
182
183         lp = sambaopts.get_loadparm()
184         creds = credopts.get_credentials(lp)
185
186         samdb = SamDB(url=H, session_info=system_session(),
187             credentials=creds, lp=lp)
188
189         try:
190             samdb.setexpiry(filter, days*24*3600, no_expiry_req=noexpiry)
191         except Exception, msg:
192             raise CommandError("Failed to set expiry for user '%s': %s" % (username or filter, msg))
193         print("Set expiry for user '%s' to %u days" % (username or filter, days))
194
195
196
197 class cmd_user_password(Command):
198     """Change password for a user account (the one provided in authentication)"""
199
200     synopsis = "%prog user password [options]"
201
202     takes_options = [
203         Option("--newpassword", help="New password", type=str),
204         ]
205
206     def run(self, credopts=None, sambaopts=None, versionopts=None,
207                 newpassword=None):
208
209         lp = sambaopts.get_loadparm()
210         creds = credopts.get_credentials(lp)
211
212         # FIXME: How to ensure user is authenticated before prompting for new password?
213         net = Net(creds, lp, server=credopts.ipaddress)
214
215         password = newpassword
216         while 1:
217             if password is not None and password is not '':
218                 break
219             password = getpass("New Password: ")
220
221         try:
222             net.change_password(password)
223         except Exception, msg:
224             raise CommandError("Failed to change password : %s" % msg)
225         print "Changed password OK"
226
227
228
229 class cmd_user_setpassword(Command):
230     """(Re)sets the password of a user account"""
231
232     synopsis = "%prog user setpassword (<username>|--filter <filter>) [options]"
233
234     takes_options = [
235         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
236                metavar="URL", dest="H"),
237         Option("--filter", help="LDAP Filter to set password on", type=str),
238         Option("--newpassword", help="Set password", type=str),
239         Option("--must-change-at-next-login",
240                help="Force password to be changed on next login",
241                action="store_true"),
242         ]
243
244     takes_args = ["username?"]
245
246     def run(self, username=None, filter=None, credopts=None, sambaopts=None,
247             versionopts=None, H=None, newpassword=None,
248             must_change_at_next_login=None):
249         if filter is None and username is None:
250             raise CommandError("Either the username or '--filter' must be specified!")
251
252         password = newpassword
253         while 1:
254             if password is not None and password is not '':
255                 break
256             password = getpass("New Password: ")
257
258         if filter is None:
259             filter = "(&(objectClass=user)(sAMAccountName=%s))" % (username)
260
261         lp = sambaopts.get_loadparm()
262         creds = credopts.get_credentials(lp)
263
264         creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
265
266         samdb = SamDB(url=H, session_info=system_session(),
267                       credentials=creds, lp=lp)
268
269         try:
270             samdb.setpassword(filter, password,
271                               force_change_at_next_login=must_change_at_next_login,
272                               username=username)
273         except Exception, msg:
274             raise CommandError("Failed to set password for user '%s': %s" % (username or filter, msg))
275         print "Changed password OK"
276
277
278
279 class cmd_user(SuperCommand):
280     """User management [server connection needed]"""
281
282     subcommands = {}
283     subcommands["add"] = cmd_user_add()
284     subcommands["delete"] = cmd_user_delete()
285     subcommands["enable"] = cmd_user_enable()
286     subcommands["setexpiry"] = cmd_user_setexpiry()
287     subcommands["password"] = cmd_user_password()
288     subcommands["setpassword"] = cmd_user_setpassword()