Python cmd.Cmd() Examples

The following are 30 code examples of cmd.Cmd(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cmd , or try the search function .
Example #1
Source File: test_cmd.py    From BinderFilter with MIT License 6 votes vote down vote up
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")) 
Example #2
Source File: test_cmd.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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")) 
Example #3
Source File: wmi_exec.py    From MultiProxies with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, share, win32Process, smbConnection):
        cmd.Cmd.__init__(self)
        self.__share = share
        self.__output = '\\' + 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'

        # 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 
Example #4
Source File: cmedb.py    From CrackMapExec with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, config_path):
        cmd.Cmd.__init__(self)

        self.config_path = config_path

        try:
            self.config = configparser.ConfigParser()
            self.config.read(self.config_path)
        except Exception as e:
            print("[-] Error reading cme.conf: {}".format(e))
            sys.exit(1)

        self.workspace_dir = os.path.expanduser('~/.cme/workspaces')
        self.conn = None
        self.p_loader = protocol_loader()
        self.protocols = self.p_loader.get_protocols()

        self.workspace = self.config.get('CME', 'workspace')
        self.do_workspace(self.workspace)

        self.db = self.config.get('CME', 'last_used_db')
        if self.db:
            self.do_proto(self.db) 
Example #5
Source File: smb_exec.py    From MultiProxies with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, share, rpc, mode):
        cmd.Cmd.__init__(self)
        self.__share = share
        self.__mode = mode
        self.__output = '\\Windows\\Temp\\' + OUTPUT_FILENAME
        self.__batchFile = '%TEMP%\\' + BATCH_FILENAME
        self.__outputBuffer = ''
        self.__command = ''
        self.__shell = '%COMSPEC% /Q /c '
        self.__serviceName = 'BTOBTO'.encode('utf-16le')
        self.intro = '[!] Launching semi-interactive shell - Careful what you execute'

        dce = dcerpc.DCERPC_v5(rpc)


        try:
            dce.connect()
        except Exception, e:
            pass 
Example #6
Source File: wmiexec.py    From spraykatz with MIT License 6 votes vote down vote up
def __init__(self, share, win32Process, smbConnection):
        cmd.Cmd.__init__(self)
        self.__share = share
        self.__output = '\\' + OUTPUT_FILENAME
        self.__outputBuffer = str('')
        self.__shell = 'cmd.exe /Q /c '
        self.__win32Process = win32Process
        self.__transferClient = smbConnection
        self.__pwd = str('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(1000000)
            self.do_cd('\\')
        else:
            self.__noOutput = True 
Example #7
Source File: pdb.py    From meddle with MIT License 6 votes vote down vote up
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) 
Example #8
Source File: wmiexec_delete.py    From spraykatz with MIT License 6 votes vote down vote up
def __init__(self, share, win32Process, smbConnection):
        cmd.Cmd.__init__(self)
        self.__share = share
        self.__output = '\\' + OUTPUT_FILENAME
        self.__outputBuffer = str('')
        self.__shell = 'cmd.exe /Q /c '
        self.__win32Process = win32Process
        self.__transferClient = smbConnection
        self.__pwd = str('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(1000000)
            self.do_cd('\\')
        else:
            self.__noOutput = True 
Example #9
Source File: vibe.py    From Vibe with MIT License 6 votes vote down vote up
def do_columns(self, option, intro=None):
			try:
				if option == "users":
					print "[-] Displaying the columns in the User Table"
					tb = dp.read_sql('select *from UserTB', conn)
					print tb.columns.values.tolist()
				elif option == "groups":
					print "[-] Displaying the columns in the Group Table"
					tb = dp.read_sql('select *from GroupTB', conn)
					print tb.columns.values.tolist()
				elif option == "computers":
					print "[-] Displaying the columns in the Computer Table"
					tb = dp.read_sql('select *from ComputerTB', conn)
					print tb.columns.values.tolist()
				else:
					print "Not one of the tables."
			except pandas.io.sql.DatabaseError:
				print colors.RD + "[-] " + colors.NRM + "Error: Empty database."
			return cmd.Cmd.cmdloop(self, intro) 
Example #10
Source File: cmd2.py    From Beehive with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #11
Source File: vibe.py    From Vibe with MIT License 6 votes vote down vote up
def do_share_hunter(self, option, intro=None):
			try:
				self.cmd_sub_arg_parse(option)
				if not netaddr:
					print colors.RD + "[-] " + colors.NRM + "No target provided. Please try again"
					return
				else:
					targets = IP(netaddr)
				if not user and not password and not domain:
					print colors.RD + "[-] " + colors.NRM + "Missing user information (i.e Domain, Username, Password). Please try again"
				else:
					pass

				sh = Share_Hunting(domain, user, password, jitter)
				print targets
				sh.share_hunter(targets)
			except IndexError:
				print colors.RD + "[-] " + colors.NRM + "Invalid Option"
				print colors.BLU + "[*] " + colors.NRM + "Scans target(s) enumerating the shares on the target(s) and the level of access the specified user, using  -u/--user. Can take a list or range of hosts, using -t/--target. Example  share_hunter --user admin -t 192.168.1./24 -j 3."
			except KeyboardInterrupt:
				return
			return cmd.Cmd.cmdloop(self, intro) 
Example #12
Source File: vibe.py    From Vibe with MIT License 6 votes vote down vote up
def do_help(self, intro=None):
			print "Commands"
			print "========"
			print "clear                Clears the screen"
			print "help                 Displays this help menu"
			print "list                 Lists either all Users, Computers, or Groups. Use the -f option to pipe the contents to a file"
			print "session              Scans target(s) to see who has/is currently logged in. Can take a list or range of hosts, using -t/--target and specify a user using -d/--domain, -u/--user, -p/--password and --jitter/-j to add a delay. Requires: read/write privileges on either Admin$ or C$ share"
			print "net                  Perform a query to view all information pertaining to a specific user, group, or computer (Similar to the Windows net user, net group commands). example: \'net group Domain Admins\'"
			print "columns              Displays the column names in each of the three major tables (users, groups and computers"
			print "query                Executes a query on the contents of tables"
			print "search               Searches for a key word(s) through every field of every table for any matches, displaying row"
			print "share_hunter         Scans target(s) enumerating the shares on the target(s) and the level of access the specified user, using -d/--domain, -u/--user, -p/--password. Can take a list or range of hosts, using -t/--target and --jitter/-j to add a delay"
			print "show                 Shows the contents of Users, Computers, Credentials, Groups, Password policy, Store, Credentials, Files Servers and Access tables"
			print "store                Displays the contents of a specific table. Example: \'show [table name] (access, creds, computers, file servers, pwdpolicy, users)"
			print "export               Export the contents of the database to a path in one of the following formats: CSV, HTML. (using with -f or --filetype)"
			print "exit                 Exit Vibe"
			return cmd.Cmd.cmdloop(self, intro) 
Example #13
Source File: mpfshell.py    From mpfshell with MIT License 6 votes vote down vote up
def __init__(self, color=False, caching=False, reset=False):
        if color:
            colorama.init()
            cmd.Cmd.__init__(self, stdout=colorama.initialise.wrapped_stdout)
        else:
            cmd.Cmd.__init__(self)

        if platform.system() == "Windows":
            self.use_rawinput = False

        self.color = color
        self.caching = caching
        self.reset = reset

        self.fe = None
        self.repl = None
        self.tokenizer = Tokenizer()

        self.__intro()
        self.__set_prompt_path() 
Example #14
Source File: cmd2.py    From WebPocket with GNU General Public License v3.0 6 votes vote down vote up
def run_transcript_tests(self, callargs: List[str]) -> None:
        """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 of transcript test file names
        """
        import unittest
        from .transcript import Cmd2TestCase

        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) 
