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
42 synopsis
= "Please provide synopsis for this command."
43 # long_description is a string describing the command in details
47 takes_optiongroups
= {
48 "sambaopts": options
.SambaOptions
,
49 "credopts": options
.CredentialsOptions
,
50 "versionopts": options
.VersionOptions
,
55 def usage(self
, *args
):
56 parser
, _
= self
._create
_parser
()
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 self
.errf
.write("ERROR(ldb): %s - %s\n" % (message
, ldb_emsg
))
75 elif isinstance(inner_exception
, AssertionError):
76 self
.errf
.write("ERROR(assert): %s\n" % message
)
77 force_traceback
= True
78 elif isinstance(inner_exception
, RuntimeError):
79 self
.errf
.write("ERROR(runtime): %s - %s\n" % (message
, evalue
))
80 elif type(inner_exception
) is Exception:
81 self
.errf
.write("ERROR(exception): %s - %s\n" % (message
, evalue
))
82 force_traceback
= True
83 elif inner_exception
is None:
84 self
.errf
.write("ERROR: %s\n" % (message
))
86 self
.errf
.write("ERROR(%s): %s - %s\n" % (str(etype
), message
, evalue
))
87 force_traceback
= True
89 if force_traceback
or samba
.get_debug_level() >= 3:
90 traceback
.print_tb(etraceback
)
92 def _create_parser(self
):
93 parser
= optparse
.OptionParser(usage
=self
.synopsis
,
94 description
=self
.long_description
)
95 parser
.add_options(self
.takes_options
)
97 for name
, optiongroup
in self
.takes_optiongroups
.iteritems():
98 optiongroups
[name
] = optiongroup(parser
)
99 parser
.add_option_group(optiongroups
[name
])
100 return parser
, optiongroups
102 def message(self
, text
):
103 self
.outf
.write(text
+"\n")
105 def _run(self
, *argv
):
106 parser
, optiongroups
= self
._create
_parser
()
107 opts
, args
= parser
.parse_args(list(argv
))
108 # Filter out options from option groups
110 kwargs
= dict(opts
.__dict
__)
111 for option_group
in parser
.option_groups
:
112 for option
in option_group
.option_list
:
113 if option
.dest
is not None:
114 del kwargs
[option
.dest
]
115 kwargs
.update(optiongroups
)
117 # Check for a min a max number of allowed arguments, whenever possible
118 # The suffix "?" means zero or one occurence
119 # The suffix "+" means at least one occurence
122 undetermined_max_args
= False
123 for i
, arg
in enumerate(self
.takes_args
):
127 undetermined_max_args
= True
130 if (len(args
) < min_args
) or (undetermined_max_args
== False and len(args
) > max_args
):
135 return self
.run(*args
, **kwargs
)
137 self
.show_command_error(e
)
141 """Run the command. This should be overriden by all subclasses."""
142 raise NotImplementedError(self
.run
)
144 def get_logger(self
, name
="netcmd"):
145 """Get a logger object."""
147 logger
= logging
.getLogger(name
)
148 logger
.addHandler(logging
.StreamHandler(self
.outf
))
152 class SuperCommand(Command
):
153 """A samba-tool command with subcommands."""
157 def _run(self
, myname
, subcommand
=None, *args
):
158 if subcommand
in self
.subcommands
:
159 return self
.subcommands
[subcommand
]._run
(subcommand
, *args
)
161 if (myname
== "samba-tool"):
162 usage
= "samba-tool <subcommand>"
164 usage
= "samba-tool %s <subcommand>" % myname
165 self
.outf
.write("Usage: %s [options]\n" % usage
)
166 self
.outf
.write("Available subcommands:\n")
167 subcmds
= self
.subcommands
.keys()
169 max_length
= max([len(c
) for c
in subcmds
])
171 self
.outf
.write(" %*s - %s\n" % (-max_length
, cmd
, self
.subcommands
[cmd
].description
))
172 if subcommand
in [None]:
173 raise CommandError("You must specify a subcommand")
174 if subcommand
in ['help', '-h', '--help']:
175 self
.outf
.write("For more help on a specific subcommand, please type: %s (-h|--help)\n" % usage
)
177 raise CommandError("No such subcommand '%s'" % subcommand
)
181 class CommandError(Exception):
182 '''an exception class for samba-tool cmd errors'''
183 def __init__(self
, message
, inner_exception
=None):
184 self
.message
= message
185 self
.inner_exception
= inner_exception
186 self
.exception_info
= sys
.exc_info()