Exemple #1
0
def cmd_quit(*args):
    """
    :quit                 Exit interactive mode and quit the program.
    """
    terminal.error(text='Stopping any running jobs ...')
    connections.conns.kill_all()
    terminal.error(text='Disconnecting from all remote hosts ...')
    connections.conns.disconnect_all()
    sys.exit(os.EX_OK)
Exemple #2
0
def cmd_quit(*args):
    """
    :quit                 Exit interactive mode and quit the program.
    """
    terminal.error(text = 'Stopping any running jobs ...')
    connections.conns.kill_all()
    terminal.error(text = 'Disconnecting from all remote hosts ...')
    connections.conns.disconnect_all()
    sys.exit(os.EX_OK)
Exemple #3
0
def run(command = ''):
    """
    Run individual commands by passing them to the Connections object. Failures
    should be collected and dealt with here by checking the return codes of
    completed commands.
    """

    if not len(connections.conns.hosts):
        terminal.error(text = 'No hosts specified.')

    connections.conns.run_command_all(command)

    return os.EX_OK
Exemple #4
0
def run(command=''):
    """
    Run individual commands by passing them to the Connections object. Failures
    should be collected and dealt with here by checking the return codes of
    completed commands.
    """

    if not len(connections.conns.hosts):
        terminal.error(text='No hosts specified.')

    connections.conns.run_command_all(command)

    return os.EX_OK
Exemple #5
0
def cmd_show(*args):
    """
    :show <host>          Show the output of the last command for <host>.
    :<host>               A shortcut for `:show <host>`
    """
    if len(args) == 1:
        host = args[0]
        host = connections.conns._gethost(host)
        if not host:
            terminal.error(text = "No such host")
            return os.EX_OK
        history = connections.conns.get_history(host)
        if not history:
            terminal.error(text = "No output available for %s" % host)
        else:
            last_history = history[-1]
            command = last_history.get('command')
            output = last_history.get('output')
            exitcode = last_history.get('exitcode')

            if exitcode is None:
                terminal.error(text = "Command still pending")
                return os.EX_OK
            else:
                # This will block if the process isn't complete
                outlines = output.readlines()
                # Reset the output for later re-reading. If we've already
                # replaced the buffer with a StringIO we can just seek.
                try:
                    output.seek(0)
                except:
                    output = StringIO.StringIO()
                    output.writelines(outlines)
                    output.seek(0)
                last_history['output'] = output
            outstr = ''
            outstr += terminal.error(
                text = terminal.tocolor(command + '\n', 'bold'),
                silent = True
            )
            for line in outlines:
                outstr += terminal.error(
                    '[%s] ' % host,
                    line.strip('\n'),
                    1,
                    silent = True
                )
            outstr += terminal.error(
                text = 'Exit code: %s' % exitcode,
                silent = True
            )
            outstr = outstr.replace('\r', '\n')
            pydoc.pipepager(outstr, config.get('pager'))
    else:
        return os.EX_USAGE
    return os.EX_OK
Exemple #6
0
def cmd_list(*args):
    """
    :list                 List all hosts in the current hosts list.
    """
    output = []
    for idx, item in enumerate(connections.conns.items()):
        host, hostinfo = item
        output.append(('[%s]' % idx, host, hostinfo.get('connected'),
                       hostinfo.get('exitcode')))
    if not len(output):
        terminal.error(text='No hosts.')
        return os.EX_OK
    headers = ('', 'Hostname', 'Connected', 'Last exit')
    print '\n', terminal.format_columns(headers, output), '\n'
    return os.EX_OK
Exemple #7
0
def cmd_show(*args):
    """
    :show <host>          Show the output of the last command for <host>.
    :<host>               A shortcut for `:show <host>`
    """
    if len(args) == 1:
        host = args[0]
        host = connections.conns._gethost(host)
        if not host:
            terminal.error(text="No such host")
            return os.EX_OK
        history = connections.conns.get_history(host)
        if not history:
            terminal.error(text="No output available for %s" % host)
        else:
            last_history = history[-1]
            command = last_history.get('command')
            output = last_history.get('output')
            exitcode = last_history.get('exitcode')

            if exitcode is None:
                terminal.error(text="Command still pending")
                return os.EX_OK
            else:
                # This will block if the process isn't complete
                outlines = output.readlines()
                # Reset the output for later re-reading. If we've already
                # replaced the buffer with a StringIO we can just seek.
                try:
                    output.seek(0)
                except:
                    output = StringIO.StringIO()
                    output.writelines(outlines)
                    output.seek(0)
                last_history['output'] = output
            outstr = ''
            outstr += terminal.error(text=terminal.tocolor(
                command + '\n', 'bold'),
                                     silent=True)
            for line in outlines:
                outstr += terminal.error('[%s] ' % host,
                                         line.strip('\n'),
                                         1,
                                         silent=True)
            outstr += terminal.error(text='Exit code: %s' % exitcode,
                                     silent=True)
            outstr = outstr.replace('\r', '\n')
            pydoc.pipepager(outstr, config.get('pager'))
    else:
        return os.EX_USAGE
    return os.EX_OK
