Example #1
0
def default_shell():
    try:
        if utils.get_os() == "Darwin":
            shell = subprocess.check_output('dscl . -read /Users/' +
                                            getpass.getuser() + ' UserShell',
                                            shell=True)
            def_shell = shlex.split(shell.decode('utf-8'))[1]

        elif utils.get_os() == "Linux":
            file = open('/etc/passwd')
            for line in file:
                if re.search(getpass.getuser(), line):
                    def_shell = line.split(':')[-1].replace('\n', '')

        elif not utils.get_os():
            def_shell = default_shell_error_message
        else:
            def_shell = "NOT IMPLEMENTED!"
    except:
        logger.debug(default_shell_error_message)
        def_shell = default_shell_error_message

    if def_shell != utils.get_alpsh_installation():
        if config.get_setting(
                'GENERAL', 'show_default_shell_warning', isbool=True) is True:
            print(
                config.get_setting('TEXT', 'warning') +
                '=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\nCURRENT DEFAULT SHELL IS : '
                + def_shell + '\n=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-' +
                COLORS.CLEAR)
Example #2
0
def history(args):
    print("ARGS : " + str(args))
    # If no arguments typed
    if len(args) == 0:
        print("HOWTO")
    elif str(args[0]) == "list":
        # List history in order
        print("List history")
        with open(CONFIG_PATH + 'alpsh_history.json', 'r') as history_list:
            data = json.load(history_list)
            count = 0
            table = []
            for item in range(len(data["history"])):
                table.append({
                    'Index':
                    str(count),
                    'Command':
                    data['history'][count]['command'],
                    "Timestamp":
                    data['history'][count]['timestamp'],
                    'Success':
                    data['history'][count]['success'],
                    'Ran from directory':
                    data['history'][count]['dir_when_ran']
                })
                count += 1
            tables = make_table(table, tablefmt='md')
            print(tables)
            print()
    elif str(args[0] == "clear"):
        print(
            config.get_setting('text', 'danger') +
            "-=-=-=-=-=-=-=-WARNING-=-=-=-=-=-=-=\n" + COLORS.CLEAR +
            "You are about to remove your command history.\n" +
            "This is generally not necessary and is not recommended to do without reason.\n"
            + config.get_setting('text', 'danger') +
            "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" + COLORS.CLEAR)
        response = input("Are you sure you want to continue? [y/N] ")
        if response == "y":
            # Remove history
            history_listener.create(reset=True)
            print(
                config.get_setting('text', 'warning') + "History cleared!\n" +
                COLORS.CLEAR)
        else:
            # Don't remove history
            print(
                config.get_setting('text', 'warning') + "Aborted!\n" +
                COLORS.CLEAR)

    return SHELL_STATUS_RUN
Example #3
0
def execute(cmd_tokens):
    try:
        cmd_name = cmd_tokens[0]
        cmd_args = cmd_tokens[1:]

        if any('~' in word for word in cmd_args):
            logger.debug('Expanding tilde')
            cmd_tokens[1:] = [args.replace('~', os.path.expanduser('~')) for args in cmd_tokens[1:]]

        if '|' in cmd_tokens:
            pipeline = split_pipes(cmd_tokens)
            procs = [subprocess.Popen(pipeline[0], stdout=subprocess.PIPE)]
            time.sleep(0.1)
            for index, cmd in enumerate(pipeline):
                if index == 0:
                    continue
                elif index < len(pipeline) - 1:
                    procs.append(subprocess.Popen(cmd, stdin=procs[index-1].stdout, stdout=subprocess.PIPE))
                else:
                    procs.append(subprocess.Popen(cmd, stdin=procs[index-1].stdout))
                time.sleep(0.1)

            procs[0].communicate()
            procs[-1].wait()

        elif cmd_name in built_in_cmds:
            history_listener.write(" ".join(cmd_tokens))
            return built_in_cmds[cmd_name](cmd_args)
        elif cmd_name in alias_in_cmds:
            try:
                subprocess.call(tokenize(alias_in_cmds[cmd_name]))
            except FileNotFoundError:
                logger.info(str(tokenize(alias_in_cmds[cmd_name])) + " : Command not found!")
                print(str(tokenize(alias_in_cmds[cmd_name])) + " : Command not found!")
        elif config.get_setting('general', 'open_if_file', isbool=True) is True and os.path.isfile(cmd_name):
            if platform.system() == "Darwin":
                subprocess.call('open ' + cmd_name, shell=True)
        elif os.path.isdir(cmd_name):
            os.chdir(cmd_name)
            prompt.handle_prompt()
        else:

            # Execute command
            try:
                subprocess.call(cmd_tokens)
                history_listener.write(" ".join(cmd_tokens))
            except subprocess.CalledProcessError as error:
                logger.error(error.output)
            except OSError as error:
                if "[Errno 2] No such file or directory:" in str(error):
                    logger.info(str(cmd_tokens[0]) + ": Command not found!")
                    print(str(cmd_tokens[0]) + ": Command not found!")
                    history_listener.write(" ".join(cmd_tokens), False)
                else:
                    logger.error(str(error))
    except IndexError as error:
        logger.debug("IndexError occurred : " + str(error))

    # Return status indicating to wait for next command in shell_loop
    return SHELL_STATUS_RUN
Example #4
0
def init():
    register_command("cd", cd)
    register_command("exit", exit)
    register_command("history", history)
    register_command('reload', reload)
    if config.get_setting('general', 'override_coreutils') == "True":
        register_command("ls", ls)
    register_alias()
Example #5
0
def handle_prompt():
    global altered_prompt
    altered_prompt = config.get_setting('GENERAL', 'prompt')
    if "@host" in config.get_setting('GENERAL', 'prompt'):
        altered_prompt = altered_prompt.replace('@host', socket.gethostname())
    if "@user" in config.get_setting('GENERAL', 'prompt'):
        altered_prompt = altered_prompt.replace('@user', getpass.getuser())
    if "@dir" in config.get_setting('GENERAL', 'prompt'):
        altered_prompt = altered_prompt.replace('@dir',
                                                os.path.split(os.getcwd())[1])
    if "@fulldir" in config.get_setting('GENERAL', 'prompt'):
        altered_prompt = altered_prompt.replace('@fulldir', os.getcwd())
    if "@shortdir" in config.get_setting('general', 'prompt'):
        altered_prompt = altered_prompt.replace(
            '@shortdir',
            str(
                Path(*Path(os.getcwd()).parts[-config.get_setting(
                    'prompt', 'short_directory_length', fallback=4):])))