Esempio n. 1
0
    def run(self, args):
        try:
            interfaces = self.client.remote('pupyps', 'interfaces')
            families = {
                int(k):v for k,v in self.client.remote_const(
                    'pupyps', 'families'
                ).iteritems()
            }

            data = interfaces()
            families = {
                int(x):y for x,y in families.iteritems()
            }

            objects = []

            for addr, addresses in data['addrs'].iteritems():

                if args.iface and addr not in args.iface:
                    continue

                color = ""
                if 'stats' in data and data['stats']:
                    if addr in data['stats'] and not data['stats'][addr].get('isup'):
                        color = 'darkgrey'
                    elif not any([families[x.get('family')] == 'INET' for x in addresses]):
                        color = 'grey'
                else:
                    color = 'white'

                record = {}
                record['K'] = Color(addr, color or 'cyan')

                first = True

                for address in addresses:
                    if first:
                        first = False
                    else:
                        record = {}
                        record['K'] = ''

                    record['F'] = Color(families[address.get('family')], color)
                    V = Color(address.get('address', '').split('%')[0], color or 'yellow')

                    if address.get('netmask') != 'None':
                        V = Line(V, Color(address.get('netmask'), color))
                        V.dm = '/'

                    if address.get('broadcast') != 'None':
                        V = Line(V, Color('brd '+address.get('broadcast'), color))

                    record['V'] = Line(V)

                    objects.append(record)

            self.log(Table(objects, ['K', 'F', 'V'], legend=False))

        except Exception, e:
            logging.exception(e)
Esempio n. 2
0
        def make_fields(item):
            items = []
            if args.time:
                date = datetime.utcfromtimestamp(item['date'])
                date_str = ''
                if date.date() == today:
                    date_str = date.strftime('%H:%M:%S')
                elif date.date().year == today.year:
                    date_str = date.strftime('%d/%m %H:%M:%S')
                else:
                    date_str = date.strftime('%Y/%d/%m %H:%M:%S')

                items.append(Color(date_str, 'lightgrey'))

            msg = item['msg']

            if not args.width:
                msg = ' '.join([x.strip() for x in msg.split('\n')])

            if item.get('type') in ('CRITICAL', 'EMERGENCY', 'ALERT', 'ERROR'):
                msg = Color(msg, 'lightred')
            elif item.get('type') == 'WARNING':
                msg = Color(msg, 'lightyellow')
            elif item.get('type') == 'DEBUG':
                msg = Color(msg, 'grey')

            items.append(msg)
            return Line(*items)
Esempio n. 3
0
def do(server, handler, config, modargs):
    pj = None
    args = modargs.arguments
    clients_filter = modargs.filter or handler.default_filter

    try:
        module = server.get_module(
            server.get_module_name_from_category(modargs.module))

    except PupyModuleUsageError, e:
        prog, message, usage = e.args
        handler.display(Line(Error(prog+':'), Color(message, 'lightred')))
        handler.display(usage)
Esempio n. 4
0
            if all(not x['resource'] for x in info['creds']):
                del columns[columns.index('resource')]

            cids = set(x['cid'] for x in info['creds'])
            if len(cids) == 1:
                del columns[columns.index('cid')]
                caption += ' (cid={})'.format(list(cids)[0])

            if credtype in ('plaintext', 'hash') or all(
                len(x['secret']) <= 64 for x in info['creds']):

                handler.display(TruncateToTerm(
                    Table(info['creds'], columns,
                          caption=Color(caption, 'yellow'))))
            else:
                caption = Line('{', Color(caption, 'yellow'), '}')
                handler.display(caption)
                parts = []
                for cred in info['creds']:
                    line = []
                    for column in columns:
                        if column == 'secret' or not cred[column]:
                            continue

                        line.append(Color(column+':', 'yellow'))
                        line.append(Color(cred[column], 'lightyellow'))

                    line.append(NewLine())
                    line.append(cred['secret'])
                    line.append(NewLine())
                    parts.append(Line(*line))
