Пример #1
0
    def _run(self):
        try:
            while self.running():
                with self._lock:
                    if self._code:
                        codeColor = Fore.RED
                    else:
                        codeColor = Fore.GREEN

                    cliJoined = ' '.join(self._cli)
                    codePart = '{}{}{}'.format(
                        codeColor, self._code, Style.RESET_ALL)
                    cliPart = '{}{}{}'.format(
                        Fore.LIGHTCYAN_EX, cliJoined, Style.RESET_ALL)

                    line = input('[{}] ({}) > '.format(codePart, cliPart))
                    if readline.get_history_length() == 0:
                        readline.add_history(line)
                    elif line != readline.get_history_item(readline.get_current_history_length()):
                        readline.add_history(line)

                    self._execute(shlex.split(line))
        except EOFError:
            self.stop()
            try:
                readline.write_history_file(self._historyFile)
            except:
                print()
                print('Could not save history file: {}'.format(
                    self._historyFile))
Пример #2
0
    def __init__(self, env):
        """Set up the seval REPL.

        We open a .history file in ~/.config/seval_history, or create
        it if it doesn't exist.

        We then save the build the tab completer with the environment
        passed into the object, and finally save the environment.

        """
        try:
            readline.read_history_file(HISTFILE)
            self.history_length = readline.get_history_length()
        except FileNotFoundError:
            open(HISTFILE, 'wb').close()
            self.history_length = 0

        completer = readline_completer.Completer(namespace=env)
        readline.set_completer(completer.complete)
        readline.parse_and_bind('tab: complete')
        self.built_ins = {
            "print_env":
            (self.toggle_print_env,
             "Toggle printing the environment after each command"),
            "env": (self.print_env, "Print the whole environment"),
            "help": (self.print_help, "Display this message")
        }

        self.env = env
Пример #3
0
 def __init__(self,
              env,
              path_from_home=None,
              prompt_method=None,
              path_delimeter=None,
              stdin=None,
              stdout=None,
              stderr=None,
              logger=None,
              add_setup_menu=False):
     # Note super does not work as Cmd() is an 'old style' class which
     # does not inherit from object(). Instead call init directly.
     #self._submenu_names = None
     self._last_keyboard_interupt = 0
     signal.signal(signal.SIGINT, self._keyboard_interupt_handler)
     if 'colorama' in sys.modules:
         init()
     self.stdout = stdout or env.default_output or sys.stdout
     self.stdin = stdin or env.default_input or sys.stdin
     # Attempt to populate the command history from history file,
     # if it has not yet, and the file is provided and exists
     try:
         history_len = readline.get_history_length()
         if history_len < 1:
             history_path = getattr(env.simplecli_config, 'history_file',
                                    None)
             if history_path and os.path.exists(history_path):
                 readline.read_history_file(history_path)
     except ImportError as IE:
         self.eprint('Failed to read in history file, err:{0}'.format(IE))
         pass
     Cmd.__init__(self, completekey='tab', stdin=stdin, stdout=stdout)
     self.stderr = stderr or env.default_error or sys.stderr
     if not self.name:
         raise ValueError('Class must define "name", extend BaseEnv')
     assert isinstance(env, BaseEnv), "env variable must be of type BaseEnv"
     self._add_setup_menu = add_setup_menu
     # Env should be of type BaseEnv or None
     self.env = env
     # Use the shared env logger if provided for ease of controlling log levels, etc.
     self.logger = logger
     if not self.logger and hasattr(self.env, 'logger'):
         self.logger = self.env.logger
     # Setup CLI interface
     #if self.env and self.env.home is None:
     #    print('({0}): setting self for env.home:"{1}"'.format(self, self.env.home))
     #    self.env.home = self
     #    readline.set_completion_display_matches_hook(self._completer_display)
     self.callers = []
     self.prompt_method = prompt_method or env.simplecli_config.prompt_method
     self.path_delimeter = path_delimeter or env.simplecli_config.path_delimeter
     self._path_from_home = []
     self.path_from_home = path_from_home
     self._setup()
     self._init_submenus()
     self._old_completer = readline.get_completer()
     if self.env and not self.env.get_cached_menu_by_class(self.__class__):
         self.env.menu_cache.append(self)
