コード例 #1
0
ファイル: icmd.py プロジェクト: vitaliirat/mcplayeredit
	def __init__(self, rootclass, prompt='> ', histfile=os.path.join(os.environ.get('HOME', ''), '.icmd_hist'), welcometext='Type \'help\' for help.', helptext_prefix='The following commands are available:\n', helptext_suffix='\n(type \'help <command>\' for details)\n', batch=False):
		"""
		Create a new interactive commandline interface to rootclass by creating
		an instance of rootclass (your class must derive from ICmdBase). Use
		ICmd.run() or run_once() to start the commandline client. `batch`
		indicates wether to run in batch mode. If so, ICmd is silent (except
		for errors) and non-interactive; instead reading from stdin and
		executing each line as a command. It will exit after no more lines are
		available.
		"""
		self.rootclass = rootclass
		self.prompt = prompt
		self.welcometext = welcometext
		self.batch = batch
		self.histfile = histfile
		self.instclass = self.rootclass(helptext_prefix, helptext_suffix, self.batch)

		# Initialize readline, but only if we we're able to load the module.
		if 'readline' in sys.modules or 'pyreadline' in sys.modules:
			logging.info("Using readline")
			try:
				readline.read_history_file(self.histfile)
			except IOError:
				pass
			logging.info("Setting readline completer")
			readline.set_completer(self._completer)
			readline.parse_and_bind("tab: complete")

		if not self.batch:
			sys.stdout.write(welcometext + '\n')
コード例 #2
0
ファイル: keykit_console.py プロジェクト: YggdrasiI/Pyconsole
 def __init__(self, completer=None, shell=None, bBind=True):
     self.prefix = None
     self.shell = shell
     self.completer = \
         self.complete_advanced if completer is None else completer
     if bBind:
         readline.parse_and_bind('tab: complete')
         readline.set_completer(self.complete)
コード例 #3
0
    def __read_input(self):

        readline.set_completer(rlcompleter.Completer(self.__vars).complete)
        readline.parse_and_bind("tab: complete")

        if os.path.exists(self.HistoryFile.value):
            readline.read_history_file(self.HistoryFile.value)

        while (True):
            try:
                line = raw_input('\001' + print_green + '\002' +
                                 self.Prompt.value + '\001' + print_reset +
                                 '\002')
                self.__input_queue.put(line)
            except:
                print "Exiting GuaVe, press Ctrl-C to kill guacamole..."
                #sys.exit(0)
                break
コード例 #4
0
    def __read_input(self):

        readline.set_completer(rlcompleter.Completer(self.__vars).complete)
        readline.parse_and_bind("tab: complete")

        if os.path.exists(self.HistoryFile.value):
            readline.read_history_file(self.HistoryFile.value)

        while True:
            try:
                line = input("\001" + print_green + "\002" + self.Prompt.value + "\001" + print_reset + "\002")
                self.__input_queue.put(line)
            except EOFError:
                print("Bye")  # , press Ctrl-C to kill guacamole...")
                os._exit(0)
            except IOError as err:
                print("I/O error: {0}".format(err))
                os._exit(1)
            except:
                print("Unexpected error:", sys.exc_info()[0])
                os._exit(1)
コード例 #5
0
    def __read_input(self):

        readline.set_completer(rlcompleter.Completer(self.__vars).complete)
        readline.parse_and_bind("tab: complete")

        if os.path.exists(self.HistoryFile.value):
            readline.read_history_file(self.HistoryFile.value)

        while (True):
            try:
                line = input('\001' + print_green + '\002' +
                             self.Prompt.value + '\001' + print_reset + '\002')
                self.__input_queue.put(line)
            except EOFError:
                print("Bye")  #, press Ctrl-C to kill guacamole...")
                os._exit(0)
            except IOError as err:
                print("I/O error: {0}".format(err))
                os._exit(1)
            except:
                print("Unexpected error:", sys.exc_info()[0])
                os._exit(1)
コード例 #6
0
    def _bind_help(self):
        def _show_help_proxy(_, __):
            self._show_help(None, None)

        pyreadline.rl.mode.cly_help = types.MethodType(_show_help_proxy,
                                                       pyreadline.rl.mode,
                                                       pyreadline.Readline)
        pyreadline.parse_and_bind('?: cly-help')
        pyreadline.parse_and_bind('Shift-?: cly-help')
        pyreadline.parse_and_bind('F1: cly-help')
コード例 #7
0
ファイル: CommandLine.py プロジェクト: claudiogreco/turtle

wstream = None

colored_loaded = False