Example #15
Source File: cmd2plus.py    From OpenTrader with GNU Lesser General Public License v3.0 6 votes vote down vote up
def pseudo_raw_input(self, prompt):
        """copied from cmd cmdloop; like raw_input, but accounts for changed stdin, stdout"""

        if self.use_rawinput:
            try:
                line = raw_input(prompt)
            except EOFError:
                if self.continue_on_eof:
                    line = '#'
                    # Fixme: sys.stdin
                else:
                    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 
Example #16
Source File: test_cmd.py    From oss-ftp with MIT License 6 votes vote down vote up
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")) 
Example #17
Source File: vibe.py    From Vibe with MIT License 5 votes vote down vote up
def do_store(self, intro=None):
			global store
			store = precommand
			return cmd.Cmd.cmdloop(self, intro) 
Example #18
Source File: __main__.py    From pyamaha with MIT License 5 votes vote down vote up
def __init__(self):
        cmd.Cmd.__init__(self)
        self.prompt = '{}>'.format(RootCli.PROMPT)
    # end-of-method __init__ 
Example #19
Source File: vibe.py    From Vibe with MIT License 5 votes vote down vote up
def do_search(self, option, intro=None):
			try:
				value = option
				dp.options.display.max_colwidth = 40000
				group_tb = dp.read_sql('select * from GroupTB where Name like "%' + value + '%" or SID like "%' + value + '%" or Description like "%' + value + '%" or "Member Of" like "%' + value + '%"  or Members like "%' + value + '%"  COLLATE NOCASE', conn)
				group_tb['Description'] = group_tb['Description'].str[:35] + '...'
				if group_tb.empty:
					pass
				else:
					print "Groups"
					print "---------"
					print (tabulate(group_tb, showindex=False, headers=group_tb.columns, tablefmt="grid"))
				user_tb = dp.read_sql('select * from UserTB where Username like "%' + value + '%" or Description like "%' + value + '%" or SID like "%' + value + '%" or "Profile Path" like "%' + value + '%" or "Home Directory" like "%' + value + '%" or "Password Last Set" like "%' + value + '%" or "Last Logged On" like "%' + value + '%" or "Account Settings" like "%' + value + '%" or "Primary Group Name" like "%' + value + '%" or "Member Of" like "%' + value + '%" COLLATE NOCASE', conn)
				user_tb['Description'] = user_tb['Description'].str[:35] + '...'
				user_tb['Member Of'] = user_tb[['Primary Group Name', 'Member Of']].sum(axis=1)
				del user_tb['Primary Group Name']
				if user_tb.empty:
					pass
				else:
					print "Users"
					print "---------"
					print (tabulate(user_tb, showindex=False, headers=user_tb.columns, tablefmt="grid"))
				computer_tb = dp.read_sql('select * from ComputerTB where Name like "%' + value + '%" or Description like "%' + value + '%" or "Operating System" like "%' + value + '%" or "Operating System Version Number" like "%' + value + '%"  or "Member Of" like "%' + value + '%" COLLATE NOCASE', conn)
				if computer_tb.empty:
					pass
				else:
					print "Computers"
					print "---------"
					print (tabulate(computer_tb, showindex=False, headers=computer_tb.columns, tablefmt="grid"))
				return cmd.Cmd.cmdloop(self, intro)
			except KeyboardInterrupt:
				return
			return cmd.Cmd.cmdloop(self, intro) 