Пример #4
0
 def __init__(self,
              env,
              path_from_home=None,
              prompt_method=None,
              path_delimeter=None,
              stdin=None,
              stdout=None,
              stderr=None,
              logger=None,
              add_setup_menu=False):
     # Note super does not work as Cmd() is an 'old style' class which
     # does not inherit from object(). Instead call init directly.
     #self._submenu_names = None
     self._last_keyboard_interupt = 0
     signal.signal(signal.SIGINT, self._keyboard_interupt_handler)
     if 'colorama' in sys.modules:
         init()
     self.stdout = stdout or env.default_output or sys.stdout
     self.stdin = stdin or env.default_input or sys.stdin
     # Attempt to populate the command history from history file,
     # if it has not yet, and the file is provided and exists
     try:
         history_len = readline.get_history_length()
         if history_len < 1:
             history_path = getattr(env.simplecli_config, 'history_file', None)
             if history_path and os.path.exists(history_path):
                 readline.read_history_file(history_path)
     except ImportError as IE:
         self.eprint('Failed to read in history file, err:{0}'.format(IE))
         pass
     Cmd.__init__(self, completekey='tab', stdin=stdin, stdout=stdout)
     self.stderr = stderr or env.default_error or sys.stderr
     if not self.name:
         raise ValueError('Class must define "name", extend BaseEnv')
     assert isinstance(env, BaseEnv), "env variable must be of type BaseEnv"
     self._add_setup_menu = add_setup_menu
     # Env should be of type BaseEnv or None
     self.env = env
     # Use the shared env logger if provided for ease of controlling log levels, etc.
     self.logger = logger
     if not self.logger and hasattr(self.env, 'logger'):
         self.logger = self.env.logger
     # Setup CLI interface
     #if self.env and self.env.home is None:
     #    print('({0}): setting self for env.home:"{1}"'.format(self, self.env.home))
     #    self.env.home = self
     #    readline.set_completion_display_matches_hook(self._completer_display)
     self.callers = []
     self.prompt_method = prompt_method or env.simplecli_config.prompt_method
     self.path_delimeter = path_delimeter or env.simplecli_config.path_delimeter
     self._path_from_home = []
     self.path_from_home = path_from_home
     self._setup()
     self._init_submenus()
     self._old_completer = readline.get_completer()
     if self.env and not self.env.get_cached_menu_by_class(self.__class__):
         self.env.menu_cache.append(self)
Пример #5
0
def save(prev_h_len, histfile):
    """Save the history file on exit."""
    readline.set_history_length(1000)

    if hasattr(readline, 'append_history_file'):
        new_h_len = readline.get_history_length()
        # py 3.5+
        readline.append_history_file(new_h_len - prev_h_len, histfile)
    else:
        readline.write_history_file(histfile)
Пример #6
0
def save(prev_h_len, histfile):
    """Save the history file on exit."""
    readline.set_history_length(1000)

    if hasattr(readline, 'append_history_file'):
        new_h_len = readline.get_history_length()
        # py 3.5+
        readline.append_history_file(new_h_len - prev_h_len, histfile)
    else:
        readline.write_history_file(histfile)
def input_loop():
    if os.path.exists(HISTORY_FILENAME):
        readline.read_history_file(HISTORY_FILENAME)
    print 'Lunghezza max file storico:', readline.get_history_length()
    print 'Storico di partenza:', get_history_items()
    try:
        while True:
            line = raw_input('Prompt ("stop" per uscire): ')
            if line == 'stop':
                break
            if line:
                print 'Aggiunta di "%s" nello storico' % line
    finally:
        print 'Storico finale:', get_history_items()
        readline.write_history_file(HISTORY_FILENAME)
Пример #8
0
def input_loop():
    if os.path.exists(HISTORY_FILENAME):
        readline.read_history_file(HISTORY_FILENAME)
    print 'Max history file length:', readline.get_history_length()
    print 'Startup history:', get_history_items()
    try:
        while True:
            line = raw_input('Prompt ("stop" to quit): ')
            if line == 'stop':
                break
            if line:
                print 'Adding "%s" to the history' % line
    finally:
        print 'Final history:', get_history_items()
        readline.write_history_file(HISTORY_FILENAME)
Пример #9
0
def input_loop():
    if os.path.exists(HISTORY_FILENAME):
        readline.read_history_file(HISTORY_FILENAME)
    print 'Max history file length:', readline.get_history_length()
    print 'Start-up history:', get_history_items()
    try:
        while True:
            line = raw_input('Prompt ("stop" to quit):')
            if line == 'stop':
                break
            if line:
                print 'Adding "%s" to the history' % line
    finally:
        print 'Final history:', get_history_items()
        readline.write_history_file(HISTORY_FILENAME)
Пример #10
0
def input_function(prompt="", history=True):
    """Reads an input line, with readline disabled"""
    remove_history = rlmodule is not None and not history
    if remove_history:
        hcurlen = rlmodule.get_current_history_length()
        hmaxlen = rlmodule.get_history_length()
        rlmodule.set_history_length(hmaxlen + 1)
    try:
        answer = input(prompt)  # pylint: disable=bad-builtin
    finally:
        if remove_history:
            hlen = rlmodule.get_current_history_length()
            for i in range(hcurlen, hlen):
                rlmodule.remove_history_item(i)
            rlmodule.set_history_length(hmaxlen)
    return answer
Пример #11
0
    def start(self, args):
        histfile = os.path.join(os.path.expanduser("~"), ".{}_history".format(self.__name))
        try:
            readline.read_history_file(histfile)
            h_len = readline.get_history_length()
        except FileNotFoundError:
            open(histfile, 'wb').close()
            h_len = 0
        atexit.register(save_history, h_len, histfile)

        readline.parse_and_bind('tab: complete')
        readline.set_completer(self.complete)
        readline.set_completer_delims(self.__delims)
        try:
            self.input_loop()
        except (KeyboardInterrupt, EOFError):
            print()
            sys.exit(-1)
Пример #12
0
def registerreadline():
    import atexit
    import os
    import readline
    histfile = os.path.join(os.path.expanduser("~"), ".config", "python",
                            "history")

    try:
        readline.read_history_file(histfile)
        h_len = readline.get_history_length()
    except FileNotFoundError:
        open(histfile, 'wb').close()
        h_len = 0

    def save(prev_h_len, histfile):
        new_h_len = readline.get_history_length()
        readline.set_history_length(1000)
        readline.append_history_file(new_h_len - prev_h_len, histfile)

    atexit.register(save, h_len, histfile)
