s4-s3-upgrade Improve samba-tool domain samba3upgrade behaviour
[samba.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     DONT_USE_KERBEROS,
29     MUST_USE_KERBEROS,
30     )
31 from samba.hostconfig import Hostconfig
32 import sys
33
34
35 class SambaOptions(optparse.OptionGroup):
36     """General Samba-related command line options."""
37
38     def __init__(self, parser):
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=int, 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         self._lp.set('debug level', str(arg))
67
68     def _set_realm(self, option, opt_str, arg, parser):
69         self._lp.set('realm', arg)
70         self.realm = arg
71
72     def _set_option(self, option, opt_str, arg, parser):
73         if arg.find('=') == -1:
74             print("--option takes a 'a=b' argument")
75             sys.exit(1)
76         a = arg.split('=')
77         self._lp.set(a[0], a[1])
78
79     def get_loadparm(self):
80         """Return loadparm object with data specified on the command line."""
81         if self._configfile is not None:
82             self._lp.load(self._configfile)
83         elif os.getenv("SMB_CONF_PATH") is not None:
84             self._lp.load(os.getenv("SMB_CONF_PATH"))
85         else:
86             self._lp.load_default()
87         return self._lp
88
89     def get_hostconfig(self):
90         return Hostconfig(self.get_loadparm())
91
92
93 class VersionOptions(optparse.OptionGroup):
94     """Command line option for printing Samba version."""
95     def __init__(self, parser):
96         optparse.OptionGroup.__init__(self, parser, "Version Options")
97         self.add_option("--version", action="callback",
98                 callback=self._display_version,
99                 help="Display version number")
100
101     def _display_version(self, option, opt_str, arg, parser):
102         import samba
103         print samba.version
104         sys.exit(0)
105
106
107 class CredentialsOptions(optparse.OptionGroup):
108     """Command line options for specifying credentials."""
109     def __init__(self, parser):
110         self.no_pass = True
111         self.ipaddress = None
112         optparse.OptionGroup.__init__(self, parser, "Credentials Options")
113         self.add_option("--simple-bind-dn", metavar="DN", action="callback",
114                         callback=self._set_simple_bind_dn, type=str,
115                         help="DN to use for a simple bind")
116         self.add_option("--password", metavar="PASSWORD", action="callback",
117                         help="Password", type=str, callback=self._set_password)
118         self.add_option("-U", "--username", metavar="USERNAME",
119                         action="callback", type=str,
120                         help="Username", callback=self._parse_username)
121         self.add_option("-W", "--workgroup", metavar="WORKGROUP",
122                         action="callback", type=str,
123                         help="Workgroup", callback=self._parse_workgroup)
124         self.add_option("-N", "--no-pass", action="store_true",
125                         help="Don't ask for a password")
126         self.add_option("-k", "--kerberos", metavar="KERBEROS",
127                         action="callback", type=str,
128                         help="Use Kerberos", callback=self._set_kerberos)
129         self.add_option("", "--ipaddress", metavar="IPADDRESS",
130                         action="callback", type=str,
131                         help="IP address of server",
132                         callback=self._set_ipaddress)
133         self.creds = Credentials()
134
135     def _parse_username(self, option, opt_str, arg, parser):
136         self.creds.parse_string(arg)
137
138     def _parse_workgroup(self, option, opt_str, arg, parser):
139         self.creds.set_domain(arg)
140
141     def _set_password(self, option, opt_str, arg, parser):
142         self.creds.set_password(arg)
143         self.no_pass = False
144
145     def _set_ipaddress(self, option, opt_str, arg, parser):
146         self.ipaddress = arg
147
148     def _set_kerberos(self, option, opt_str, arg, parser):
149         if arg.lower() in ["yes", 'true', '1']:
150             self.creds.set_kerberos_state(MUST_USE_KERBEROS)
151         elif arg.lower() in ["no", 'false', '0']:
152             self.creds.set_kerberos_state(DONT_USE_KERBEROS)
153         else:
154             raise optparse.BadOptionErr("invalid kerberos option: %s" % arg)
155
156     def _set_simple_bind_dn(self, option, opt_str, arg, parser):
157         self.creds.set_bind_dn(arg)
158
159     def get_credentials(self, lp, fallback_machine=False):
160         """Obtain the credentials set on the command-line.
161
162         :param lp: Loadparm object to use.
163         :return: Credentials object
164         """
165         self.creds.guess(lp)
166         if self.no_pass:
167             self.creds.set_cmdline_callbacks()
168
169         # possibly fallback to using the machine account, if we have
170         # access to the secrets db
171         if fallback_machine and not self.creds.authentication_requested():
172             try:
173                 self.creds.set_machine_account(lp)
174             except Exception:
175                 pass
176
177         return self.creds
178
179
180 class CredentialsOptionsDouble(CredentialsOptions):
181     """Command line options for specifying credentials of two servers."""
182     def __init__(self, parser):
183         CredentialsOptions.__init__(self, parser)
184         self.no_pass2 = True
185         self.add_option("--simple-bind-dn2", metavar="DN2", action="callback",
186                         callback=self._set_simple_bind_dn2, type=str,
187                         help="DN to use for a simple bind")
188         self.add_option("--password2", metavar="PASSWORD2", action="callback",
189                         help="Password", type=str,
190                         callback=self._set_password2)
191         self.add_option("--username2", metavar="USERNAME2",
192                         action="callback", type=str,
193                         help="Username for second server",
194                         callback=self._parse_username2)
195         self.add_option("--workgroup2", metavar="WORKGROUP2",
196                         action="callback", type=str,
197                         help="Workgroup for second server",
198                         callback=self._parse_workgroup2)
199         self.add_option("--no-pass2", action="store_true",
200                         help="Don't ask for a password for the second server")
201         self.add_option("--kerberos2", metavar="KERBEROS2",
202                         action="callback", type=str,
203                         help="Use Kerberos", callback=self._set_kerberos2)
204         self.creds2 = Credentials()
205
206     def _parse_username2(self, option, opt_str, arg, parser):
207         self.creds2.parse_string(arg)
208
209     def _parse_workgroup2(self, option, opt_str, arg, parser):
210         self.creds2.set_domain(arg)
211
212     def _set_password2(self, option, opt_str, arg, parser):
213         self.creds2.set_password(arg)
214         self.no_pass2 = False
215
216     def _set_kerberos2(self, option, opt_str, arg, parser):
217         if bool(arg) or arg.lower() == "yes":
218             self.creds2.set_kerberos_state(MUST_USE_KERBEROS)
219         else:
220             self.creds2.set_kerberos_state(DONT_USE_KERBEROS)
221
222     def _set_simple_bind_dn2(self, option, opt_str, arg, parser):
223         self.creds2.set_bind_dn(arg)
224
225     def get_credentials2(self, lp, guess=True):
226         """Obtain the credentials set on the command-line.
227
228         :param lp: Loadparm object to use.
229         :param guess: Try guess Credentials from environment
230         :return: Credentials object
231         """
232         if guess:
233             self.creds2.guess(lp)
234         elif not self.creds2.get_username():
235                 self.creds2.set_anonymous()
236
237         if self.no_pass2:
238             self.creds2.set_cmdline_callbacks()
239         return self.creds2