Esempio n. 5
0
File: help.py Progetto: txtaly/pupy
def do(server, handler, config, args):

    tables = []

    if args.module:
        if handler.commands.has(args.module):
            command = handler.commands.get(args.module)
            tables.append(
                Line(Color('Command:', 'yellow'),
                     Color(args.module + ':', 'green'), command.usage
                     or 'No description'))
            if command.parser.add_help:
                tables.append(command.parser.format_help())
            else:
                tables.append(command.parser.parse_args(['--help']))

        for module in server.iter_modules():
            if module.get_name().lower() == args.module.lower():
                if module.__doc__:
                    doc = module.__doc__.strip()
                else:
                    doc = ''

                tables.append(
                    Line(Color('Module:', 'yellow'),
                         Color(args.module + ':', 'green'),
                         doc.title().split('\n')[0]))

                if command.parser.add_help:
                    tables.append(command.parser.format_help())
                else:
                    tables.append(command.parser.parse_args(['--help']))

                clients = server.get_clients(handler.default_filter)
                if clients:
                    ctable = []
                    for client in clients:
                        compatible = module.is_compatible_with(client)
                        ctable.append({
                            'OK':
                            Color('Y' if compatible else 'N',
                                  'green' if compatible else 'grey'),
                            'CLIENT':
                            Color(str(client),
                                  'green' if compatible else 'grey')
                        })

                    tables.append(
                        Table(ctable, ['OK', 'CLIENT'],
                              Color('Compatibility', 'yellow'), False))

        for command, alias in config.items("aliases"):
            if command == args.module:
                tables.append(
                    Line(Color('Alias:', 'yellow'),
                         Color(args.module + ':', 'green'), alias))

    else:
        commands = []
        for command, description in handler.commands.list():
            commands.append({'COMMAND': command, 'DESCRIPTION': description})

        tables.append(
            Table(commands, ['COMMAND', 'DESCRIPTION'],
                  Color('COMMANDS', 'yellow')))

        if args.modules:
            modules = sorted(list(server.iter_modules()),
                             key=(lambda x: x.category))
            table = []

            for mod in modules:
                compatible = all(
                    mod.is_compatible_with(client)
                    for client in server.get_clients(handler.default_filter))

                compatible_some = any(
                    mod.is_compatible_with(client)
                    for client in server.get_clients(handler.default_filter))

                if mod.__doc__:
                    doc = mod.__doc__.strip()
                else:
                    doc = ''

                category = mod.category
                name = mod.get_name()
                brief = doc.title().split('\n')[0]

                if compatible:
                    pass
                elif compatible_some:
                    category = Color(category, 'grey')
                    name = Color(name, 'grey')
                    brief = Color(brief, 'grey')
                else:
                    category = Color(category, 'darkgrey')
                    name = Color(name, 'darkgrey')
                    brief = Color(brief, 'darkgrey')

                table.append({
                    'CATEGORY': category,
                    'NAME': name,
                    'HELP': brief
                })

            tables.append(
                TruncateToTerm(
                    Table(table, ['CATEGORY', 'NAME', 'HELP'],
                          Color('MODULES', 'yellow'))))

        else:
            aliased = []
            for module, description in server.get_aliased_modules():
                aliased.append({'MODULE': module, 'DESCRIPTION': description})

            if aliased:
                tables.append(
                    Table(aliased, ['MODULE', 'DESCRIPTION'],
                          Color('ALIASED MODULES', 'yellow')))

        aliases = []
        for command, alias in config.items("aliases"):
            aliases.append({'ALIAS': command, 'COMMAND': alias})

        if aliases:
            tables.append(
                Table(aliases, ['ALIAS', 'COMMAND'],
                      Color('ALIASES', 'yellow')))

        if not args.modules:
            tables.append(
                Line('Use', Color('help -M', 'green'),
                     'command to show all available modules'))

    handler.display(MultiPart(tables))
