e7ec1f78369c3f8247fd8654af88b418ee28d04d
[idra/samba.git] / source4 / scripting / python / samba / netcmd / __init__.py
1 #!/usr/bin/env python
2
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
7 #
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.
12 #
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.
17 #
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/>.
20 #
21
22 import optparse, samba
23 from samba import getopt as options
24 from ldb import LdbError
25 import sys, traceback
26
27
28 class Option(optparse.Option):
29     pass
30
31
32
33 class Command(object):
34     """A %prog command."""
35
36     def _get_description(self):
37         return self.__doc__.splitlines()[0].rstrip("\n")
38
39     def _get_name(self):
40         name = self.__class__.__name__
41         if name.startswith("cmd_"):
42             return name[4:]
43         return name
44
45     name = property(_get_name)
46
47     def usage(self, *args):
48         parser, _ = self._create_parser()
49         parser.print_usage()
50
51     description = property(_get_description)
52
53     def _get_synopsis(self):
54         ret = self.name
55         if self.takes_args:
56             ret += " " + " ".join([x.upper() for x in self.takes_args])
57         return ret
58
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
64             message = e.message
65             force_traceback = False
66         else:
67             (etype, evalue, etraceback) = sys.exc_info()
68             inner_exception = e
69             message = "uncaught exception"
70             force_traceback = True
71
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)
85         else:
86             print >>sys.stderr, "ERROR(%s): %s - %s" % (str(etype), message, evalue)
87             force_traceback = True
88
89         if force_traceback or samba.get_debug_level() >= 3:
90             traceback.print_tb(etraceback)
91
92     synopsis = property(_get_synopsis)
93
94     outf = sys.stdout
95
96     takes_args = []
97     takes_options = []
98     takes_optiongroups = {
99         "sambaopts": options.SambaOptions,
100         "credopts": options.CredentialsOptions,
101         "versionopts": options.VersionOptions,
102         }
103
104     def _create_parser(self):
105         parser = optparse.OptionParser(self.synopsis)
106         parser.add_options(self.takes_options)
107         optiongroups = {}
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
112
113     def message(self, text):
114         print text
115
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
120         args = args[1:]
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)
127
128         # Check for a min a max number of allowed arguments, whenever possible
129         # The suffix "?" means zero or one occurence
130         # The suffix "+" means at least one occurence
131         min_args = 0
132         max_args = 0
133         undetermined_max_args = False
134         for i, arg in enumerate(self.takes_args):
135             if arg[-1] != "?":
136                min_args += 1
137             if arg[-1] == "+":
138                undetermined_max_args = True
139             else:
140                max_args += 1
141         if (len(args) < min_args) or (undetermined_max_args == False and len(args) > max_args):
142             parser.print_usage()
143             return -1
144
145         try:
146             return self.run(*args, **kwargs)
147         except Exception, e:
148             self.show_command_error(e)
149             return -1
150
151     def run(self):
152         """Run the command. This should be overriden by all subclasses."""
153         raise NotImplementedError(self.run)
154
155
156
157 class SuperCommand(Command):
158     """A %prog command with subcommands."""
159
160     subcommands = {}
161
162     def _run(self, myname, subcommand=None, *args):
163         if subcommand in self.subcommands:
164             return self.subcommands[subcommand]._run(subcommand, *args)
165         print "Available subcommands:"
166         for cmd in self.subcommands:
167             print "\t%-20s - %s" % (cmd, self.subcommands[cmd].description)
168         if subcommand in [None]:
169             self.show_command_error("You must specify a subcommand")
170             return -1
171         if subcommand in ['-h', '--help']:
172             print "For more help on a specific subcommand, please type: samba-tool %s <subcommand> (-h|--help)" % myname
173             return 0
174         self.show_command_error("No such subcommand '%s'" % (subcommand))
175
176     def show_command_error(self, msg):
177         '''display a command error'''
178
179         print >>sys.stderr, "ERROR: %s" % (msg)
180         return -1
181
182     def usage(self, myname, subcommand=None, *args):
183         if subcommand is None or not subcommand in self.subcommands:
184             print "Usage: %s (%s) [options]" % (myname,
185                 " | ".join(self.subcommands.keys()))
186         else:
187             return self.subcommands[subcommand].usage(*args)
188
189
190
191 class CommandError(Exception):
192     '''an exception class for %prog cmd errors'''
193     def __init__(self, message, inner_exception=None):
194         self.message = message
195         self.inner_exception = inner_exception
196         self.exception_info = sys.exc_info()
197
198
199
200 commands = {}
201 from samba.netcmd.newuser import cmd_newuser
202 commands["newuser"] = cmd_newuser()
203 from samba.netcmd.netacl import cmd_acl
204 commands["acl"] = cmd_acl()
205 from samba.netcmd.fsmo import cmd_fsmo
206 commands["fsmo"] = cmd_fsmo()
207 from samba.netcmd.time import cmd_time
208 commands["time"] = cmd_time()
209 from samba.netcmd.user import cmd_user
210 commands["user"] = cmd_user()
211 from samba.netcmd.vampire import cmd_vampire
212 commands["vampire"] = cmd_vampire()
213 from samba.netcmd.spn import cmd_spn
214 commands["spn"] = cmd_spn()
215 from samba.netcmd.group import cmd_group
216 commands["group"] = cmd_group()
217 from samba.netcmd.rodc import cmd_rodc
218 commands["rodc"] = cmd_rodc()
219 from samba.netcmd.drs import cmd_drs
220 commands["drs"] = cmd_drs()
221 from samba.netcmd.gpo import cmd_gpo
222 commands["gpo2"] = cmd_gpo()
223 from samba.netcmd.ldapcmp import cmd_ldapcmp
224 commands["ldapcmp"] = cmd_ldapcmp()
225 from samba.netcmd.testparm import cmd_testparm
226 commands["testparm"] =  cmd_testparm()
227 from samba.netcmd.dbcheck import cmd_dbcheck
228 commands["dbcheck"] =  cmd_dbcheck()
229 from samba.netcmd.delegation import cmd_delegation
230 commands["delegation"] = cmd_delegation()
231 from samba.netcmd.domain import cmd_domain
232 commands["domain"] = cmd_domain()