3 # Unix SMB/CIFS implementation.
4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2009
5 # Copyright (C) Theresa Halloran <theresahalloran@gmail.com> 2011
6 # Copyright (C) Giampaolo Lauria <lauria2@yahoo.com> 2011
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.
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.
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/>.
22 import optparse, samba
23 from samba import getopt as options
24 from ldb import LdbError
28 class Option(optparse.Option):
33 class Command(object):
34 """A samba-tool command."""
36 def _get_description(self):
37 return self.__doc__.splitlines()[0].rstrip("\n")
39 description = property(_get_description)
41 # synopsis must be defined in all subclasses in order to provide the command usage
45 takes_optiongroups = {
46 "sambaopts": options.SambaOptions,
47 "credopts": options.CredentialsOptions,
48 "versionopts": options.VersionOptions,
52 def usage(self, *args):
53 parser, _ = self._create_parser()
56 def show_command_error(self, e):
57 '''display a command error'''
58 if isinstance(e, CommandError):
59 (etype, evalue, etraceback) = e.exception_info
60 inner_exception = e.inner_exception
62 force_traceback = False
64 (etype, evalue, etraceback) = sys.exc_info()
66 message = "uncaught exception"
67 force_traceback = True
69 if isinstance(inner_exception, LdbError):
70 (ldb_ecode, ldb_emsg) = inner_exception
71 print >>sys.stderr, "ERROR(ldb): %s - %s" % (message, ldb_emsg)
72 elif isinstance(inner_exception, AssertionError):
73 print >>sys.stderr, "ERROR(assert): %s" % message
74 force_traceback = True
75 elif isinstance(inner_exception, RuntimeError):
76 print >>sys.stderr, "ERROR(runtime): %s - %s" % (message, evalue)
77 elif type(inner_exception) is Exception:
78 print >>sys.stderr, "ERROR(exception): %s - %s" % (message, evalue)
79 force_traceback = True
80 elif inner_exception is None:
81 print >>sys.stderr, "ERROR: %s" % (message)
83 print >>sys.stderr, "ERROR(%s): %s - %s" % (str(etype), message, evalue)
84 force_traceback = True
86 if force_traceback or samba.get_debug_level() >= 3:
87 traceback.print_tb(etraceback)
90 def _create_parser(self):
91 parser = optparse.OptionParser(self.synopsis)
92 parser.add_options(self.takes_options)
94 for name, optiongroup in self.takes_optiongroups.iteritems():
95 optiongroups[name] = optiongroup(parser)
96 parser.add_option_group(optiongroups[name])
97 return parser, optiongroups
99 def message(self, text):
102 def _run(self, *argv):
103 parser, optiongroups = self._create_parser()
104 opts, args = parser.parse_args(list(argv))
105 # Filter out options from option groups
107 kwargs = dict(opts.__dict__)
108 for option_group in parser.option_groups:
109 for option in option_group.option_list:
110 if option.dest is not None:
111 del kwargs[option.dest]
112 kwargs.update(optiongroups)
114 # Check for a min a max number of allowed arguments, whenever possible
115 # The suffix "?" means zero or one occurence
116 # The suffix "+" means at least one occurence
119 undetermined_max_args = False
120 for i, arg in enumerate(self.takes_args):
124 undetermined_max_args = True
127 if (len(args) < min_args) or (undetermined_max_args == False and len(args) > max_args):
132 return self.run(*args, **kwargs)
134 self.show_command_error(e)
138 """Run the command. This should be overriden by all subclasses."""
139 raise NotImplementedError(self.run)
143 class SuperCommand(Command):
144 """A samba-tool command with subcommands."""
148 def _run(self, myname, subcommand=None, *args):
149 if subcommand in self.subcommands:
150 return self.subcommands[subcommand]._run(subcommand, *args)
151 print "Usage: samba-tool %s <subcommand> [options]" % myname
152 print "Available subcommands:"
153 subcmds = self.subcommands.keys()
156 print " %-20s - %s" % (cmd, self.subcommands[cmd].description)
157 if subcommand in [None]:
158 raise CommandError("You must specify a subcommand")
159 if subcommand in ['help', '-h', '--help']:
160 print "For more help on a specific subcommand, please type: samba-tool %s <subcommand> (-h|--help)" % myname
162 raise CommandError("No such subcommand '%s'" % subcommand)
164 def usage(self, myname, subcommand=None, *args):
165 if subcommand is None or not subcommand in self.subcommands:
166 print "Usage: samba-tool %s (%s) [options]" % (myname,
167 " | ".join(self.subcommands.keys()))
169 return self.subcommands[subcommand].usage(*args)
173 class CommandError(Exception):
174 '''an exception class for samba-tool cmd errors'''
175 def __init__(self, message, inner_exception=None):
176 self.message = message
177 self.inner_exception = inner_exception
178 self.exception_info = sys.exc_info()
183 from samba.netcmd.netacl import cmd_acl
184 commands["acl"] = cmd_acl()
185 from samba.netcmd.fsmo import cmd_fsmo
186 commands["fsmo"] = cmd_fsmo()
187 from samba.netcmd.time import cmd_time
188 commands["time"] = cmd_time()
189 from samba.netcmd.user import cmd_user
190 commands["user"] = cmd_user()
191 from samba.netcmd.vampire import cmd_vampire
192 commands["vampire"] = cmd_vampire()
193 from samba.netcmd.spn import cmd_spn
194 commands["spn"] = cmd_spn()
195 from samba.netcmd.group import cmd_group
196 commands["group"] = cmd_group()
197 from samba.netcmd.rodc import cmd_rodc
198 commands["rodc"] = cmd_rodc()
199 from samba.netcmd.drs import cmd_drs
200 commands["drs"] = cmd_drs()
201 from samba.netcmd.gpo import cmd_gpo
202 commands["gpo"] = cmd_gpo()
203 from samba.netcmd.ldapcmp import cmd_ldapcmp
204 commands["ldapcmp"] = cmd_ldapcmp()
205 from samba.netcmd.testparm import cmd_testparm
206 commands["testparm"] = cmd_testparm()
207 from samba.netcmd.dbcheck import cmd_dbcheck
208 commands["dbcheck"] = cmd_dbcheck()
209 from samba.netcmd.delegation import cmd_delegation
210 commands["delegation"] = cmd_delegation()
211 from samba.netcmd.domain import cmd_domain
212 commands["domain"] = cmd_domain()