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 Giampaolo Lauria 2011 <lauria2@yahoo.com>
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):
36 def _get_description(self):
37 return self.__doc__.splitlines()[0].rstrip("\n")
40 name = self.__class__.__name__
41 if name.startswith("cmd_"):
45 name = property(_get_name)
47 def usage(self, *args):
48 parser, _ = self._create_parser()
51 description = property(_get_description)
53 def _get_synopsis(self):
56 ret += " " + " ".join([x.upper() for x in self.takes_args])
59 def show_command_error(self, e):
60 '''display a command error'''
61 if isinstance(e, CommandError):
62 (etype, evalue, etraceback) = e.exception_info
63 inner_exception = e.inner_exception
65 force_traceback = False
67 (etype, evalue, etraceback) = sys.exc_info()
69 message = "uncaught exception"
70 force_traceback = True
72 if isinstance(inner_exception, LdbError):
73 (ldb_ecode, ldb_emsg) = inner_exception
74 print >>sys.stderr, "ERROR(ldb): %s - %s" % (message, ldb_emsg)
75 elif isinstance(inner_exception, AssertionError):
76 print >>sys.stderr, "ERROR(assert): %s" % message
77 force_traceback = True
78 elif isinstance(inner_exception, RuntimeError):
79 print >>sys.stderr, "ERROR(runtime): %s - %s" % (message, evalue)
80 elif type(inner_exception) is Exception:
81 print >>sys.stderr, "ERROR(exception): %s - %s" % (message, evalue)
82 force_traceback = True
83 elif inner_exception is None:
84 print >>sys.stderr, "ERROR: %s" % (message)
86 print >>sys.stderr, "ERROR(%s): %s - %s" % (str(etype), message, evalue)
87 force_traceback = True
89 if force_traceback or samba.get_debug_level() >= 3:
90 traceback.print_tb(etraceback)
92 synopsis = property(_get_synopsis)
98 takes_optiongroups = {
99 "sambaopts": options.SambaOptions,
100 "credopts": options.CredentialsOptions,
101 "versionopts": options.VersionOptions,
104 def _create_parser(self):
105 parser = optparse.OptionParser(self.synopsis)
106 parser.add_options(self.takes_options)
108 for name, optiongroup in self.takes_optiongroups.iteritems():
109 optiongroups[name] = optiongroup(parser)
110 parser.add_option_group(optiongroups[name])
111 return parser, optiongroups
113 def message(self, text):
116 def _run(self, *argv):
117 parser, optiongroups = self._create_parser()
118 opts, args = parser.parse_args(list(argv))
119 # Filter out options from option groups
121 kwargs = dict(opts.__dict__)
122 for option_group in parser.option_groups:
123 for option in option_group.option_list:
124 if option.dest is not None:
125 del kwargs[option.dest]
126 kwargs.update(optiongroups)
129 for i, arg in enumerate(self.takes_args):
130 if arg[-1] not in ("?", "*"):
135 if len(args) < min_args or (max_args != -1 and len(args) > max_args):
139 return self.run(*args, **kwargs)
141 self.show_command_error(e)
145 """Run the command. This should be overriden by all subclasses."""
146 raise NotImplementedError(self.run)
150 class SuperCommand(Command):
151 """A command with subcommands."""
155 def _run(self, myname, subcommand=None, *args):
156 if subcommand in self.subcommands:
157 return self.subcommands[subcommand]._run(subcommand, *args)
158 print "Available subcommands:"
159 for cmd in self.subcommands:
160 print "\t%-20s - %s" % (cmd, self.subcommands[cmd].description)
161 if subcommand in [None, 'help', '-h', '--help' ]:
163 self.show_command_error("No such subcommand '%s'" % (subcommand))
165 def show_command_error(self, msg):
166 '''display a command error'''
168 print >>sys.stderr, "ERROR: %s" % (msg)
171 def usage(self, myname, subcommand=None, *args):
172 if subcommand is None or not subcommand in self.subcommands:
173 print "Usage: %s (%s) [options]" % (myname,
174 " | ".join(self.subcommands.keys()))
176 return self.subcommands[subcommand].usage(*args)
180 class CommandError(Exception):
181 '''an exception class for netcmd errors'''
182 def __init__(self, message, inner_exception=None):
183 self.message = message
184 self.inner_exception = inner_exception
185 self.exception_info = sys.exc_info()
190 from samba.netcmd.newuser import cmd_newuser
191 commands["newuser"] = cmd_newuser()
192 from samba.netcmd.netacl import cmd_acl
193 commands["acl"] = cmd_acl()
194 from samba.netcmd.fsmo import cmd_fsmo
195 commands["fsmo"] = cmd_fsmo()
196 from samba.netcmd.time import cmd_time
197 commands["time"] = cmd_time()
198 from samba.netcmd.user import cmd_user
199 commands["user"] = cmd_user()
200 from samba.netcmd.vampire import cmd_vampire
201 commands["vampire"] = cmd_vampire()
202 from samba.netcmd.spn import cmd_spn
203 commands["spn"] = cmd_spn()
204 from samba.netcmd.group import cmd_group
205 commands["group"] = cmd_group()
206 from samba.netcmd.rodc import cmd_rodc
207 commands["rodc"] = cmd_rodc()
208 from samba.netcmd.drs import cmd_drs
209 commands["drs"] = cmd_drs()
210 from samba.netcmd.gpo import cmd_gpo
211 commands["gpo2"] = cmd_gpo()
212 from samba.netcmd.ldapcmp import cmd_ldapcmp
213 commands["ldapcmp"] = cmd_ldapcmp()
214 from samba.netcmd.testparm import cmd_testparm
215 commands["testparm"] = cmd_testparm()
216 from samba.netcmd.dbcheck import cmd_dbcheck
217 commands["dbcheck"] = cmd_dbcheck()
218 from samba.netcmd.delegation import cmd_delegation
219 commands["delegation"] = cmd_delegation()
220 from samba.netcmd.domain import cmd_domain
221 commands["domain"] = cmd_domain()