samba-tool: Improve getopt.py error handling
[obnox/samba/samba-obnox.git] / source4 / scripting / python / samba / getopt.py
1 #!/usr/bin/env python
2
3 # Samba-specific bits for optparse
4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 #
19
20 """Support for parsing Samba-related command-line options."""
21
22 __docformat__ = "restructuredText"
23
24 import optparse
25 import os
26 from samba.credentials import (
27     Credentials,
28     AUTO_USE_KERBEROS,
29     DONT_USE_KERBEROS,
30     MUST_USE_KERBEROS,
31     )
32 from samba.hostconfig import Hostconfig
33 import sys
34
35
36 class SambaOptions(optparse.OptionGroup):
37     """General Samba-related command line options."""
38
39     def __init__(self, parser):
40         from samba.param import LoadParm
41         optparse.OptionGroup.__init__(self, parser, "Samba Common Options")
42         self.add_option("-s", "--configfile", action="callback",
43                         type=str, metavar="FILE", help="Configuration file",
44                         callback=self._load_configfile)
45         self.add_option("-d", "--debuglevel", action="callback",
46                         type=int, metavar="DEBUGLEVEL", help="debug level",
47                         callback=self._set_debuglevel)
48         self.add_option("--option", action="callback",
49                         type=str, metavar="OPTION",
50                         help="set smb.conf option from command line",
51                         callback=self._set_option)
52         self.add_option("--realm", action="callback",
53                         type=str, metavar="REALM", help="set the realm name",
54                         callback=self._set_realm)
55         self._configfile = None
56         self._lp = LoadParm()
57         self.realm = None
58
59     def get_loadparm_path(self):
60         """Return path to the smb.conf file specified on the command line."""
61         return self._configfile
62
63     def _load_configfile(self, option, opt_str, arg, parser):
64         self._configfile = arg
65
66     def _set_debuglevel(self, option, opt_str, arg, parser):
67         if arg < 0:
68             raise optparse.OptionValueError("invalid %s option value: %s" %
69                                             (opt_str, arg))
70         self._lp.set('debug level', str(arg))
71
72     def _set_realm(self, option, opt_str, arg, parser):
73         self._lp.set('realm', arg)
74         self.realm = arg
75
76     def _set_option(self, option, opt_str, arg, parser):
77         if arg.find('=') == -1:
78             raise optparse.OptionValueError("--option option takes a 'a=b' argument")
79         a = arg.split('=')
80         try:
81             self._lp.set(a[0], a[1])
82         except Exception:
83             raise optparse.OptionValueError("invalid --option option value: %s"
84                                             % arg)
85
86     def get_loadparm(self):
87         """Return loadparm object with data specified on the command line."""
88         if self._configfile is not None:
89             self._lp.load(self._configfile)
90         elif os.getenv("SMB_CONF_PATH") is not None:
91             self._lp.load(os.getenv("SMB_CONF_PATH"))
92         else:
93             self._lp.load_default()
94         return self._lp
95
96     def get_hostconfig(self):
97         return Hostconfig(self.get_loadparm())
98
99
100 class VersionOptions(optparse.OptionGroup):
101     """Command line option for printing Samba version."""
102     def __init__(self, parser):
103         optparse.OptionGroup.__init__(self, parser, "Version Options")
104         self.add_option("--version", action="callback",
105                 callback=self._display_version,
106                 help="Display version number")
107
108     def _display_version(self, option, opt_str, arg, parser):
109         import samba
110         print samba.version
111         sys.exit(0)
112
113
114 def parse_kerberos_arg(arg, opt_str):
115     if arg.lower() in ["yes", 'true', '1']:
116         return MUST_USE_KERBEROS
117     elif arg.lower() in ["no", 'false', '0']:
118         return DONT_USE_KERBEROS
119     elif arg.lower() in ["auto"]:
120         return AUTO_USE_KERBEROS
121     else:
122         raise optparse.OptionValueError("invalid %s option value: %s" %
123                                         (opt_str, arg))
124
125
126 class CredentialsOptions(optparse.OptionGroup):
127     """Command line options for specifying credentials."""
128
129     def __init__(self, parser):
130         self.no_pass = True
131         self.ipaddress = None
132         optparse.OptionGroup.__init__(self, parser, "Credentials Options")
133         self.add_option("--simple-bind-dn", metavar="DN", action="callback",
134                         callback=self._set_simple_bind_dn, type=str,
135                         help="DN to use for a simple bind")
136         self.add_option("--password", metavar="PASSWORD", action="callback",
137                         help="Password", type=str, callback=self._set_password)
138         self.add_option("-U", "--username", metavar="USERNAME",
139                         action="callback", type=str,
140                         help="Username", callback=self._parse_username)
141         self.add_option("-W", "--workgroup", metavar="WORKGROUP",
142                         action="callback", type=str,
143                         help="Workgroup", callback=self._parse_workgroup)
144         self.add_option("-N", "--no-pass", action="store_true",
145                         help="Don't ask for a password")
146         self.add_option("-k", "--kerberos", metavar="KERBEROS",
147                         action="callback", type=str,
148                         help="Use Kerberos", callback=self._set_kerberos)
149         self.add_option("", "--ipaddress", metavar="IPADDRESS",
150                         action="callback", type=str,
151                         help="IP address of server",
152                         callback=self._set_ipaddress)
153         self.creds = Credentials()
154
155     def _parse_username(self, option, opt_str, arg, parser):
156         self.creds.parse_string(arg)
157
158     def _parse_workgroup(self, option, opt_str, arg, parser):
159         self.creds.set_domain(arg)
160
161     def _set_password(self, option, opt_str, arg, parser):
162         self.creds.set_password(arg)
163         self.no_pass = False
164
165     def _set_ipaddress(self, option, opt_str, arg, parser):
166         self.ipaddress = arg
167
168     def _set_kerberos(self, option, opt_str, arg, parser):
169         self.creds.set_kerberos_state(parse_kerberos_arg(arg, opt_str))
170
171     def _set_simple_bind_dn(self, option, opt_str, arg, parser):
172         self.creds.set_bind_dn(arg)
173
174     def get_credentials(self, lp, fallback_machine=False):
175         """Obtain the credentials set on the command-line.
176
177         :param lp: Loadparm object to use.
178         :return: Credentials object
179         """
180         self.creds.guess(lp)
181         if self.no_pass:
182             self.creds.set_cmdline_callbacks()
183
184         # possibly fallback to using the machine account, if we have
185         # access to the secrets db
186         if fallback_machine and not self.creds.authentication_requested():
187             try:
188                 self.creds.set_machine_account(lp)
189             except Exception:
190                 pass
191
192         return self.creds
193
194
195 class CredentialsOptionsDouble(CredentialsOptions):
196     """Command line options for specifying credentials of two servers."""
197
198     def __init__(self, parser):
199         CredentialsOptions.__init__(self, parser)
200         self.no_pass2 = True
201         self.add_option("--simple-bind-dn2", metavar="DN2", action="callback",
202                         callback=self._set_simple_bind_dn2, type=str,
203                         help="DN to use for a simple bind")
204         self.add_option("--password2", metavar="PASSWORD2", action="callback",
205                         help="Password", type=str,
206                         callback=self._set_password2)
207         self.add_option("--username2", metavar="USERNAME2",
208                         action="callback", type=str,
209                         help="Username for second server",
210                         callback=self._parse_username2)
211         self.add_option("--workgroup2", metavar="WORKGROUP2",
212                         action="callback", type=str,
213                         help="Workgroup for second server",
214                         callback=self._parse_workgroup2)
215         self.add_option("--no-pass2", action="store_true",
216                         help="Don't ask for a password for the second server")
217         self.add_option("--kerberos2", metavar="KERBEROS2",
218                         action="callback", type=str,
219                         help="Use Kerberos", callback=self._set_kerberos2)
220         self.creds2 = Credentials()
221
222     def _parse_username2(self, option, opt_str, arg, parser):
223         self.creds2.parse_string(arg)
224
225     def _parse_workgroup2(self, option, opt_str, arg, parser):
226         self.creds2.set_domain(arg)
227
228     def _set_password2(self, option, opt_str, arg, parser):
229         self.creds2.set_password(arg)
230         self.no_pass2 = False
231
232     def _set_kerberos2(self, option, opt_str, arg, parser):
233         self.creds2.set_kerberos_state(parse_kerberos_arg(arg, opt_str))
234
235     def _set_simple_bind_dn2(self, option, opt_str, arg, parser):
236         self.creds2.set_bind_dn(arg)
237
238     def get_credentials2(self, lp, guess=True):
239         """Obtain the credentials set on the command-line.
240
241         :param lp: Loadparm object to use.
242         :param guess: Try guess Credentials from environment
243         :return: Credentials object
244         """
245         if guess:
246             self.creds2.guess(lp)
247         elif not self.creds2.get_username():
248             self.creds2.set_anonymous()
249
250         if self.no_pass2:
251             self.creds2.set_cmdline_callbacks()
252         return self.creds2