# If the operating system doesn't support the POSIX standard
# then it uses the pyreadline module; otherwise, it uses
# the readline module and it sets the autocompletion.
try:
    if os.name is not 'posix':
        import pyreadline as readline
    else:
        import readline
        if 'libedit' in readline.__doc__:
            readline.parse_and_bind("bind ^I rl_complete")
        else:
            readline.parse_and_bind("tab: complete")

except Exception:
    print '\nWarning! Pyreadline or readline should be installed.\n   Unix-like: "pip install readline"\n \
            Windows: "pip install pyreadline"\nThe system will start without keys support.\n'

# Se sono disponibili le librerie aggiuntive
# allora utilizza i colori; in caso contrario
# utilizza la linea di comando classica
try:
    import sys
    from colorama import init
    from termcolor import colored
    from colorama import AnsiToWin32
コード例 #8
0
"""Utilities functions related to terminal display."""

import re
from difflib import SequenceMatcher

try:
    import pyreadline as readline  # Windows
except ImportError:
    try:
        import gnureadline as readline  # Mac OS X
    except ImportError:
        import readline

from qifqif.terminal import TERM

readline.parse_and_bind('tab: complete')


def colorize_match(t, field, matches=None):
    field_val = t[field]
    if not field_val:
        return None
    match = matches.get(field, '') if matches else ''
    seqmatch = SequenceMatcher(None, field_val, match)
    a, b, size = seqmatch.find_longest_match(0, len(field_val), 0, len(match))
    return (field_val[:a] + TERM.green(field_val[a:a + size]) +
            field_val[a + size:])


class InputCompleter(object):
    """Input completer for categories."""
コード例 #9
0
    USAGE =\
"""
python demo.py start_url
"""
    if len(sys.argv) != 2:
        sys.exit(USAGE)
    start_page = sys.argv[1]

    readline_config = [
        "tab: complete",
        "set show-all-if-unmodified on",
        "set skip-completed-text on",
        "set completion-ignore-case on"
    ]
    for line in readline_config:
        readline.parse_and_bind(line)
    readline.set_completer_delims('')

    spider = ManualSpider()
    spider.visit(start_page, start=True)

    link = link_prompt(spider.get_all_links())
    if not link:
        sys.exit()
    spider.visit(link)

    max_links_in_menu = 5
    while True:
        links = []
        n = 0
        score_1 = None
コード例 #10
0
def main():
    global conf
    global credentials
    global domains
    global have_readline
    global pool_thread

    banner()
    conf = cmdline_parser()
    check_conf()
    pool_thread = threading.BoundedSemaphore(conf.threads)

    try:
        for target in targets:
            pool_thread.acquire()
            current = test_login(target)
            current.daemon = True
            current.start()

        while threading.activeCount() > 1:
            a = 'Caughtit'
            pass

    except KeyboardInterrupt:
        print
        try:
            logger.warn('Test interrupted')
            a = 'Caughtit'
            stop_threads[0] = True
        except KeyboardInterrupt:
            print
            logger.info('User aborted')
            exit(1)

    if successes == 0:
        print '\nNo credentials worked on any target\n'
        exit(0)

    print '\nThe credentials worked in total %d times\n' % successes
    print 'TARGET SORTED RESULTS:\n'

    for target in targets:
        valid_credentials = target.get_valid_credentials()

        if len(valid_credentials) > 0:
            print target.get_identity()

            for valid_credential in valid_credentials:
                print '  %s' % valid_credential.get_identity()

            print

    print '\nUSER SORTED RESULTS:\n'

    for credential in credentials:
        valid_credentials = credential.get_valid_targets()

        if len(valid_credentials) > 0:
            print credential.get_identity()

            for valid_credential in valid_credentials:
                print '  %s' % valid_credential.get_identity()

            print

    if conf.smbcmdlist is not None:
        smb_cmd_list()

    if conf.oscmdlist is not None:
        os_cmd_list()

    if conf.batch or conf.smbcmdlist or conf.oscmdlist:
        return

    while True:
        msg = 'Do you want to establish a SMB shell from any of the targets? [Y/n] '
        choice = raw_input(msg)

        if choice and choice[0].lower() != 'y':
            return

        counter = 0
        targets_dict = {}
        msg = 'Which target do you want to connect to?'

        for target in targets:
            valid_credentials = target.get_valid_credentials()

            if len(valid_credentials) > 0:
                counter += 1
                msg += '\n[%d] %s%s' % (counter, target.get_identity(), ' (default)' if counter == 1 else '')
                targets_dict[counter] = (target, valid_credentials)

        msg += '\n> '
        choice = read_input(msg, counter)
        user_target, valid_credentials = targets_dict[int(choice)]

        counter = 0
        credentials_dict = {}
        msg = 'Which credentials do you want to use to connect?'

        for credential in valid_credentials:
            counter += 1
            msg += '\n[%d] %s%s' % (counter, credential.get_identity(), ' (default)' if counter == 1 else '')
            credentials_dict[counter] = credential

        msg += '\n> '
        choice = read_input(msg, counter)
        user_credentials = credentials_dict[int(choice)]

        if sys.platform.lower() == 'win32' and have_readline:
            try:
                _outputfile = readline.GetOutputFile()
            except AttributeError:
                logger.debug('Failed GetOutputFile when using platform\'s readline library')
                have_readline = False

        uses_libedit = False

        if sys.platform.lower() == 'darwin' and have_readline:
            import commands

            (status, result) = commands.getstatusoutput('otool -L %s | grep libedit' % readline.__file__)

            if status == 0 and len(result) > 0:
                readline.parse_and_bind('bind ^I rl_complete')

                debugMsg = 'Leopard libedit detected when using platform\'s '
                debugMsg += 'readline library'
                logger.debug(debugMsg)

                uses_libedit = True

        try:
            shell = InteractiveShell(user_target, user_credentials, conf.name)
            shell.cmdloop()
        except RuntimeError, e:
            logger.error('Runtime error: %s' % str(e))
        except Exception, _:
            # traceback.print_exc()
            pass
