1 # Samba-specific bits for optparse
2 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007
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.
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.
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/>.
18 """Support for parsing Samba-related command-line options."""
20 __docformat__
= "restructuredText"
25 from samba
.credentials
import (
34 class SambaOptions(optparse
.OptionGroup
):
35 """General Samba-related command line options."""
37 def __init__(self
, parser
):
38 from samba
import fault_setup
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=str, 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
59 def get_loadparm_path(self
):
60 """Return path to the smb.conf file specified on the command line."""
61 return self
._configfile
63 def _load_configfile(self
, option
, opt_str
, arg
, parser
):
64 self
._configfile
= arg
66 def _set_debuglevel(self
, option
, opt_str
, arg
, parser
):
67 self
._lp
.set('debug level', arg
)
68 parser
.values
.debuglevel
= arg
70 def _set_realm(self
, option
, opt_str
, arg
, parser
):
71 self
._lp
.set('realm', arg
)
74 def _set_option(self
, option
, opt_str
, arg
, parser
):
75 if arg
.find('=') == -1:
76 raise optparse
.OptionValueError(
77 "--option option takes a 'a=b' argument")
80 self
._lp
.set(a
[0], a
[1])
81 except Exception as e
:
82 raise optparse
.OptionValueError(
83 "invalid --option option value %r: %s" % (arg
, e
))
85 def get_loadparm(self
):
86 """Return loadparm object with data specified on the command line."""
87 if self
._configfile
is not None:
88 self
._lp
.load(self
._configfile
)
89 elif os
.getenv("SMB_CONF_PATH") is not None:
90 self
._lp
.load(os
.getenv("SMB_CONF_PATH"))
92 self
._lp
.load_default()
96 class VersionOptions(optparse
.OptionGroup
):
97 """Command line option for printing Samba version."""
98 def __init__(self
, parser
):
99 optparse
.OptionGroup
.__init
__(self
, parser
, "Version Options")
100 self
.add_option("-V", "--version", action
="callback",
101 callback
=self
._display
_version
,
102 help="Display version number")
104 def _display_version(self
, option
, opt_str
, arg
, parser
):
110 def parse_kerberos_arg(arg
, opt_str
):
111 if arg
.lower() in ["yes", 'true', '1']:
112 return MUST_USE_KERBEROS
113 elif arg
.lower() in ["no", 'false', '0']:
114 return DONT_USE_KERBEROS
115 elif arg
.lower() in ["auto"]:
116 return AUTO_USE_KERBEROS
118 raise optparse
.OptionValueError("invalid %s option value: %s" %
122 class CredentialsOptions(optparse
.OptionGroup
):
123 """Command line options for specifying credentials."""
125 def __init__(self
, parser
, special_name
=None):
126 self
.special_name
= special_name
127 if special_name
is not None:
128 self
.section
= "Credentials Options (%s)" % special_name
130 self
.section
= "Credentials Options"
132 self
.ask_for_password
= True
133 self
.ipaddress
= None
134 self
.machine_pass
= False
135 optparse
.OptionGroup
.__init
__(self
, parser
, self
.section
)
136 self
._add
_option
("--simple-bind-dn", metavar
="DN", action
="callback",
137 callback
=self
._set
_simple
_bind
_dn
, type=str,
138 help="DN to use for a simple bind")
139 self
._add
_option
("--password", metavar
="PASSWORD", action
="callback",
140 help="Password", type=str, callback
=self
._set
_password
)
141 self
._add
_option
("-U", "--username", metavar
="USERNAME",
142 action
="callback", type=str,
143 help="Username", callback
=self
._parse
_username
)
144 self
._add
_option
("-W", "--workgroup", metavar
="WORKGROUP",
145 action
="callback", type=str,
146 help="Workgroup", callback
=self
._parse
_workgroup
)
147 self
._add
_option
("-N", "--no-pass", action
="callback",
148 help="Don't ask for a password",
149 callback
=self
._set
_no
_password
)
150 self
._add
_option
("-k", "--kerberos", metavar
="KERBEROS",
151 action
="callback", type=str,
152 help="Use Kerberos", callback
=self
._set
_kerberos
)
153 self
._add
_option
("", "--ipaddress", metavar
="IPADDRESS",
154 action
="callback", type=str,
155 help="IP address of server",
156 callback
=self
._set
_ipaddress
)
157 self
._add
_option
("-P", "--machine-pass",
159 help="Use stored machine account password",
160 callback
=self
._set
_machine
_pass
)
161 self
._add
_option
("--krb5-ccache", metavar
="KRB5CCNAME",
162 action
="callback", type=str,
163 help="Kerberos Credentials cache",
164 callback
=self
._set
_krb
5_ccache
)
165 self
.creds
= Credentials()
167 def _add_option(self
, *args1
, **kwargs
):
168 if self
.special_name
is None:
169 return self
.add_option(*args1
, **kwargs
)
173 if not a
.startswith("--"):
175 args2
+= (a
.replace("--", "--%s-" % self
.special_name
),)
176 self
.add_option(*args2
, **kwargs
)
178 def _parse_username(self
, option
, opt_str
, arg
, parser
):
179 self
.creds
.parse_string(arg
)
180 self
.machine_pass
= False
182 def _parse_workgroup(self
, option
, opt_str
, arg
, parser
):
183 self
.creds
.set_domain(arg
)
185 def _set_password(self
, option
, opt_str
, arg
, parser
):
186 self
.creds
.set_password(arg
)
187 self
.ask_for_password
= False
188 self
.machine_pass
= False
190 def _set_no_password(self
, option
, opt_str
, arg
, parser
):
191 self
.ask_for_password
= False
193 def _set_machine_pass(self
, option
, opt_str
, arg
, parser
):
194 self
.machine_pass
= True
196 def _set_ipaddress(self
, option
, opt_str
, arg
, parser
):
199 def _set_kerberos(self
, option
, opt_str
, arg
, parser
):
200 self
.creds
.set_kerberos_state(parse_kerberos_arg(arg
, opt_str
))
202 def _set_simple_bind_dn(self
, option
, opt_str
, arg
, parser
):
203 self
.creds
.set_bind_dn(arg
)
205 def _set_krb5_ccache(self
, option
, opt_str
, arg
, parser
):
206 self
.creds
.set_named_ccache(arg
)
208 def get_credentials(self
, lp
, fallback_machine
=False):
209 """Obtain the credentials set on the command-line.
211 :param lp: Loadparm object to use.
212 :return: Credentials object
215 if self
.machine_pass
:
216 self
.creds
.set_machine_account(lp
)
217 elif self
.ask_for_password
:
218 self
.creds
.set_cmdline_callbacks()
220 # possibly fallback to using the machine account, if we have
221 # access to the secrets db
222 if fallback_machine
and not self
.creds
.authentication_requested():
224 self
.creds
.set_machine_account(lp
)
231 class CredentialsOptionsDouble(CredentialsOptions
):
232 """Command line options for specifying credentials of two servers."""
234 def __init__(self
, parser
):
235 CredentialsOptions
.__init
__(self
, parser
)
237 self
.add_option("--simple-bind-dn2", metavar
="DN2", action
="callback",
238 callback
=self
._set
_simple
_bind
_dn
2, type=str,
239 help="DN to use for a simple bind")
240 self
.add_option("--password2", metavar
="PASSWORD2", action
="callback",
241 help="Password", type=str,
242 callback
=self
._set
_password
2)
243 self
.add_option("--username2", metavar
="USERNAME2",
244 action
="callback", type=str,
245 help="Username for second server",
246 callback
=self
._parse
_username
2)
247 self
.add_option("--workgroup2", metavar
="WORKGROUP2",
248 action
="callback", type=str,
249 help="Workgroup for second server",
250 callback
=self
._parse
_workgroup
2)
251 self
.add_option("--no-pass2", action
="store_true",
252 help="Don't ask for a password for the second server")
253 self
.add_option("--kerberos2", metavar
="KERBEROS2",
254 action
="callback", type=str,
255 help="Use Kerberos", callback
=self
._set
_kerberos
2)
256 self
.creds2
= Credentials()
258 def _parse_username2(self
, option
, opt_str
, arg
, parser
):
259 self
.creds2
.parse_string(arg
)
261 def _parse_workgroup2(self
, option
, opt_str
, arg
, parser
):
262 self
.creds2
.set_domain(arg
)
264 def _set_password2(self
, option
, opt_str
, arg
, parser
):
265 self
.creds2
.set_password(arg
)
266 self
.no_pass2
= False
268 def _set_kerberos2(self
, option
, opt_str
, arg
, parser
):
269 self
.creds2
.set_kerberos_state(parse_kerberos_arg(arg
, opt_str
))
271 def _set_simple_bind_dn2(self
, option
, opt_str
, arg
, parser
):
272 self
.creds2
.set_bind_dn(arg
)
274 def get_credentials2(self
, lp
, guess
=True):
275 """Obtain the credentials set on the command-line.
277 :param lp: Loadparm object to use.
278 :param guess: Try guess Credentials from environment
279 :return: Credentials object
282 self
.creds2
.guess(lp
)
283 elif not self
.creds2
.get_username():
284 self
.creds2
.set_anonymous()
287 self
.creds2
.set_cmdline_callbacks()
290 # Custom option type to allow the input of sizes using byte, kb, mb ...
291 # units, e.g. 2Gb, 4KiB ...
292 # e.g. Option("--size", type="bytes", metavar="SIZE")
294 def check_bytes(option
, opt
, value
):
300 "GB" : 1024 * 1024 * 1024}
302 # strip out any spaces
303 v
= value
.replace(" ", "")
305 # extract the numeric prefix
307 while v
and v
[0:1].isdigit() or v
[0:1] == '.':
314 msg
= ("{0} option requires a numeric value, "
315 "with an optional unit suffix").format(opt
)
316 raise optparse
.OptionValueError(msg
)
319 # strip out the 'i' and convert to upper case so
320 # kib Kib kb KB are all equivalent
321 suffix
= v
.upper().replace("I", "")
323 return m
* multipliers
[suffix
]
324 except KeyError as k
:
325 msg
= ("{0} invalid suffix '{1}', "
326 "should be B, Kb, Mb or Gb").format(opt
, v
)
327 raise optparse
.OptionValueError(msg
)
329 class SambaOption(optparse
.Option
):
330 TYPES
= optparse
.Option
.TYPES
+ ("bytes",)
331 TYPE_CHECKER
= copy(optparse
.Option
.TYPE_CHECKER
)
332 TYPE_CHECKER
["bytes"] = check_bytes