Example #20
Source File: plac_ext.py    From plac with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def add(cls, obj, specialcommands):
        p = plac_core.parser_from(obj)
        c = cmd.Cmd(stdout=cls())
        c.stdout.write('\n')
        c.print_topics('special commands',
                       sorted(specialcommands), 15, 80)
        c.print_topics('custom commands',
                       sorted(obj.commands), 15, 80)
        c.print_topics('commands run in external processes',
                       sorted(obj.mpcommands), 15, 80)
        c.print_topics('threaded commands',
                       sorted(obj.thcommands), 15, 80)
        p.helpsummary = str(c.stdout) 
Example #21
Source File: __main__.py    From pyamaha with MIT License 5 votes vote down vote up
def __init__(self, top):
        cmd.Cmd.__init__(self)
        self.prompt = '{}\{}>'.format(top, ZoneCli.PROMPT)
    # end-of-method __init__ 
Example #22
Source File: __main__.py    From pyamaha with MIT License 5 votes vote down vote up
def __init__(self, top):
        cmd.Cmd.__init__(self)
        self.prompt = '{}\{}>'.format(top, SystemCli.PROMPT)
    # end-of-method __init__ 
Example #23
Source File: __init__.py    From QUANTAXIS with MIT License 5 votes vote down vote up
def __init__(self):
        cmd.Cmd.__init__(self)
        self.prompt = 'QUANTAXIS> ' # 定义命令行提示符 
Example #24
Source File: cli.py    From pina-colada with MIT License 5 votes vote down vote up
def cmdloop(self):
        try:
            cmd.Cmd.cmdloop(self)
        except KeyboardInterrupt:
            if not self.ctrlc: 
                self.ctrlc = True
                print("\n" + BAD + "Please run \"quit\" or \"exit\" to exit, or press Ctrl-C again.")
                self.cmdloop()
            else:
                print("")
                self.quit() 
Example #25
Source File: cli.py    From pina-colada with MIT License 5 votes vote down vote up
def preloop(self):
        cmd.Cmd.preloop(self)   ## sets up command completion
        self._hist    = []      ## No history yet
        self._locals  = {}      ## Initialize execution namespace for user
        self._globals = {} 
Example #26
Source File: cli.py    From pina-colada with MIT License 5 votes vote down vote up
def __init__(self):
        cmd.Cmd.__init__(self)
        self.core = core.PinaColada()
        self.ctrlc = False
        self.ascii_art()
        print "Welcome to Pina Colada, a powerful Wifi Dropbox. Type \"help\" to see the list of available commands."
        print "Defaulting to interface %s (%s)." % (self.core.default_iface, self.core.get_local_ip(self.core.default_iface)) 
Example #27
Source File: interface.py    From pina-colada with MIT License 5 votes vote down vote up
def preloop(self):
        cmd.Cmd.preloop(self)   ## sets up command completion
        self._hist    = []      ## No history yet
        self._locals  = {}      ## Initialize execution namespace for user
        self._globals = {} 
Example #28
Source File: interface.py    From pina-colada with MIT License 5 votes vote down vote up
def __init__(self, core, capability):
        cmd.Cmd.__init__(self)
        self.capability = capability
        self.core = core
        self.help_text = None
        self.prompt = Fore.RED + "("+self.capability.name+") " + Fore.BLUE + ">> " + Fore.RESET 
Example #29
Source File: framework.py    From Maryam with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, params):
		cmd.Cmd.__init__(self)
		self._modulename = params
		self.ruler = '-'
		self.spacer = '  '
		self.nohelp = f'{Colors.R}[!] No help on %s{Colors.N}'
		self.do_help.__func__.__doc__ = '''Displays this menu'''
		self.doc_header = 'Commands (type [help|?] <topic>):'
		self._exit = 0

	# ==================================================
	# CMD OVERRIDE METHODS
	# ================================================== 
Example #30
Source File: Interactive.py    From pivy with ISC License 5 votes vote down vote up
def __init__(self, **kw):
        cmd.Cmd.__init__(self)
        for key, val in kw.items():
            setattr(self, key, val)

        if sys.platform == 'win32':
            self.shell_variable = 'COMSPEC'
        else:
            self.shell_variable = 'SHELL'