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