Пример #13
0
def setup_readline():
    if not readline:
        return False

    history = Env.get("RL_HISTORY", None)
    if history:
        history = os.path.expanduser(history)
        try:
            readline.read_history_file(history)
        except FileNotFoundError:
            open(history, "wb").close()
        hlen = readline.get_history_length()

        def save():
            newhlen = readline.get_current_history_length()
            l = newhlen - hlen
            if hasattr(readline, "append_history_file"):
                readline.append_history_file(l, history)
            else:
                readline.write_history_file(history)

        atexit.register(save)

    completion_cache = []

    def rl_complete(text, n):
        nonlocal completion_cache
        if n == 0:
            try:
                completion_cache = list(complete_all(text))
            except:
                traceback.print_exc()
            # print("\nCompletion of %s, cache: %s\n--> %s" % (text, completion_cache, text),end='')
        return completion_cache[n]

    readline.set_completer(rl_complete)
    readline.set_completer_delims("")
    readline.parse_and_bind("tab: complete")
Пример #14
0
def _closeHistory():
    # Ensure that our current history is written, and, if possible,
    # clear the history afterward.  Also, if possible, don't write
    # out any history content that might have come from a different
    # history.

    global _lastsize

    curlines = readline.get_history_length()
    currentsize = get_current_history_length()

    if currentsize is not None:
        lines_added = currentsize - _lastsize
        if lines_added<0:
            lines_added = currentsize
        if curlines==-1 or lines_added<curlines:
            readline.set_history_length(lines_added)

    readline.write_history_file(curhist)
    readline.set_history_length(curlines)

    clear_history()
    _lastsize = get_current_history_length()
Пример #15
0
def swap_history(filename=None, history_length=100):
    """Pause the current readline buffer and starts a new one"""
    if rlmodule is None:
        yield
        return
    else:
        saved_history_length = rlmodule.get_history_length()
        history = []
        for i in range(1, rlmodule.get_current_history_length() + 1):
            history.append(rlmodule.get_history_item(i))
        rlmodule.clear_history()
        try:
            if filename:
                if os.path.exists(filename):
                    rlmodule.read_history_file(filename)
                    rlmodule.set_history_length(history_length)
            yield
            if filename:
                rlmodule.write_history_file(filename)
        finally:
            rlmodule.clear_history()
            for line in history:
                rlmodule.add_history(line)
            rlmodule.set_history_length(saved_history_length)
Пример #16
0
def run(parser, log_fn):
    histfile = os.path.join(os.path.expanduser("~"), HISTORY_BASENAME)

    try:
        readline.read_history_file(histfile)
        h_len = readline.get_history_length()
    except FileNotFoundError:
        open(histfile, 'wb').close()
        h_len = 0

    def save(prev_h_len, histfile):
        new_h_len = readline.get_history_length()
        readline.set_history_length(1000)
        readline.append_history_file(new_h_len - prev_h_len, histfile)

    repl_session = ReplSession(parser, log_fn)
    while True:
        try:
            src = input("> ")
            if src == "":
                continue
        except KeyboardInterrupt:
            print("^C")
            continue
        except EOFError:
            print()
            break

        try:
            result = repl_session.run(src)
            print(result)
        except Exception as e:
            print("".join(traceback.format_exception(None, e,
                                                     e.__traceback__)),
                  file=sys.stdout,
                  flush=True)
Пример #17
0
def get_history_length():
    length = rl.get_history_length()
    if 0 > length:
        return "No limit"
    return length