Exemple #8
0
def cmd_list(*args):
    """
    :list                 List all hosts in the current hosts list.
    """
    output = []
    for idx, item in enumerate(connections.conns.items()):
        host, hostinfo = item
        output.append((
            '[%s]' % idx,
            host,
            hostinfo.get('connected'),
            hostinfo.get('exitcode')
        ))
    if not len(output):
        terminal.error(text = 'No hosts.')
        return os.EX_OK
    headers = ('', 'Hostname', 'Connected', 'Last exit')
    print '\n', terminal.format_columns(headers, output), '\n'
    return os.EX_OK
Exemple #9
0
def main(command = None):
    """
    Main routine. Optionally accepts a <command> string as the first command to
    execute after connecting to the hosts.
    """

    connection_info = lambda x: error(text = x)
    connection_error = lambda x: error(text = x, lvl = 2)
    conns = connections.Connections(config.get('hosts'),
        info_output = connection_info,
        error_output = connection_error)
    connections.set(conns)

    if config.get('interactive') or not command:
        exitcode = dispatcher.run_interactive(command)
    else:
        exitcode = dispatcher.run(command)

    return exitcode
Exemple #10
0
def main(command=None):
    """
    Main routine. Optionally accepts a <command> string as the first command to
    execute after connecting to the hosts.
    """

    connection_info = lambda x: error(text=x)
    connection_error = lambda x: error(text=x, lvl=2)
    conns = connections.Connections(config.get('hosts'),
                                    info_output=connection_info,
                                    error_output=connection_error)
    connections.set(conns)

    if config.get('interactive') or not command:
        exitcode = dispatcher.run_interactive(command)
    else:
        exitcode = dispatcher.run(command)

    return exitcode
Exemple #11
0
def run_interactive(command = ''):
    """
    Interactive command loop for the dyssh prompt.
    """
    global last_traceback

    if command:
        run(command)

    while True:
        try:
            prompt = config.get('prompt', '').strip() + ' '
            prompt %= {
                'hostname': config.get('local_hostname'),
                'local_wd': os.getcwd(),
                'remote_wd': config.get('working_directory'),
            }
            command = raw_input(prompt)
            if command.startswith(':'):
                c, _, args = command[1:].partition(' ')
                possibles = []
                for fnc in globals().keys():
                    if fnc.startswith('cmd_'+c):
                        f = globals()[fnc]
                        possibles.append((f, args))
                if len(possibles) > 1:
                    terminal.error(text = 'Command is ambiguous', lvl = 1)
                    cmd_help(*[
                        p[0].__name__[4:] for p in possibles
                    ])
                elif len(possibles) == 1:
                    f, args = possibles[0]
                    args = filter(None, args.split(' '))
                    r = f(*args)
                    if r == os.EX_USAGE:
                        cmd_help(f.__name__[4:])
                    elif r != os.EX_OK:
                        terminal.error(text = "Error issuing command: %s" % r,
                            lvl = 1)
                else:
                    host = connections.conns._gethost(c[1:])
                    if host:
                        cmd_show(host)
                    else:
                        terminal.error(text = 'Invalid command.', lvl = 1)
            elif command:
                run(command)
        except Exception, e:
            last_traceback = traceback.format_exc()
            terminal.error(text = 'Error attempting to execute command: %s' % e,
                lvl = 2)
            print "Enter `:traceback` to print the last error traceback."
Exemple #12
0
def cmd_history(*args):
    """
    :history <host>       Show the command history for <host>.
    """
    if len(args) == 1:
        history = connections.conns.get_history(args[0])
        if not history:
            terminal.error(text="No history available for %s" % args[0])
        else:
            headers = ('\n#', 'Command', 'Exit code')
            output = []
            for i, h in enumerate(history):
                output.append((
                    '%s' % i,
                    h.get('command'),
                    h.get('exitcode'),
                ))
            print terminal.format_columns(headers, output), '\n'
    else:
        return os.EX_USAGE
    return os.EX_OK
Exemple #13
0
def cmd_history(*args):
    """
    :history <host>       Show the command history for <host>.
    """
    if len(args) == 1:
        history = connections.conns.get_history(args[0])
        if not history:
            terminal.error(text = "No history available for %s" % args[0])
        else:
            headers = ('\n#', 'Command', 'Exit code')
            output = []
            for i, h in enumerate(history):
                output.append((
                    '%s' % i,
                    h.get('command'),
                    h.get('exitcode'),
                ))
            print terminal.format_columns(headers, output), '\n'
    else:
        return os.EX_USAGE
    return os.EX_OK
