def __init__(self, cb, connect_callback):
"""
Create a CbLR Command Line class
:param cb: Connection to the Cb Enterprise Response API
:param connect_callback: Callable to get a sensor object from the ``connect`` command
:type cb: CbEnterpriseResponseAPI
:return:
"""
cmd.Cmd.__init__(self)
# global variables
# apply regardless of session state
self.cb = cb
self.connect_callback = connect_callback
lr_session = None
""":type lr_session: LiveResponseSession"""
self.lr_session = lr_session
self.reset()
python类Cmd()的实例源码
def cmdloop(self, intro=None):
while True:
try:
cmd.Cmd.cmdloop(self, intro)
except CliHelpException:
pass
except QuitException:
break
except KeyboardInterrupt:
break
except CliAttachError as e:
print("You must attach to a session")
continue
except CliArgsException as e:
print("Error parsing arguments!\n %s" % e)
continue
except Exception as e:
print("Error: %s" % e)
continue
if self.lr_session:
self.lr_session.close()
def __init__(self, app):
# Initiate the parent class
cmd.Cmd.__init__(self)
# Set up the command line prompt itself
self.prompt = "Tuxemon>> "
self.intro = 'Tuxemon CLI\nType "help", "copyright", "credits" or "license" for more information.'
# Import pretty print so that shit is formatted nicely
import pprint
self.pp = pprint.PrettyPrinter(indent=4)
# Import threading to start the CLI in a separate thread
from threading import Thread
self.app = app
self.cmd_thread = Thread(target=self.cmdloop)
self.cmd_thread.daemon = True
self.cmd_thread.start()
def __init__(self, share, quit, executeShellCommand, smbConnection):
cmd.Cmd.__init__(self)
self.__share = share
self.__output = '\\' + OUTPUT_FILENAME
self.__outputBuffer = ''
self.__shell = 'c:\\windows\\system32\\cmd.exe'
self.__quit = quit
self.__executeShellCommand = executeShellCommand
self.__transferClient = smbConnection
self.__pwd = 'C:\\'
self.__noOutput = False
self.intro = '[!] Launching semi-interactive shell - Careful what you execute\n[!] Press help for extra shell commands'
# We don't wanna deal with timeouts from now on.
if self.__transferClient is not None:
self.__transferClient.setTimeout(100000)
self.do_cd('\\')
else:
self.__noOutput = True
def __init__(self, smbClient,tcpShell=None):
#If the tcpShell parameter is passed (used in ntlmrelayx),
# all input and output is redirected to a tcp socket
# instead of to stdin / stdout
if tcpShell is not None:
cmd.Cmd.__init__(self,stdin=tcpShell,stdout=tcpShell)
sys.stdout = tcpShell
sys.stdin = tcpShell
sys.stderr = tcpShell
self.use_rawinput = False
self.shell = tcpShell
else:
cmd.Cmd.__init__(self)
self.shell = None
self.prompt = '# '
self.smb = smbClient
self.username, self.password, self.domain, self.lmhash, self.nthash, self.aesKey, self.TGT, self.TGS = smbClient.getCredentials()
self.tid = None
self.intro = 'Type help for list of commands'
self.pwd = ''
self.share = None
self.loggedIn = True
self.last_output = None
self.completion = []
def __init__(self, share, win32Process, smbConnection):
cmd.Cmd.__init__(self)
self.__share = share
self.__output = '\\' + OUTPUT_FILENAME
self.__outputBuffer = unicode('')
self.__shell = 'cmd.exe /Q /c '
self.__win32Process = win32Process
self.__transferClient = smbConnection
self.__pwd = unicode('C:\\')
self.__noOutput = False
self.intro = '[!] Launching semi-interactive shell - Careful what you execute\n[!] Press help for extra shell commands'
# We don't wanna deal with timeouts from now on.
if self.__transferClient is not None:
self.__transferClient.setTimeout(100000)
self.do_cd('\\')
else:
self.__noOutput = True
def __init__(self, share, win32Process, smbConnection):
cmd.Cmd.__init__(self)
self.__share = share
self.__output = '\\Windows\\Temp\\' + OUTPUT_FILENAME
self.__outputBuffer = ''
self.__shell = 'cmd.exe /Q /c '
self.__win32Process = win32Process
self.__transferClient = smbConnection
self.__pwd = 'C:\\'
self.__noOutput = False
self.intro = '[!] Launching semi-interactive shell - Careful what you execute\n[!] Press help for extra shell commands'
# We don't wanna deal with timeouts from now on.
if self.__transferClient is not None:
self.__transferClient.setTimeout(10000)
self.do_cd('\\')
else:
self.__noOutput = True
def run_transcript_tests(self, callargs):
"""Runs transcript tests for provided file(s).
This is called when either -t is provided on the command line or the transcript_files argument is provided
during construction of the cmd2.Cmd instance.
:param callargs: List[str] - list of transcript test file names
"""
class TestMyAppCase(Cmd2TestCase):
cmdapp = self
self.__class__.testfiles = callargs
sys.argv = [sys.argv[0]] # the --test argument upsets unittest.main()
testcase = TestMyAppCase()
runner = unittest.TextTestRunner()
runner.run(testcase)
def __init__(self, client, echo=False):
cmd.Cmd.__init__(self)
self.echo = echo
self.MarketClient = client
self.MarketState = client.CurrentState
if self.MarketClient.CreatorID:
self.prompt = self.MarketState.i2n(
self.MarketClient.CreatorID) + '> '
else:
self.prompt = '//UNKNOWN> '
self.IdentityMap = {
'_partid_': self.MarketClient.CreatorID,
'_name_': self.MarketState.i2n(self.MarketClient.CreatorID)
}
def onecmd_exec(self, line):
try:
if self.timing:
start_time = time.time()
result = cmd.Cmd.onecmd(self, line)
end_time = time.time()
print('took %.3f seconds' % (end_time - start_time))
return result
else:
return cmd.Cmd.onecmd(self, line)
except DeviceError as err:
print_err(err)
except ShellError as err:
print_err(err)
except SystemExit:
# When you use -h with argparse it winds up call sys.exit, which
# raises a SystemExit. We intercept it because we don't want to
# exit the shell, just the command.
return False
def do_help(self, line):
"""help [COMMAND]
List available commands with no arguments, or detailed help when
a command is provided.
"""
# We provide a help function so that we can trim the leading spaces
# from the docstrings. The builtin help function doesn't do that.
if not line:
cmd.Cmd.do_help(self, line)
self.print("Use Control-D to exit rshell.")
return
parser = self.create_argparser(line)
if parser:
parser.print_help()
return
try:
doc = getattr(self, 'do_' + line).__doc__
if doc:
self.print("%s" % trim(doc))
return
except AttributeError:
pass
self.print(str(self.nohelp % (line,)))
def __init__(self, addr, standard_client=None):
cmd.Cmd.__init__(self)
self.addr = addr
self.sok = nnpy.Socket(nnpy.AF_SP, nnpy.REQ)
try:
self.sok.connect(self.addr)
self.sok.setsockopt(nnpy.SOL_SOCKET, nnpy.RCVTIMEO, 500)
except:
print "Impossible to connect to provided socket (bad format?)"
sys.exit(1)
self.req_id = 0
self.switch_id = 0
# creates new attributes
self.reset()
# creates new attributes
self.standard_client = standard_client
self.json_dependent_init()
def do_help(self, arg):
"""h(elp)
Without argument, print the list of available commands.
With a command name as argument, print help about that command.
"help pdb" shows the full pdb documentation.
"help exec" gives help on the ! command.
"""
if not arg:
return cmd.Cmd.do_help(self, arg)
try:
try:
topic = getattr(self, 'help_' + arg)
return topic()
except AttributeError:
command = getattr(self, 'do_' + arg)
except AttributeError:
self.error('No help for %r' % arg)
else:
if sys.flags.optimize >= 2:
self.error('No help for %r; please do not run Python with -OO '
'if you need command help' % arg)
return
self.message(command.__doc__.rstrip())
def test_input_reset_at_EOF(self):
input = io.StringIO("print test\nprint test2")
output = io.StringIO()
cmd = self.simplecmd2(stdin=input, stdout=output)
cmd.use_rawinput = False
cmd.cmdloop()
self.assertMultiLineEqual(output.getvalue(),
("(Cmd) test\n"
"(Cmd) test2\n"
"(Cmd) *** Unknown syntax: EOF\n"))
input = io.StringIO("print \n\n")
output = io.StringIO()
cmd.stdin = input
cmd.stdout = output
cmd.cmdloop()
self.assertMultiLineEqual(output.getvalue(),
("(Cmd) \n"
"(Cmd) \n"
"(Cmd) *** Unknown syntax: EOF\n"))
def test_input_reset_at_EOF(self):
input = StringIO.StringIO("print test\nprint test2")
output = StringIO.StringIO()
cmd = self.simplecmd2(stdin=input, stdout=output)
cmd.use_rawinput = False
cmd.cmdloop()
self.assertMultiLineEqual(output.getvalue(),
("(Cmd) test\n"
"(Cmd) test2\n"
"(Cmd) *** Unknown syntax: EOF\n"))
input = StringIO.StringIO("print \n\n")
output = StringIO.StringIO()
cmd.stdin = input
cmd.stdout = output
cmd.cmdloop()
self.assertMultiLineEqual(output.getvalue(),
("(Cmd) \n"
"(Cmd) \n"
"(Cmd) *** Unknown syntax: EOF\n"))
def test_input_reset_at_EOF(self):
input = StringIO.StringIO("print test\nprint test2")
output = StringIO.StringIO()
cmd = self.simplecmd2(stdin=input, stdout=output)
cmd.use_rawinput = False
cmd.cmdloop()
self.assertMultiLineEqual(output.getvalue(),
("(Cmd) test\n"
"(Cmd) test2\n"
"(Cmd) *** Unknown syntax: EOF\n"))
input = StringIO.StringIO("print \n\n")
output = StringIO.StringIO()
cmd.stdin = input
cmd.stdout = output
cmd.cmdloop()
self.assertMultiLineEqual(output.getvalue(),
("(Cmd) \n"
"(Cmd) \n"
"(Cmd) *** Unknown syntax: EOF\n"))
def __init__(self, args):
# init cmd module
cmd.Cmd.__init__(self)
self.debug = args.debug # debug mode
self.quiet = args.quiet # quiet mode
self.mode = args.mode # command mode
# connect to device
self.do_open(args.target, 'init')
# log pjl/ps cmds to file
if args.log:
self.logfile = log().open(args.log)
header = None
if self.mode == 'ps': header = c.PS_HEADER
if self.mode == 'pcl': header = c.PCL_HEADER
if header: log().write(self.logfile, header + os.linesep)
# run pret cmds from file
if args.load:
self.do_load(args.load)
# input loop
self.cmdloop()
def do_cmd(self, s=''):
"""
Generate a command line to call the
ability with the current parameters from
a standard system's script.
Your can specify the 'oneline' argument to have
a one-line version to run the ability directly
from a system's shell.
"""
self._view.delimiter("Cmd to replay the module")
options, command = self._generate_command()
if s == "oneline":
sep = ' '
self._view.info('{}{};{}'.format(sep.join(options), sep, command))
else:
sep = '\n'
self._view.info('{}{}{}'.format(
sep.join(['export {}'.format(opt) for opt in options]),
sep, command
))
def __init__ (self, image) :
cmd.Cmd.__init__(self)
self.__image = image
self.__wd = image['system']
self.__base = self.__wd
self.__user = image['meta']['user']
self.__host = image['meta']['hostname']
col = color['green']
symb = '$'
if self.__image['meta']['UID'] == 0 :
col = color['red']
symb = '#'
self.prompt_format = self.prompt_format % (col, self.__user, self.__host, color['END'], symb)
self.change_prompt(self.__wd)
def do_help(self, arg):
"""h(elp)
Without argument, print the list of available commands.
With a command name as argument, print help about that command.
"help pdb" shows the full pdb documentation.
"help exec" gives help on the ! command.
"""
if not arg:
return cmd.Cmd.do_help(self, arg)
try:
try:
topic = getattr(self, 'help_' + arg)
return topic()
except AttributeError:
command = getattr(self, 'do_' + arg)
except AttributeError:
self.error('No help for %r' % arg)
else:
if sys.flags.optimize >= 2:
self.error('No help for %r; please do not run Python with -OO '
'if you need command help' % arg)
return
self.message(command.__doc__.rstrip())
def test_input_reset_at_EOF(self):
input = io.StringIO("print test\nprint test2")
output = io.StringIO()
cmd = self.simplecmd2(stdin=input, stdout=output)
cmd.use_rawinput = False
cmd.cmdloop()
self.assertMultiLineEqual(output.getvalue(),
("(Cmd) test\n"
"(Cmd) test2\n"
"(Cmd) *** Unknown syntax: EOF\n"))
input = io.StringIO("print \n\n")
output = io.StringIO()
cmd.stdin = input
cmd.stdout = output
cmd.cmdloop()
self.assertMultiLineEqual(output.getvalue(),
("(Cmd) \n"
"(Cmd) \n"
"(Cmd) *** Unknown syntax: EOF\n"))
def pseudo_raw_input(self, prompt):
"""copied from cmd's cmdloop; like raw_input, but accounts for changed stdin, stdout"""
if self.use_rawinput:
try:
line = raw_input(prompt)
except EOFError:
line = 'EOF'
else:
self.stdout.write(prompt)
self.stdout.flush()
line = self.stdin.readline()
if not len(line):
line = 'EOF'
else:
if line[-1] == '\n': # this was always true in Cmd
line = line[:-1]
return line
def __init__( self, handler, **kw ) :
cmd.Cmd.__init__(self)
arguments = defaultArgMerging(BaseShell.Defaults, kw)
self.prompt_templ = arguments['prompt']
self.ignore_messages = arguments['ignore_messages']
self.output = arguments['output']
self.debug = arguments['debug']
subshells = arguments['subshells']
self.subshells_dict = {}
self.handler = handler
for stream_name, subshell_attrs in subshells.items() :
if type(subshell_attrs) is tuple :
subshell_class, subshell_kwargs = subshell_attrs
else :
subshell_class, subshell_kwargs = (subshell_attrs, dict())
self.addSubShell( stream_name, subshell_class, subshell_kwargs )
handler.onChunk = handlerCallbackHook( handler.onChunk, self.subshells_dict )
self.updatePrompt()
self.sysinfo = None
def test_input_reset_at_EOF(self):
input = StringIO.StringIO("print test\nprint test2")
output = StringIO.StringIO()
cmd = self.simplecmd2(stdin=input, stdout=output)
cmd.use_rawinput = False
cmd.cmdloop()
self.assertMultiLineEqual(output.getvalue(),
("(Cmd) test\n"
"(Cmd) test2\n"
"(Cmd) *** Unknown syntax: EOF\n"))
input = StringIO.StringIO("print \n\n")
output = StringIO.StringIO()
cmd.stdin = input
cmd.stdout = output
cmd.cmdloop()
self.assertMultiLineEqual(output.getvalue(),
("(Cmd) \n"
"(Cmd) \n"
"(Cmd) *** Unknown syntax: EOF\n"))
def do_help(self, arg):
"""h(elp)
Without argument, print the list of available commands.
With a command name as argument, print help about that command.
"help pdb" shows the full pdb documentation.
"help exec" gives help on the ! command.
"""
if not arg:
return cmd.Cmd.do_help(self, arg)
try:
try:
topic = getattr(self, 'help_' + arg)
return topic()
except AttributeError:
command = getattr(self, 'do_' + arg)
except AttributeError:
self.error('No help for %r' % arg)
else:
if sys.flags.optimize >= 2:
self.error('No help for %r; please do not run Python with -OO '
'if you need command help' % arg)
return
self.message(command.__doc__.rstrip())
def test_input_reset_at_EOF(self):
input = io.StringIO("print test\nprint test2")
output = io.StringIO()
cmd = self.simplecmd2(stdin=input, stdout=output)
cmd.use_rawinput = False
cmd.cmdloop()
self.assertMultiLineEqual(output.getvalue(),
("(Cmd) test\n"
"(Cmd) test2\n"
"(Cmd) *** Unknown syntax: EOF\n"))
input = io.StringIO("print \n\n")
output = io.StringIO()
cmd.stdin = input
cmd.stdout = output
cmd.cmdloop()
self.assertMultiLineEqual(output.getvalue(),
("(Cmd) \n"
"(Cmd) \n"
"(Cmd) *** Unknown syntax: EOF\n"))
def __init__(self, mainMenu):
cmd.Cmd.__init__(self)
self.mainMenu = mainMenu
self.doc_header = 'Commands'
# set the prompt text
self.prompt = '(EmPyre: '+helpers.color("agents", color="blue")+') > '
agents = self.mainMenu.agents.get_agents()
messages.display_agents(agents)
# def preloop(self):
# traceback.print_stack()
# print a nicely formatted help menu
# stolen/adapted from recon-ng
def __init__(self, mainMenu):
cmd.Cmd.__init__(self)
self.doc_header = 'Listener Commands'
self.mainMenu = mainMenu
# get all the the stock listener options
self.options = self.mainMenu.listeners.get_listener_options()
# set the prompt text
self.prompt = '(EmPyre: '+helpers.color("listeners", color="blue")+') > '
# display all active listeners on menu startup
messages.display_listeners(self.mainMenu.listeners.get_listeners())
# def preloop(self):
# traceback.print_stack()
# print a nicely formatted help menu
# stolen/adapted from recon-ng
def __init__(self, mainMenu, stagerName, listener=None):
cmd.Cmd.__init__(self)
self.doc_header = 'Stager Menu'
self.mainMenu = mainMenu
# get the current stager name
self.stagerName = stagerName
self.stager = self.mainMenu.stagers.stagers[stagerName]
# set the prompt text
self.prompt = '(EmPyre: '+helpers.color("stager/"+self.stagerName, color="blue")+') > '
# if this menu is being called from an listener menu
if listener:
# resolve the listener ID to a name, if applicable
listener = self.mainMenu.listeners.get_listener(listener)
self.stager.options['Listener']['Value'] = listener
def __init__(self, *args, **kwargs):
cmd.Cmd.__init__(self, *args, **kwargs)
self.status = 'status'
path = [os.path.expanduser('~'), self.status,
'%s.yml' % self._get_next_monday().strftime("%B-%m-%d").lower()]
self.file = '/'.join(path)
if not os.path.exists(self.file):
file(self.file, 'w').close()
content = ''
with open(self.file, 'r') as fobj:
content = fobj.read()
self._d = yaml.load(content) or []
self.projects = self._get_projects()