Пример #18
0
def main():
    """
    Launch tests to check required modules and OS-specific dependencies.
    Exit with a relevant error code.
    """
    exit_code = 0
    import sys
    print('python %s' % (sys.version,))

    try:
        import zlib
    except:
        sys.stderr.write('"zlib" is missing.\n')
        exit_code = 131
    else:
        print('zlib %s' % (zlib.__version__,))

    try:
        from ssl import OPENSSL_VERSION
        import _hashlib
        exit_code = egg_check(_hashlib) | exit_code
    except:
        sys.stderr.write('standard "ssl" is missing.\n')
        exit_code = 132
    else:
        print('stdlib ssl - %s' % (OPENSSL_VERSION,))

    try:
        from cryptography.hazmat.backends.openssl.backend import backend
        import cryptography
        openssl_version = backend.openssl_version_text()
        if CHEVAH_OS in [ "win", "macos", "lnx", "rhel-8" ]:
            if CHEVAH_OS == "rhel-8":
                # On RHEL 8.3, OpenSSL got updated to 1.1.1g. To keep backward
                # compatibility, link to version 1.1.1c from CentOS 8.2.2004.
                expecting = u'OpenSSL 1.1.1c FIPS  28 May 2019'
            else:
                # Use latest OpenSSL version when building it from source.
                expecting = u'OpenSSL 1.1.1k  25 Mar 2021'
            if openssl_version != expecting:
                sys.stderr.write('Expecting %s, got %s.\n' % (
                    expecting, openssl_version))
                exit_code = 133
    except Exception as error:
        sys.stderr.write('"cryptography" failure. %s\n' % (error,))
        exit_code = 134
    else:
        print('cryptography %s - %s' % (
            cryptography.__version__, openssl_version))

    try:
        from ctypes import CDLL
        import ctypes
        CDLL
    except:
        sys.stderr.write('"ctypes - CDLL" is missing. %s\n')
        exit_code = 138
    else:
        print('ctypes %s' % (ctypes.__version__,))

    try:
        from ctypes.util import find_library
        find_library
    except:
        sys.stderr.write('"ctypes.utils - find_library" is missing.\n')
        exit_code = 139

    try:
        import multiprocessing
        multiprocessing.current_process()
    except:
        sys.stderr.write('"multiprocessing" is missing or broken.\n')
        exit_code = 140

    try:
        import subprocess32 as subprocess
        dir_output = subprocess.check_output('ls')
    except:
        sys.stderr.write('"subprocess32" is missing or broken.\n')
        exit_code = 145
    else:
        print('"subprocess32" module is present.')

    try:
        import bcrypt
        password = b"super secret password"
        # Hash the password with a randomly-generated salt.
        hashed = bcrypt.hashpw(password, bcrypt.gensalt())
        # Check that an unhashed password matches hashed one.
        if bcrypt.checkpw(password, hashed):
            print('bcrypt %s' % (bcrypt.__version__,))
        else:
            sys.stderr.write('"bcrypt" is present, but broken.\n')
            exit_code = 146
    except:
        sys.stderr.write('"bcrypt" is missing.\n')
        exit_code = 147

    try:
        import bz2
        test_string = b"just a random string to quickly test bz2"
        test_string_bzipped = bz2.compress(test_string)
        if bz2.decompress(test_string_bzipped) == test_string:
            print('"bz2" module is present.')
        else:
            sys.stderr.write('"bzip" is present, but broken.\n')
            exit_code = 148
    except:
        sys.stderr.write('"bz2" is missing.\n')
        exit_code = 149

    try:
        import setproctitle
        current_process_title = setproctitle.getproctitle()
    except:
        sys.stderr.write('"setproctitle" is missing or broken.\n')
        exit_code = 150
    else:
        print('setproctitle %s' % (setproctitle.__version__,))

    try:
        from sqlite3 import dbapi2 as sqlite
    except:
        sys.stderr.write('"sqlite3" is missing or broken.\n')
        exit_code = 153
    else:
        print('sqlite3 %s - sqlite %s' % (
                sqlite.version, sqlite.sqlite_version))

    try:
        import psutil
        cpu_percent = psutil.cpu_percent()
    except:
        sys.stderr.write('"psutil" is missing or broken.\n')
        exit_code = 160
    else:
        print('psutil %s' % (psutil.__version__,))

    try:
        import uuid
        uuid.uuid4()
    except:
        sys.stderr.write('"uuid" is missing or broken.\n')
        exit_code = 163
    else:
        print('"uuid" module is present.')

    if os.name == 'nt':
        # Windows specific modules.
        try:
            from ctypes import windll
            windll
        except:
            sys.stderr.write('"ctypes - windll" is missing.\n')
            exit_code = 152
        else:
            print('ctypes %s' % (ctypes.__version__,))

    else:
        # Linux / Unix stuff.
        try:
            import crypt
            crypt
        except:
            sys.stderr.write('"crypt" is missing.\n')
            exit_code = 155

        # Check for the git revision in Python's sys.version on Linux and Unix.
        try:
            git_rev_cmd = ['git', 'log', '-1', '--no-merges', '--format=%h']
            git_rev = subprocess.check_output(git_rev_cmd).strip().decode()
        except:
            sys.stderr.write("Couldn't get the git rev for the current tree.\n")
            exit_code = 157
        else:
            bin_ver = sys.version.split('(')[1].split(',')[0]
            if bin_ver != git_rev:
                sys.stderr.write("Python version doesn't match git revision!\n"
                                 "\tBin ver: {0}".format(bin_ver) + "\n"
                                 "\tGit rev: {0}".format(git_rev) + "\n")
                exit_code = 158

    if platform_system in [ 'linux', 'sunos' ]:
        try:
            import spwd
            spwd
        except:
            sys.stderr.write('"spwd" is missing, but it should be present.\n')
            exit_code = 161
        else:
            print('"spwd" module is present.')

    # The readline module is built using libedit only on selected platforms.
    if BUILD_LIBEDIT:
        try:
            import readline
            readline.get_history_length()
        except:
            sys.stderr.write('"readline" is missing or broken.\n')
            exit_code = 162
        else:
            print('"readline" module is present.')


    exit_code = test_dependencies() | exit_code


    sys.exit(exit_code)
Пример #19
0
from __future__ import print_function
import os
import sys

try:
    import readline  # import readline if not running on windows
    readline.get_history_length()  # redundant, prevents unused import warn
except:
    pass


class __Wrapper__(dict):
    """
    A Wrapper object is like a dictionary except `obj.foo` can be used
    in addition to `obj['foo']`.
        >>> o = Wrapper(a=1)
        >>> o.a
        1
        >>> o['a']
        1
        >>> o.a = 2
        >>> o['a']
        2
        >>> del o.a
        >>> o.a
        Traceback (most recent call last):
            ...
        AttributeError: 'a'
    """
    def override(self, other):
        def override(a, b):