Exemple #14
0
def run_interactive(command=''):
    """
    Interactive command loop for the dyssh prompt.
    """
    global last_traceback

    if command:
        run(command)

    while True:
        try:
            prompt = config.get('prompt', '').strip() + ' '
            prompt %= {
                'hostname': config.get('local_hostname'),
                'local_wd': os.getcwd(),
                'remote_wd': config.get('working_directory'),
            }
            command = raw_input(prompt)
            if command.startswith(':'):
                c, _, args = command[1:].partition(' ')
                possibles = []
                for fnc in globals().keys():
                    if fnc.startswith('cmd_' + c):
                        f = globals()[fnc]
                        possibles.append((f, args))
                if len(possibles) > 1:
                    terminal.error(text='Command is ambiguous', lvl=1)
                    cmd_help(*[p[0].__name__[4:] for p in possibles])
                elif len(possibles) == 1:
                    f, args = possibles[0]
                    args = filter(None, args.split(' '))
                    r = f(*args)
                    if r == os.EX_USAGE:
                        cmd_help(f.__name__[4:])
                    elif r != os.EX_OK:
                        terminal.error(text="Error issuing command: %s" % r,
                                       lvl=1)
                else:
                    host = connections.conns._gethost(c[1:])
                    if host:
                        cmd_show(host)
                    else:
                        terminal.error(text='Invalid command.', lvl=1)
            elif command:
                run(command)
        except Exception, e:
            last_traceback = traceback.format_exc()
            terminal.error(text='Error attempting to execute command: %s' % e,
                           lvl=2)
            print "Enter `:traceback` to print the last error traceback."
Exemple #15
0
def cmd_timeout(*args):
    """
    :timeout              Show the current value for the 'job_timeout' config
                          option.
    :timeout <seconds>    Set the current value for the 'job_timeout' config
                          option. Seconds to wait for jobs to complete before
                          returning to the interactive prompt. Jobs that time
                          out will continue to operate in the background, and
                          can be checked with either :status or by using :join.
    """
    
    if len(args) == 1 and args[0].isdigit():
        t = float(args[0])
        if t < 0:
            t = 0
        config.config['job_timeout'] = t
        terminal.error(text = "Timeout set to %s seconds" % t)
    elif len(args) == 0:
        print config.get('job_timeout')
    else:
        return os.EX_USAGE

    return os.EX_OK
Exemple #16
0
def cmd_timeout(*args):
    """
    :timeout              Show the current value for the 'job_timeout' config
                          option.
    :timeout <seconds>    Set the current value for the 'job_timeout' config
                          option. Seconds to wait for jobs to complete before
                          returning to the interactive prompt. Jobs that time
                          out will continue to operate in the background, and
                          can be checked with either :status or by using :join.
    """

    if len(args) == 1 and args[0].isdigit():
        t = float(args[0])
        if t < 0:
            t = 0
        config.config['job_timeout'] = t
        terminal.error(text="Timeout set to %s seconds" % t)
    elif len(args) == 0:
        print config.get('job_timeout')
    else:
        return os.EX_USAGE

    return os.EX_OK
Exemple #17
0
        for args, kwargs in ARGS.items():
            if len(args) == 1 and not args[0].startswith('-'):
                positional.append(args[0])
            elif args[0].startswith('-'):
                optparser.add_option(*args, **kwargs)
        options, args = optparser.parse_args()
        # Add these to the options object so that config.update() checks them
        for k, v in zip(positional, args):
            if not hasattr(options, k):
                setattr(options, k, v)
        argv = options

    try:
        config.update(argv)
    except ValueError, e:
        error('', ' '.join(e.args))
        error('', __doc__)
        sys.exit(os.EX_USAGE)

    try:
        import atexit
        import readline
        histfile = os.path.join(config.get('histfile'))
        try:
            readline.read_history_file(histfile)
        except IOError:
            pass
        atexit.register(readline.write_history_file, histfile)
    except ImportError:
        pass
Exemple #18
0
        for args, kwargs in ARGS.items():
            if len(args) == 1 and not args[0].startswith('-'):
                positional.append(args[0])
            elif args[0].startswith('-'):
                optparser.add_option(*args, **kwargs)
        options, args = optparser.parse_args()
        # Add these to the options object so that config.update() checks them
        for k, v in zip(positional, args):
            if not hasattr(options, k):
                setattr(options, k, v)
        argv = options

    try:
        config.update(argv)
    except ValueError, e:
        error('',' '.join(e.args))
        error('',__doc__)
        sys.exit(os.EX_USAGE)
        
    try:
        import atexit
        import readline
        histfile = os.path.join(config.get('histfile'))
        try:
            readline.read_history_file(histfile)
        except IOError:
            pass
        atexit.register(readline.write_history_file, histfile)
    except ImportError:
        pass