Esempio n. 6
0
class FStat(PupyModule):
    '''Show a bit more info about file path. ACLs/Caps/Owner for now'''

    dependencies = {
        'all': ['pupyutils.basic_cmds', 'fsutils', 'fsutils_ext'],
        'windows': ['junctions', 'ntfs_streams', 'pupwinutils.security'],
        'linux': ['xattr', 'posix1e', 'prctl', '_prctl']
    }

    @classmethod
    def init_argparse(cls):
        cls.arg_parser = PupyArgumentParser(prog='stat',
                                            description=cls.__doc__)
        cls.arg_parser.add_argument(
            '-v',
            '--verbose',
            action='store_true',
            default=False,
            help='Print more information (certificates for example)')
        cls.arg_parser.add_argument('path',
                                    type=str,
                                    nargs=REMAINDER,
                                    help='path of a specific file',
                                    completer=remote_path_completer)

    def run(self, args):
        getfilesec = self.client.remote('fsutils_ext', 'getfilesec')

        path = ' '.join(args.path)

        try:
            sec = getfilesec(path)
        except Exception, e:
            self.error(' '.join(x for x in e.args
                                if type(x) in (str, unicode)))
            return

        ctime, atime, mtime, size, owner, group, header, mode, extra = sec

        owner_id, owner_name, owner_domain = owner
        group_id, group_name, group_domain = group

        default = {
            'Created':
            file_timestamp(ctime, time=True),
            'Accessed':
            file_timestamp(atime, time=True),
            'Modified':
            file_timestamp(mtime, time=True),
            'Size':
            '{} ({})'.format(size_human_readable(size), size),
            'Owner':
            '{}{} ({})'.format(owner_domain + '\\' if owner_domain else '',
                               owner_name, owner_id),
            'Group':
            '{}{} ({})'.format(group_domain + '\\' if group_domain else '',
                               group_name, group_id),
            'Mode':
            mode,
        }

        infos = []

        infos.append(
            Table([{
                'Property': p,
                'Value': default[p]
            } for p in ('Created', 'Accessed', 'Modified', 'Size', 'Owner',
                        'Group', 'Mode')], ['Property', 'Value'],
                  legend=False))

        oneliners = []

        certificates = None

        for extra, values in extra.iteritems():
            if extra == 'Certificates':
                certificates = [
                    load_cert_string(cert, FORMAT_DER).as_text()
                    for cert in values
                ]
            elif isinstance(values, dict):
                records = [{
                    'KEY':
                    k.decode('utf-8'),
                    'VALUE':
                    v.decode('utf-8') if isinstance(v, str) else str(v)
                } for k, v in values.iteritems()]

                infos.append(Table(records, ['KEY', 'VALUE'], caption=extra))
            elif isinstance(values, (list, tuple)):
                if all(
                        isinstance(value, (list, tuple)) and len(value) == 2
                        for value in values):
                    infos.append(
                        List('{}: {}'.format(key, value)
                             for key, value in values))
                else:
                    infos.append(List(values, caption=extra))
            elif isinstance(values, int):
                oneliners.append('{}: {}'.format(extra, values))
            elif '\n' in values:
                infos.append(Line(extra + ':', values))
            else:
                oneliners.append(extra + ': ' + values)

        if args.verbose:
            magic = ''
            if header:
                with Magic() as libmagic:
                    magic = libmagic.id_buffer(header)

            if magic:
                oneliners.append('Magic: {}'.format(magic))

            if certificates:
                infos.extend(certificates)

        if oneliners:
            infos.append(List(oneliners, caption='Other'))

        self.log(MultiPart(infos))
Esempio n. 7
0
class FStat(PupyModule):
    '''Show a bit more info about file path. ACLs/Caps/Owner for now'''

    dependencies = {
        'all': ['pupyutils', 'fsutils', 'fsutils_ext'],
        'windows': ['junctions', 'ntfs_streams'],
        'linux': ['xattr', 'posix1e', 'prctl', '_prctl']
    }

    @classmethod
    def init_argparse(cls):
        cls.arg_parser = PupyArgumentParser(prog='stat',
                                            description=cls.__doc__)
        cls.arg_parser.add_argument('path',
                                    type=str,
                                    nargs=REMAINDER,
                                    help='path of a specific file',
                                    completer=remote_path_completer)

    def run(self, args):
        getfilesec = self.client.remote('fsutils_ext', 'getfilesec')

        path = ' '.join(args.path)

        try:
            sec = getfilesec(path)
        except Exception, e:
            self.error(' '.join(x for x in e.args
                                if type(x) in (str, unicode)))
            return

        ctime, atime, mtime, size, owner, group, header, mode, extra = sec

        owner_id, owner_name, owner_domain = owner
        group_id, group_name, group_domain = group

        magic = ''
        if header:
            with Magic() as libmagic:
                magic = libmagic.id_buffer(header)

        default = {
            'Created':
            file_timestamp(ctime, time=True),
            'Accessed':
            file_timestamp(atime, time=True),
            'Modified':
            file_timestamp(mtime, time=True),
            'Size':
            '{} ({})'.format(size_human_readable(size), size),
            'Owner':
            '{}{} ({})'.format(owner_domain + '\\' if owner_domain else '',
                               owner_name, owner_id),
            'Group':
            '{}{} ({})'.format(group_domain + '\\' if group_domain else '',
                               group_name, group_id),
            'Mode':
            mode,
        }

        infos = []

        infos.append(
            Table([{
                'Property': p,
                'Value': default[p]
            } for p in ('Created', 'Accessed', 'Modified', 'Size', 'Owner',
                        'Group', 'Mode')], ['Property', 'Value'],
                  legend=False))

        if magic:
            infos.append('Magic: {}'.format(magic))

        for extra, values in extra.iteritems():
            if type(values) in (list, tuple):
                infos.append(List(values, caption=extra))
            else:
                infos.append(Line(extra + ':', values))

        self.log(MultiPart(infos))