Пример #20
0
    while prev != test:
        fname = os.path.join(test, '.python_history')
        if os.path.isfile(fname):
            return fname
        prev, test = test, os.path.abspath(os.path.join(test,
                                                        os.pardir))
    return default_histfile


histfile = get_histfile(os.getcwd())
# print('Using histfile {} (via {})'.format(histfile, __file__))
print('Using histfile {} (via pythonrc)'.format(histfile))

try:
    readline.read_history_file(histfile)
    h_len = readline.get_history_length()
except FileNotFoundError:
    open(histfile, 'wb').close()
    h_len = 0


def save(prev_h_len, histfile):
    """Save the history file on exit."""
    readline.set_history_length(1000)

    if hasattr(readline, 'append_history_file'):
        new_h_len = readline.get_history_length()
        # py 3.5+
        readline.append_history_file(new_h_len - prev_h_len, histfile)
    else:
        readline.write_history_file(histfile)
Пример #21
0
def main():

    # read system defaults:
    sys_configfile = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                  'sys.ini')
    sys_config = configparser.ConfigParser()
    if sys_config.read(sys_configfile) == []:
        print('ERROR: required system configuration file {} not found'.format(
            sys_configfile))
        sys.exit(1)
    defaults = dict(sys_config.items(configparser.DEFAULTSECT))

    # parse input arguments:
    parser = argparse.ArgumentParser()
    parser.add_argument('--configfile',
                        '-c',
                        type=str,
                        default=defaults['configfile'],
                        help='configuration file (default: {})'.format(
                            defaults['configfile']))
    parser.add_argument('--password',
                        '-p',
                        action='store_true',
                        help='prompt for database password')
    parser.add_argument('--inputfile', '-i', type=str, help='input file')
    parser.add_argument('--outputfile', '-o', type=str, help='output file')
    parser.add_argument('--echo', '-e', action='store_true', help='echo input')
    parser.add_argument('--verbose',
                        '-v',
                        action='store_true',
                        help='verbose output')
    parser.add_argument('--debug',
                        '-d',
                        action='store_true',
                        help='debug output')
    parser.add_argument(
        'source',
        type=str,
        nargs='?',
        default=configparser.DEFAULTSECT,
        help='data source, which can be the name of a configuration section'
        ' (default: {}), or otherwise the name of the database to connect to'
        ' (overriding the configuration default)'.format(
            configparser.DEFAULTSECT))
    args = parser.parse_args()

    # set up output replication + logging:
    if args.outputfile is not None:
        sys.stdout = utils.Tee(args.outputfile)
    logging.getLogger('ra').setLevel(logging.DEBUG if args.debug else\
                                     (logging.INFO if args.verbose else\
                                      logging.WARNING))
    logger_handler = logging.StreamHandler(sys.stdout)
    logger_handler.setFormatter(
        logging.Formatter('%(levelname)s: %(message)s'))
    logger.addHandler(logger_handler)

    # read user configuration file (starting with system defaults):
    config = configparser.ConfigParser(defaults)
    if config.read(os.path.expanduser(args.configfile)) == []:
        logger.warning('unable to read configuration file {}; resorting to system defaults'\
                       .format(os.path.expanduser(args.configfile)))

    # finalize configuration settings, using configuration file and command-line arguments:
    if args.source == configparser.DEFAULTSECT or config.has_section(
            args.source):
        configured = dict(config.items(args.source))
    else:  # args.source is not a section in the config file; treat it as a database name:
        configured = dict(config.items(configparser.DEFAULTSECT))
        configured['db.database'] = args.source
    if args.password:
        configured['db.password'] = getpass.getpass('Database password: '******'db.database' not in configured:
        logger.warning('no database specified')
    try:
        db = DB(configured)
    except Exception as e:
        logger.error('failed to connect to database: {}'.format(e))
        sys.exit(1)

    # initialize type system:
    try:
        check = ValTypeChecker(configured['default_functions'],
                               configured.get('functions', None))
    except TypeSysError as e:
        logger.error(e)
        sys.exit(1)

    # construct context (starting with empty view collection):
    context = Context(db, check, ViewCollection())

    # finally, let's start:
    if args.inputfile is None:  # interactive:
        if _readline_available:
            # set up command history file:
            historyfile = os.path.expanduser(configured['historyfile'])
            try:
                readline.read_history_file(historyfile)
                history_length = readline.get_history_length()
            except FileNotFoundError:
                open(historyfile, 'wb').close()
                history_length = 0

            def save_history(prev_history_length, historyfile):
                new_history_length = readline.get_current_history_length()
                readline.set_history_length(1000)
                readline.append_history_file(
                    new_history_length - prev_history_length, historyfile)

            atexit.register(save_history, history_length, historyfile)
            # set up command completion:
            readline.set_completer_delims(
                readline.get_completer_delims().replace('\\', ''))
            readline.parse_and_bind('tab: complete')
            readline.set_completer(RACompleter().complete)
            atexit.register(lambda: readline.set_completer(None))
        print('{name}: {description}\nVersion {version} by {author} <{author_email}>\n{url}'.
              format(**{key: configured['setup.' + key]\
                        for key in ('name', 'description',
                                    'version', 'author', 'author_email',
                                    'url')}))
        for s in statement_string_from_stdin(echo=args.echo):
            logger.info('statement received:')
            for line in utils.number_lines(s):
                logger.info(line)
            try:
                ast = one_statement_from_string(s)
                logger.info('statement parsed:')
                logger.info(str(ast))
                ast.validate(context)
                logger.info('statement validated:')
                for line in ast.info():
                    logger.info(line)
                ast.execute(context)
            except (ParsingError, ValidationError, ExecutionError) as e:
                logger.error(e)
    else:
        try:
            execute_from_file(args.inputfile, context, echo=args.echo)
        except (IOError, ParsingError, ValidationError, ExecutionError) as e:
            logger.error(e)
            sys.exit(1)
Пример #22
0
#!/usr/bin/env python3

from binascii import hexlify
import os
import paramiko
import socket
import sys
import readline
import threading

readline.get_history_length()
# throw this away because we import readline for prompt stuff
host_key = paramiko.RSAKey(filename='/etc/ssh/ssh_host_rsa_key')
priv_key = os.path.expanduser('~/.ssh/id_rsa')


class Server(paramiko.ServerInterface):
    def __init__(self):
        self.event = threading.Event()

    def check_channel_request(self, kind, chanid):
        if kind == 'session':
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED

    def check_auth_password(self, username, password):
        print(f'Auth attempt with password for user: {username}')
        if username == 'ctlfish' and password == 'ctlfish':
            return paramiko.AUTH_SUCCESSFUL

        return paramiko.AUTH_FAILED
Пример #23
0
def main():
    colorama.init(autoreset=True)
    readline.get_history_length()
    print(Fore.GREEN + Style.BRIGHT + "Tim the Enchanter v1.0")

    game = None
    namemap = {}

    while True:
        try:
            command_str = raw_input("%s> " % game)
            command_list = command_str.strip().split(" ")
            command = command_list[0]
            if command == "quit" or command == "q" or command == "exit":
                sys.exit(0)
            if command == "help":
                    help()
                    continue
            if game is None:
                if command == "newgame":
                    nplayers = raw_input("How many players? ")
                    game = DeceptionGame(
                        AvalonGame(int(nplayers)), DefaultModel)
                    namemap = {}
                elif command == "load":
                    if len(command_list) < 2:
                        print(Fore.RED + "Need an input file")
                        continue
                    inpath = os.path.expanduser(command_list[1])
                    with open(inpath, "r") as savefile:
                        observations = json.load(savefile)
                        metadata = observations[0]
                        data = observations[1:]

                        game = DeceptionGame(
                            AvalonGame(int(metadata["game_size"])),
                            DefaultModel)
                        namemap = metadata["player_names"]
                        game.load_save(data)
                else:
                    print(Fore.RED + "Need to create a game")
                continue
            elif command == "ls":
                for i, statement in enumerate(game.seen):
                    print "%d: %s" % (i, display_statement(statement, namemap))
                continue
            elif command == "vote":
                input = raw_input("Team? ").strip()
                team = [int(x) for x in input]
                votes = [int(x) for x in raw_input("Votes? ").strip()]
                round = int(raw_input("Round? ").strip())
                fail_req = int(raw_input("# Fails Required? ").strip())
                game.do_vote(team, votes, fail_req, round)
                game.trace = {}
                continue

            elif command == "mission":
                team = [int(x) for x in raw_input("Team? ").strip()]
                fails = int(raw_input("# of Fails? ").strip())
                must = int(raw_input("Spys must fail? ").strip()) == 1
                round = int(raw_input("Round? ").strip())
                game.do_mission(team, fails, must, round)
                game.trace = {}
                continue

            elif command == "lady" or command == "lol":
                p1 = int(raw_input("ID For Lady? ").strip())
                p2 = int(raw_input("ID For Target? ").strip())
                claim = int(raw_input("Claim? ").strip()) == 1
                round = int(raw_input("Round? ").strip()) == 1
                game.player_sees_player_and_claims(p1, p2, claim, round)
                game.trace = {}
                continue

            elif command == "side":
                p1 = int(raw_input("ID For Assertion? ").strip())
                claim = int(raw_input("Good? ").strip()) == 1
                game.add_known_alliance(p1, claim)
                game.trace = {}
                continue

            elif command == "switch":
                r = int(raw_input("Starting in round?").strip())
                game.switch_lancelots(r)
                game.trace = {}
                continue

            elif command == "eval":
                times = 200 / (game.n_players - 4) * 2
                if len(command_list) > 1:
                    times = int(command_list[1])
                game.eval(times, quick=True)
                repl_report(game.report(), namemap, game.n_good)
            elif command == "fulleval":
                times = 200 / (game.n_players - 4) * 2
                if len(command_list) > 1:
                    times = int(command_list[1])
                game.eval(times)
                repl_report(game.report(), namemap, game.n_good)
            elif command == "report":
                repl_report(game.report(), namemap, game.n_good)
            elif command == "save":
                if len(command_list) < 2:
                    print(Fore.RED + "Need an output file")
                    continue
                metadata = [{
                    "game_size": game.n_players,
                    "player_names": namemap
                }]
                outpath = os.path.expanduser(command_list[1])
                with open(outpath, "w") as savefile:
                    json.dump(metadata + game.seen, savefile, indent=2)
            elif command == "name":
                if len(command_list) < 3:
                    print(Fore.RED + "No args?")
                    continue
                namemap[int(command_list[1])] = command_list[2]
            elif command == "disb" or command == "disbelieve":
                if len(command_list) < 2:
                    print(Fore.RED + "No args?")
                    continue
                game.disbelieve(int(command_list[1]))
            else:
                print(Fore.RED + "Unknown command: %s" % command)
                continue
        except EOFError:
            print "Canceled"
            continue
        except Exception, e:
            print str(e)
            continue
Пример #24
0
def saveHistory(prevHistoryLen, filePath):
    logger.debug('Entering saveHistory')
    newHistoryLen = readline.get_history_length()
    logger.debug('{} {}'.format(newHistoryLen, prevHistoryLen))
    readline.set_history_length(1000)
    readline.append_history_file(newHistoryLen - prevHistoryLen, filePath)
Пример #25
0
 def get_max_length(self):
     return readline.get_history_length()
Пример #26
0
 def save(prev_h_len, histfile):
     new_h_len = readline.get_history_length()
     readline.set_history_length(1000)
     readline.append_history_file(new_h_len - prev_h_len, histfile)
Пример #27
0
def get_history_length():
    length = rl.get_history_length()
    if 0 > length:
        return "No limit"
    return length
Пример #28
0
def save_history(prev_h_len, histfile):
    new_h_len = readline.get_history_length()
    readline.set_history_length(1000)
Пример #29
0
 def save_history(self):
     """Writes the history to the HISTFILE as setup in __init__"""
     new_h_len = readline.get_history_length()
     readline.set_history_length(1000)
     readline.write_history_file(HISTFILE)
Пример #30
0
def write_history_file(hist_file):
    hist_end = readline.get_current_history_length()
    hist_start = max(0, hist_end - readline.get_history_length())
    with open(hist_file, 'w') as f:
        for i in range(hist_start, hist_end):
            f.write('%s\n' % readline.get_history_item(i + 1))
Пример #31
0
from __future__ import print_function
import os
import sys

try:
    import readline  # import readline if not running on windows
    readline.get_history_length()  # redundant, prevents unused import warn
except:
    pass


class __Wrapper__(dict):
    """
    A Wrapper object is like a dictionary except `obj.foo` can be used
    in addition to `obj['foo']`.
        >>> o = Wrapper(a=1)
        >>> o.a
        1
        >>> o['a']
        1
        >>> o.a = 2
        >>> o['a']
        2
        >>> del o.a
        >>> o.a
        Traceback (most recent call last):
            ...
        AttributeError: 'a'
    """

    def override(self, other):
def main():
    """
    Launch tests to check required modules and OS-specific dependencies.
    Exit with a relevant error code.
    """
    exit_code = 0

    try:
        import zlib
        zlib
    except:
        sys.stderr.write('"zlib" missing.\n')
        exit_code = 1

    try:
        import _hashlib
        _hashlib
    except:
        sys.stderr.write('standard "ssl" missing.\n')
        exit_code = 2

    try:
        from OpenSSL import SSL, crypto, rand
        SSL
        crypto
        rand
    except:
        sys.stderr.write('"OpenSSL" missing.\n')
        exit_code = 3

    try:
        import Crypto
        Crypto
    except:
        sys.stderr.write('"PyCrypto" missing.\n')
        exit_code = 4

    if os.name != 'nt':
        # Module only available on Linux / Unix
        try:
            import crypt
            crypt
        except:
            sys.stderr.write('"crypt" missing.\n')
            exit_code = 5

        try:
            import setproctitle
            setproctitle
        except:
            sys.stderr.write('"setproctitle" missing.\n')
            exit_code = 7

        try:
            from Crypto.PublicKey import _fastmath
            _fastmath
        except:
            sys.stderr.write('"Crypto.PublicKey._fastmath" missing. No GMP?\n')
            exit_code = 10

    try:
        import sqlite3
        sqlite3
    except:
        sys.stderr.write('"sqlite3" missing.\n')
        exit_code = 6

    try:
        from ctypes import CDLL
        CDLL
    except:
        sys.stderr.write('"ctypes - CDLL" missing.\n')
        exit_code = 8

    try:
        from ctypes.util import find_library
        find_library
    except:
        sys.stderr.write('"ctypes.utils - find_library" missing.\n')
        exit_code = 9

    # Windows specific modules.
    if os.name == 'nt':
        try:
            from ctypes import windll
            windll
        except:
            sys.stderr.write('"ctypes - windll" missing.\n')
            exit_code = 1
        try:
            import sqlite3
            sqlite3
        except:
            sys.stderr.write('"sqlite3" missing.\n')
            exit_code = 1

        # For now cryptography is only available on Winodws
        try:
            from cryptography.hazmat.backends.openssl.backend import backend
            openssl_version = backend.openssl_version_text()
        except:
            sys.stderr.write('"cryptography" failure.\n')
            exit_code = 3
        else:
            # Check OpenSSL version.
            assert openssl_version == u'OpenSSL 1.0.2d 9 Jul 2015'

    else:
        # Linux and Unix checks.
        try:
            import setproctitle
            setproctitle
        except:
            sys.stderr.write('"setproctitle" missing.\n')
            exit_code = 1

        try:
            import crypt
            crypt
        except:
            sys.stderr.write('"crypt" missing.\n')
            exit_code = 1

        try:
            from Crypto.PublicKey import _fastmath
            _fastmath
        except:
            sys.stderr.write('Crypto.PublicKey._fastmath missing. No GMP?\n')
            exit_code = 1

    if ( platform_system == 'linux' ) or ( platform_system == 'sunos' ):
        try:
            import spwd
            spwd
        except:
            sys.stderr.write('"spwd" missing.\n')
            exit_code = 1

    # We compile the readline module using libedit only on selected platforms.
    if test_for_readline:
        try:
            import readline
            readline.get_history_length()
        except:
            sys.stderr.write('"readline" missing.\n')
            exit_code = 13

        exit_code = test_dependencies() | exit_code

    sys.exit(exit_code)
Пример #33
0
def main():
    """
    Launch tests to check required modules and OS-specific dependencies.
    Exit with a relevant error code.
    """
    exit_code = 0
    import sys
    print 'python %s' % (sys.version,)

    try:
        import zlib
        print 'zlib %s' % (zlib.__version__,)
    except:
        sys.stderr.write('"zlib" missing.\n')
        exit_code = 1

    try:
        import _hashlib
        import ssl
        _hashlib
        print 'stdlib ssl %s' % (ssl.OPENSSL_VERSION,)
    except:
        sys.stderr.write('standard "ssl" missing.\n')
        exit_code = 2

    # cryptography module and latest pyOpenSSL are only available on
    # systems with cffi.
    if BUILD_CFFI:
        try:
            from cryptography.hazmat.backends.openssl.backend import backend
            import cryptography
            openssl_version = backend.openssl_version_text()
            print 'cryptography %s - OpenSSL %s' % (
                cryptography.__version__, openssl_version)

            if chevah_os == 'windows':
                # Check OpenSSL version on windows.
                expecting = u'OpenSSL 1.0.2g  1 Mar 2016'
                if openssl_version != expecting:
                    sys.stderr.write('Expecting %s got %s.\n' % (
                        expecting, openssl_version))
                    exit_code = 3
        except Exception as error:
            sys.stderr.write('"cryptography" failure. %s\n' % (error,))
            exit_code = 14

    try:
        from OpenSSL import SSL, crypto, rand, __version__ as pyopenssl_version
        crypto
        rand
        print 'pyopenssl %s - OpenSSL %s' % (
            pyopenssl_version,
            SSL.SSLeay_version(SSL.SSLEAY_VERSION),
            )
    except Exception as error:
        sys.stderr.write('"OpenSSL" missing. %s\n' % (error,))
        exit_code = 3

    try:
        import Crypto
        print 'PyCrypto %s' % (Crypto.__version__,)
    except:
        sys.stderr.write('"PyCrypto" missing.\n')
        exit_code = 4

    if os.name != 'nt':
        # Module only available on Linux / Unix
        try:
            import crypt
            crypt
        except:
            sys.stderr.write('"crypt" missing.\n')
            exit_code = 5

        try:
            import setproctitle
            setproctitle
        except:
            sys.stderr.write('"setproctitle" missing.\n')
            exit_code = 7

        try:
            from Crypto.PublicKey import _fastmath
            _fastmath
        except:
            sys.stderr.write('"Crypto.PublicKey._fastmath" missing. No GMP?\n')
            exit_code = 10

    try:
        from ctypes import CDLL
        import ctypes
        CDLL
        print 'ctypes %s' % (ctypes.__version__,)
    except:
        sys.stderr.write('"ctypes - CDLL" missing. %s\n')
        exit_code = 8

    try:
        from ctypes.util import find_library
        find_library
    except:
        sys.stderr.write('"ctypes.utils - find_library" missing.\n')
        exit_code = 9

    # Windows specific modules.
    if os.name == 'nt':
        try:
            from ctypes import windll
            windll
        except:
            sys.stderr.write('"ctypes - windll" missing.\n')
            exit_code = 1
        try:
            import sqlite3
            sqlite3
        except:
            sys.stderr.write('"sqlite3" missing.\n')
            exit_code = 6

    else:
        # Linux and Unix checks.
        try:
            import crypt
            crypt
        except:
            sys.stderr.write('"crypt" missing.\n')
            exit_code = 5

        try:
            import pysqlite2
            pysqlite2
        except:
            sys.stderr.write('"pysqlite2" missing.\n')
            exit_code = 6

        try:
            import setproctitle
            print 'setproctitle %s' % (setproctitle.__version__,)
        except:
            sys.stderr.write('"setproctitle" missing.\n')
            exit_code = 7

        try:
            from Crypto.PublicKey import _fastmath
            _fastmath
        except:
            sys.stderr.write('Crypto.PublicKey._fastmath missing. No GMP?\n')
            exit_code = 10


    if ( platform_system == 'linux' ) or ( platform_system == 'sunos' ):
        try:
            import spwd
            spwd
        except:
            sys.stderr.write('"spwd" missing.\n')
            exit_code = 1

    # We compile the readline module using libedit only on selected platforms.
    if test_for_readline:
        try:
            import readline
            readline.get_history_length()
        except:
            sys.stderr.write('"readline" missing.\n')
            exit_code = 13

        exit_code = test_dependencies() | exit_code

    sys.exit(exit_code)