コード例 #11
0
ファイル: simul.py プロジェクト: alendit/simul
        composite_commands = ['set','unset','list','detail','mout','mimage',\
                             'mcopy','detailcopy','perf']
        supported = {'all': ['save','load','compute','out','exit','change',\
                             'copy'],
                     match.Match: ['set','unset','list','image'],\
                     mslgroup.MSLGroup: composite_commands,\
                     sebracket.SEBracket: composite_commands,\
                     debracket.DEBracket: composite_commands,\
                     rrgroup.RRGroup: composite_commands,\
                     combination.Combination: composite_commands,\
                     ipl5.IPL5Bracket: composite_commands}

        words = supported['all'] + supported[type(obj)] + ['name','race','elo']
        completer = Completer(words)
        completer.add_words([p.name for p in obj.get_players()])
        readline.parse_and_bind("tab: complete")
        readline.set_completer(completer.complete)

        while True:
            s = better_input('> ').lower().split(' ')
            s = filter(lambda p: p != '', s)
            s = list(map(lambda p: p.strip(), s))
            if len(s) < 1:
                continue

            if s[0] not in supported['all'] and s[0] not in supported[type(obj)]:
                print('Invalid command for type \'' + str(type(obj)) + '\'')
                continue

            if s[0] == 'exit':
                break
コード例 #12
0
"""
import sys, os
# normal CMT setup does not put ROOT.py in the python path
if sys.platform == 'win32':
    import win32api
    console_title = win32api.GetConsoleTitle()
try:
    import ROOT
except:
    sys.path.append(os.path.join(os.environ['ROOTSYS'], 'bin'))
    import ROOT

if sys.platform == 'win32':
    win32api.SetConsoleTitle(console_title)  #restore title bar!
    import pyreadline  # fix for tab completion
    pyreadline.parse_and_bind('set show-all-if-ambiguous on')

from ROOT import TMinuit, Long, Double

import numpy as np
from numpy.linalg import inv


def rosenbrock(x):
    """Rosenbrock function, to use for testing."""
    return (1 - x[0])**2 + 100 * (x[1] - x[0]**2)**2


def rosengrad(x):
    """Gradient of Rosenbrock function, for testing."""
    drdx = -2 * ((1 - x[0]) + 200 * x[0] * (x[1] - x[0]**2))
コード例 #13
0
ファイル: color_output.py プロジェクト: Kder/color-output
注意: Windows下需要pyreadline模块
作者:Kder [ http://www.kder.info/ ]
许可:Apache License V2

'''
import sys
import rlcompleter

def uprint(msg):
    msg = str(msg)
    try:
        print(msg.decode('utf-8'))
    except UnicodeDecodeError as e:
        print(msg.decode('gbk'))

if sys.platform == 'win32':
    try:
        import pyreadline
        pyreadline.parse_and_bind("tab: complete")
        sys.stdout = pyreadline.console.Console(0)
    except:
        pass
    # colored = colored_console.write_color
else:
    import readline
    readline.parse_and_bind("tab: complete")


if __name__ == "__main__":
    uprint("\033[32m绿色\033[0m \033[36m蓝色\033[0m \033[31m红色\033[0m")