我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用cmd.Cmd()。
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()
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 __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 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 __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()
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 = sm.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 onecmd(self, line): """ Wrap error handling around cmd.Cmd.onecmd(). Might want to do something kinder than showing a traceback, eventually. """ self.last_command_failed = False try: return cmd.Cmd.onecmd(self, line) except SystemExit: raise except ExitArgparse, e: if e.message is not None: print e.message self.last_command_failed = e.status != 0 return False except BadCommandSyntax, e: print e except Exception: traceback.print_exc() self.last_command_failed = True return False
def onecmd(self, line): """Interpret the argument as though it had been typed in response to the prompt. Checks whether this line is typed at the normal prompt or in a breakpoint command list definition. """ if not self.commands_defining: return cmd.Cmd.onecmd(self, line) else: return self.handle_command_def(line)
def __init__(self, profile=None): cmd.Cmd.__init__(self) self.prompt = "% " self.stats = None self.stream = sys.stdout if profile is not None: self.do_read(profile)
def __init__(self): cmd.Cmd.__init__(self) self.prompt = 'QUANTAXIS> ' # ????????
def __init__(self, pre_type, standard_client, mc_client=None): cmd.Cmd.__init__(self) self.client = standard_client self.mc_client = mc_client self.pre_type = pre_type
def __init__(self, env, quiet=False): self.env = env if not quiet: self.intro = "RavelConsole: interactive console for Ravel.\n" \ "Configuration:\n" + self.env.pprint() cmd.Cmd.__init__(self) self.env.set_cli(self)
def do_help(self, arg): "List available commands with 'help' or detailed help with 'help cmd'" # extend to include loaded apps and their help methods tokens = arg.split() if len(tokens) > 0 and tokens[0] in self.env.loaded: app = self.env.apps[tokens[0]] if len(tokens) <= 1: print app.description app.console.do_help("") else: app.console.do_help(" ".join(tokens[1:])) else: cmd.Cmd.do_help(self, arg)
def completenames(self, text, *ignored): "Add loaded application names/shortcuts to cmd name completions" completions = cmd.Cmd.completenames(self, text, ignored) apps = self.env.loaded.keys() if not text: completions.extend(apps) else: completions.extend([d for d in apps if d.startswith(text)]) return completions
def __init__(self, db, env, components): """db: a ravel.db.RavelDb instance env: a ravel.env.Environment instance of the CLI's executing environment components: list of the app's SQL components (tables, view, etc.)""" self.db = db self.env = env self.components = components cmd.Cmd.__init__(self)
def __init__(self, file_name, options): cmd.Cmd.__init__(self) self.units = [] self.file_name = file_name self.env_list = [] # ?????? self.cmd_parser = False self.options = options
def __init__(self, request, print_full_response=False): cmd.Cmd.__init__(self) self.request = request self.print_full_response = print_full_response self.prompt = PROMPT
def __init__(self): cmd.Cmd.__init__(self) # Declaration of the variables. self.__strategy = DepthStrategy() self.clear() # Declaration of the variables of the shell. global wstream, colored_loaded self.__milestone = 'Almost Ninja' self.__version = '1.0' self.__main_title = 'TURTLE v' + self.__version + ' (' + self.__milestone + ')' self.__wstream = wstream self.__colored_loaded = colored_loaded self.__error_prefix = str(colortext(r'[ERROR] ', 'red', True)) self.__start_time = 0 self.__elapsed_time = 0 self.__stats = True self.__default_exception_message = 'Unknown exception!' self.use_rawinput = True self.ruler = '=' self.default_file_name = 'new.clp' self.prompt = str(colortext('TURTLE> ', 'green')) self.intro = """\ __ .,-;-;-,. /'_\ """ + self.__main_title + """ _/_/_/_|_\_\) / '-<_><_><_><_>=/\ An expert system shell inspired by CLIPS syntax `/_/====/_/-'\_\\ Running on Python """ + str(platform.python_version()) + ' ' + str(platform.architecture()[0]) + """ '' '' '' Usage: help to see online help <Tab> to show commands <Up-arrow>, <Down-arrow> to scroll through the history <Ctrl-d>, quit or exit to leave """
def cmdloop(self, intro=None): print('cmdloop({})'.format(intro)) return cmd.Cmd.cmdloop(self, intro)
def parseline(self, line): print('parseline({!r}) =>'.format(line), end='') ret = cmd.Cmd.parseline(self, line) print(ret) return ret
def onecmd(self, s): print('onecmd({})'.format(s)) return cmd.Cmd.onecmd(self, s)
def emptyline(self): print('emptyline()') return cmd.Cmd.emptyline(self)