samba-tool: added setpassword to user
[ira/wip.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 #
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21
22 import samba.getopt as options
23 import sys
24 from getpass import getpass
25 from samba.auth import system_session
26 from samba.samdb import SamDB
27 from samba import gensec
28 from samba.net import Net
29
30 from samba.netcmd import (
31     Command,
32     CommandError,
33     SuperCommand,
34     Option,
35     )
36
37
38 class cmd_user_add(Command):
39     """Create a new user."""
40     synopsis = "%prog user add <name> [<password>]"
41
42     takes_optiongroups = {
43         "sambaopts": options.SambaOptions,
44         "credopts": options.CredentialsOptions,
45         "versionopts": options.VersionOptions,
46         }
47
48     takes_args = ["name", "password?"]
49
50     def run(self, name, password=None, credopts=None, sambaopts=None, versionopts=None):
51         lp = sambaopts.get_loadparm()
52         creds = credopts.get_credentials(lp )
53         net = Net(creds, lp, server=credopts.ipaddress)
54         net.create_user(name)
55         if password is not None:
56             net.set_password(name, creds.get_domain(), password, creds)
57
58
59 class cmd_user_delete(Command):
60     """Delete a user."""
61     synopsis = "%prog user delete <name>"
62
63     takes_optiongroups = {
64         "sambaopts": options.SambaOptions,
65         "credopts": options.CredentialsOptions,
66         "versionopts": options.VersionOptions,
67         }
68
69     takes_args = ["name"]
70
71     def run(self, name, credopts=None, sambaopts=None, versionopts=None):
72         lp = sambaopts.get_loadparm()
73         creds = credopts.get_credentials(lp, fallback_machine=True)
74         net = Net(creds, lp, server=credopts.ipaddress)
75         try:
76             net.delete_user(name)
77         except RuntimeError, msg:
78             raise CommandError("Failed to delete user %s: %s" % (name, msg))
79
80
81 class cmd_user_enable(Command):
82     """Enables a user"""
83
84     synopsis = "%prog user enable <username> [options]"
85
86
87     takes_optiongroups = {
88         "sambaopts": options.SambaOptions,
89         "versionopts": options.VersionOptions,
90         "credopts": options.CredentialsOptions,
91     }
92
93     takes_options = [
94         Option("-H", help="LDB URL for database or target server", type=str),
95         Option("--filter", help="LDAP Filter to set password on", type=str),
96         ]
97
98     takes_args = ["username?"]
99
100     def run(self, username=None, sambaopts=None, credopts=None,
101             versionopts=None, filter=None, H=None):
102         if username is None and filter is None:
103             raise CommandError("Either the username or '--filter' must be specified!")
104
105         if filter is None:
106             filter = "(&(objectClass=user)(sAMAccountName=%s))" % (username)
107
108         lp = sambaopts.get_loadparm()
109         creds = credopts.get_credentials(lp, fallback_machine=True)
110
111         samdb = SamDB(url=H, session_info=system_session(),
112             credentials=creds, lp=lp)
113         try:
114             samdb.enable_account(filter)
115         except Exception, msg:
116             raise CommandError("Failed to enable user %s: %s" % (username or filter, msg))
117         print("Enabled user %s" % (username or filter))
118
119
120 class cmd_user_setexpiry(Command):
121     """Sets the expiration of a user account"""
122
123     synopsis = "%prog user setexpiry <username> [options]"
124
125     takes_optiongroups = {
126         "sambaopts": options.SambaOptions,
127         "versionopts": options.VersionOptions,
128         "credopts": options.CredentialsOptions,
129     }
130
131     takes_options = [
132         Option("-H", help="LDB URL for database or target server", type=str),
133         Option("--filter", help="LDAP Filter to set password on", type=str),
134         Option("--days", help="Days to expiry", type=int),
135         Option("--noexpiry", help="Password does never expire", action="store_true"),
136     ]
137
138     takes_args = ["username?"]
139     def run(self, username=None, sambaopts=None, credopts=None,
140             versionopts=None, H=None, filter=None, days=None, noexpiry=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)
149
150         if days is None:
151             days = 0
152
153         samdb = SamDB(url=H, session_info=system_session(),
154             credentials=creds, lp=lp)
155
156         try:
157             samdb.setexpiry(filter, days*24*3600, no_expiry_req=noexpiry)
158         except Exception, msg:
159             raise CommandError("Failed to set expiry for user %s: %s" % (username or filter, msg))
160         print("Set expiry for user %s to %u days" % (username or filter, days))
161
162
163 class cmd_user_setpassword(Command):
164     """(Re)sets the password of a user account"""
165
166     synopsis = "%prog user setpassword [username] [options]"
167
168     takes_optiongroups = {
169         "sambaopts": options.SambaOptions,
170         "versionopts": options.VersionOptions,
171         "credopts": options.CredentialsOptions,
172     }
173
174     takes_options = [
175         Option("-H", help="LDB URL for database or target server", type=str),
176         Option("--filter", help="LDAP Filter to set password on", type=str),
177         Option("--newpassword", help="Set password", type=str),
178         Option("--must-change-at-next-login",
179             help="Force password to be changed on next login",
180             action="store_true"),
181         ]
182
183     takes_args = ["username?"]
184
185     def run(self, username=None, filter=None, credopts=None, sambaopts=None,
186             versionopts=None, H=None, newpassword=None,
187             must_change_at_next_login=None):
188         if filter is None and username is None:
189             raise CommandError("Either the username or '--filter' must be specified!")
190
191         password = newpassword
192         if password is None:
193             password = getpass("New Password: ")
194
195         if filter is None:
196             filter = "(&(objectClass=user)(sAMAccountName=%s))" % (username)
197
198         lp = sambaopts.get_loadparm()
199         creds = credopts.get_credentials(lp)
200
201         creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
202
203         samdb = SamDB(url=H, session_info=system_session(),
204                       credentials=creds, lp=lp)
205
206         try:
207             samdb.setpassword(filter, password,
208                               force_change_at_next_login=must_change_at_next_login,
209                               username=username)
210         except Exception, e:
211             raise CommandError('Failed to set password for user "%s"' % username, e)
212         print "Changed password OK"
213
214
215 class cmd_user(SuperCommand):
216     """User management [server connection needed]"""
217
218     subcommands = {}
219     subcommands["add"] = cmd_user_add()
220     subcommands["delete"] = cmd_user_delete()
221     subcommands["enable"] = cmd_user_enable()
222     subcommands["setexpiry"] = cmd_user_setexpiry()
223     subcommands["setpassword"] = cmd_user_setpassword()