Пример #1
0
def configLogging(build):
    global log
    logging.captureWarnings(True)
    term = os.environ.get('TERM')
    if term and term.startswith('screen.'):
        term = term[7:]
    record_format = '%(name)s: %(message)s'
    try:
        clifmt = utils.ColoredFormatter(
            blessings.Terminal(term, force_styling=build.force_color),
            record_format)
    except curses.error:
        try:
            # try falling back to basic term type
            clifmt = utils.ColoredFormatter(
                blessings.Terminal('linux', force_styling=build.force_color),
                record_format)
        except curses.error:
            # fall back to uncolored formatter
            clifmt = logging.Formatter(record_format)
    root_logger = logging.getLogger()
    clihandler = logging.StreamHandler(sys.stdout)
    clihandler.setFormatter(clifmt)
    if isinstance(build.log_level, str):
        build.log_level = build.log_level.upper()
    root_logger.setLevel(build.log_level)
    log.setLevel(build.log_level)
    root_logger.addHandler(clihandler)
    requests_logger = logging.getLogger("requests")
    requests_logger.setLevel(logging.WARN)
    urllib_logger = logging.getLogger("urllib3")
    urllib_logger.setLevel(logging.CRITICAL)
Пример #2
0
    def web_output(self):

        web_title = '| {0:28} | {1:16} | {2:10} | {3:14} | {4:44} | {5:1}'.format('User-Agent', 'FQDN', 'VLAN', 'Port', 'Platform', 'Power')

        print self.color('-' * blessings.Terminal().width, char='')
        print self.color(gateways_title, char='')
        print self.color('-' * blessings.Terminal().width, char='')
Пример #3
0
    def username_output(self):

        if len(self.usernames) > 0:
            usernames_title = '| {0:16} | {1:10} | {2:16} | {3:1}'.format(
                'Username', 'Host', 'Domain', 'Win2k Format')

            print '-' * blessings.Terminal().width
            print self.color(usernames_title, char='')
            print '-' * blessings.Terminal().width

            for userpair in self.usernames:

                for username in userpair.keys():

                    hostname = userpair[username]
                    domain = None
                    win2k = None

                    if hostname in self.hosts.keys():
                        domain = self.hosts[hostname]['domain']
                        win2k = '{}\{}'.format(domain, username)

                    username_output = '| {0:16} | {1:10} | {2:16} | {3:1}'.format(
                        username, hostname, domain, win2k)

                    print self.color(username_output, char='')

        print '-' * blessings.Terminal().width
        print ''
Пример #4
0
    def gateways_output(self):

        gateways_title = '| {0:28} | {1:16} | {2:10} | {3:14} | {4:44} | {5:1}'.format('Device', 'MgtIPv4', 'VLAN', 'Port', 'Platform', 'Power')

        print self.color('-' * blessings.Terminal().width, char='')
        print self.color(gateways_title, char='')
        print self.color('-' * blessings.Terminal().width, char='')

        for device in sorted(list(set(self.gateways.keys()))):
            gatekeys = self.gateways[device].keys()

            if self.gateways[device] != None:

                protocol = self.gateways[device]['protocol']
                mgt_ipv4 = self.gateways[device]['ipv4']

                if protocol.upper() == 'CDP':

                    vlan = self.gateways[device]['cdp_vlan']
                    port_id = self.gateways[device]['cdp_port_id']
                    platform = self.gateways[device]['cdp_platform_name'].split(',')[0]
                    protocol_version = self.gateways[device]['cdp_version']
                    power = self.gateways[device]['power']
                    software_version= self.gateways[device]['cdp_software_version']
                    mgt_802 = ''
                    address = ''

                    if power != None:
                        power = '{} ({}, {})'.format(power['cdp_power_mgt_id'], power['cdp_power_available'], power['cdp_power_max'])

                    cdp_output = '| {0:28} | {1:16} | {2:10} | {3:14} | {4:44} | {5:1}'.format(device, mgt_ipv4, vlan, port_id, platform, power)

                    print self.color(cdp_output, char='')

                if protocol.upper() == 'LLDP':

                    protocol_version = ''
                    power = None

                    port_id = self.gateways[device]['lldp_port_id']
                    mgt_802 = self.gateways[device]['mgt_802']
                    vlan = self.gateways[device]['lldp_vlan']
                    address = self.gateways[device]['address']
                    platform = self.gateways[device]['sysinfo']

                    if ',' in platform:
                        platform = platform.split(',')[0]

                    lldp_output = '| {0:28} | {1:16} | {2:10} | {3:14} | {4:44} | {5:1}'.format(device, mgt_ipv4, vlan, port_id, platform, power)

                    print self.color(lldp_output, char='')

                    if address != None:
                        print ''
                        print self.color('LLDP TR-41 Address: {}'.format(address), char=' . ')

        print '-' * blessings.Terminal().width
        print ''
Пример #5
0
    def routers_output(self):

        routers_title = '{0:18} | {1:18} | {2:16} | {3:20} | {4:1}'.format(
            'Router', 'Server ID', 'Domain', 'Client ID', 'Name Servers')

        print self.color('-' * blessings.Terminal().width, char='')
        print self.color(routers_title, char='| ')
        print self.color('-' * blessings.Terminal().width, char='')

        for router in sorted(list(set(self.routers.keys()))):

            routerkeys = self.routers[router].keys()

            if 'router' in routerkeys:
                router = self.routers[router]['router']

            else:
                router = 'Unknown'

            if 'server_id' in routerkeys:
                server_id = self.routers[router]['server_id']

            else:
                server_id = 'Unknown'

            if 'name_server' in routerkeys:
                name_servers = self.routers[router]['name_server']

            else:
                name_servers = 'Unknown'

            if 'client_id' in routerkeys:
                client_id = self.routers[router]['client_id']

            else:
                client_id = 'Unknown'

            if 'domain' in routerkeys:
                domain = self.routers[router]['domain']

            else:
                domain = 'Unknown'

            if type(name_servers) == 'list':
                name_servers = str(','.join(name_servers)).strip()

            else:
                name_servers = name_servers

            router_output = '{0:18} | {1:18} | {2:16} | {3:20} | {4:1}'.format(
                router, server_id, domain, client_id, name_servers)

            print self.color(router_output, char='| ')

        print '-' * blessings.Terminal().width
        print ''
Пример #6
0
    def ipv4_hostname_output(self):

        ipv4_host_title = '| {0:16} | {1:16} | {2:18} | {3:10} | {4:18} | {5:1}'.format('Host', 'IPv4', 'MAC', 'Domain', 'Server Type', 'Windows OS (Server Fingerprint)')

        print '-' * blessings.Terminal().width
        print self.color(ipv4_host_title, char='')
        print '-' * blessings.Terminal().width

        server_type = ''

        for host in sorted(self.hosts):

            ipv4 = self.hosts[host]['ipv4']
            mac = self.hosts[host]['mac']

            if host != None and '*' not in host:

                if 'fqdn' in self.hosts[host].keys():
                    print self.hosts[host]['fqdn']

                mac = self.hosts[host]['mac']
                os = self.hosts[host]['os']
                nt_version = None
                os_version = os
                serverlist = {'domain_controller': 'DC', 'backup_controller': 'Backup DC', 'sql_server': 'SQL', 'print': 'Printer'}
                host_comment = None

                if 'comment' in self.hosts[host].keys():
                    host_comment = self.hosts[host]['comment']

                if os != None and not os.startswith('Microsoft'):
                    nt_version = os.split('(')[1].split(')')[0].strip()
                    os_version = os.split('(')[0].strip()

                if host_comment != None and list(host_comment)[0] != '\x00':
                    os_version += ' ({})'.format(host_comment.capitalize())

                domain = self.hosts[host]['domain']
                #notes = self.hosts[host]['notes']

                if 'server_keys' in self.hosts[host].keys():

                    servers = []
                    server_types = self.hosts[host]['server_keys']

                    for server in server_types:

                        if server_types[server] == '1' and server in serverlist.keys():
                            servers.append(serverlist[server])

                    ipv4_host_output = '| {0:16} | {1:16} | {2:18} | {3:10} | {4:18} | {5:1}'.format(host.upper(), ipv4, mac, domain, ','.join(servers).strip(), os_version)

                    print self.color(ipv4_host_output, char='')

        print '-' * blessings.Terminal().width
        print ''
Пример #7
0
    def protos_output(self):

        protos_title = '| Protocols'

        print '-' * blessings.Terminal().width
        print self.color(protos_title, char='')
        print '-' * blessings.Terminal().width

        for proto in self.protocols:

            print self.color('{}'.format(proto), char='| ')

        print self.color('-' * blessings.Terminal().width, char='')
        print ''
Пример #8
0
    def dns_output(self):

        dns_title = '| DNS Name Servers'

        print '-' * blessings.Terminal().width
        print self.color(dns_title, char='')
        print '-' * blessings.Terminal().width

        for d in sort_ips(self.dns[0].split(',')):

            print self.color(d.strip(), char='| ')

        print '-' * blessings.Terminal().width
        print ''
Пример #9
0
    def fingerprints_output(self):

        fingerprints_title = '| {0:30}'.format('Fingerprints')

        print '-' * blessings.Terminal().width
        print self.color(fingerprints_title, char='')
        print '-' * blessings.Terminal().width

        for fingerprint in sorted(list(set(self.fprints))):
            fprint_output = '{0:30}'.format(fingerprint)

            print self.color(fprint_output, char='| ')

        print '-' * blessings.Terminal().width
        print ''
Пример #10
0
    def __init__(self, opt, prefix, toconsole=True):

        self.t = blessings.Terminal()
        self.logger = None

        logfilename = prefix + '_' + self.timestamp() + '.log'
        self.configure_logfile(opt, logfilename, toconsole)
Пример #11
0
    def initialize(self):
        self.term = blessings.Terminal()
        self.colors = [self.term.green, self.term.red, self.term.blue,
                       self.term.cyan, self.term.yellow]

        assert self.term.is_a_tty, \
            'Attempting to run in a non-tty environment.'
        n_charts = len(self.initial_stats)

        # every chart can take up 1 / n_charts of the terminal space
        # the terminal space is equal to the height - 2 because there can
        # be one empty line at the top and one at the bottom
        height = (self.term.height - 2) // n_charts
        resolution = (height, self.term.width)

        for i, stat in enumerate(self.initial_stats):
            monitor = TerminalMonitor(stat,
                                      fps=self.fps,
                                      color=self.colors[i],
                                      app=self,
                                      resolution=resolution)
            self.monitors.append(monitor)

        print(self.term.enter_fullscreen())
        print(self.term.hide_cursor())

        try:
            while True:
                print(self.term.move(0, 1))
                self.update()
                time.sleep(1 / self.fps)
        except KeyboardInterrupt:
            print(self.term.exit_fullscreen())
            # explicitly delete monitors to stop threads run by stats
            del self.monitors
Пример #12
0
 def __init__(self, fp=None, term=None):
     if fp is None:
         fp = sys.stdout
     self.fp = fp
     if term is None:
         term = blessings.Terminal()
     self.term = term
Пример #13
0
def main(args):
    term = blessings.Terminal()

    table_generator = OrderedDict([
        ("ID", lambda x: x.id),
        ("name", lambda x: x.name),
        ("host", lambda x: x.hostname),
        ("active", lambda x: x.active),
        ("tasks", lambda x: x.task_count),
        ("cpu", lambda x: x.cpu_allocated),
        ("mem", lambda x: x.mem_allocated),
        ("disk", lambda x: x.disk_allocated),
    ])

    tb = prettytable.PrettyTable([x.upper() for x in table_generator.keys()],
                                 border=False,
                                 max_table_width=term.width,
                                 hrules=prettytable.NONE,
                                 vrules=prettytable.NONE,
                                 left_padding_width=0,
                                 right_padding_width=1)

    def format_row(framework):
        return [fn(framework) for fn in table_generator.values()]

    for framework in MASTER.frameworks(active_only=not args.inactive):
        tb.add_row(format_row(framework))

    if tb.rowcount == 0:
        cli.header('You have no frameworks')
    else:
        print(tb)
Пример #14
0
 def __init__(self, message, totalCount=None, disp=True):
     if not disp or sys.platform == 'win32':
         self.update = self.empty
         self.curlUpdate = self.empty
         self.progress = self.empty
         self.progressBy = self.empty
         self.outputProgress = self.empty
         self.done = self.empty
         self.main = ''
         self.finished = 0
         return
     # windows system does not support ncurse
     import blessings
     self.term = blessings.Terminal(stream=sys.stderr)
     self.main = message
     self.main_start_time = time.time()
     self.message = self.main
     # get terminal width
     self.term_width = shutil.get_terminal_size((80, 20)).columns
     #
     # total count
     self.count = 0
     # total initial count
     self.init_count = self.count
     #
     self.finished = 0
     self.uuid = uuid.uuid4().hex
     with fasteners.InterProcessLock('/tmp/sos_progress_'):
         with open('/tmp/sos_progress', 'a') as prog_index:
             prog_index.write('{}\n'.format(self.uuid))
     self.reset('', totalCount)
    def __init__(self):
        super(InteractiveDisplay, self).__init__()
        self._blessings = blessings.Terminal()
        self._lines = []

        self._clear_screen()
        self._print_logo()
Пример #16
0
 def __init__(self, name):
     '''
     Constructor
     '''
     self.name = name
     if not IS_WINDOWS:
         self.term = blessings.Terminal()
Пример #17
0
    def __init__(self, options):
        self.output = []
        self.options = options
        with open(os.path.expanduser(options['--config'])) as conf_file:
            self.config = yaml.safe_load(conf_file)
        for opt in options['--set-conf']:
            key, sep, value = opt.partition('=')
            self.config[key] = yaml.safe_load(value)
        self.term = blessings.Terminal(
            force_styling=COLOR_OPT_MAP[options['--color']])
        self.verbosity = self.options['--verbose']
        if self.verbosity:
            self.eprint('Options:')
            self.eprint(pprint.pformat(self.options))
            self.eprint('Config:')
            self.eprint(pprint.pformat(self.config))
        if self.options['--no-trac']:
            self.trac = None
        else:
            url = self.config['trac-xmlrpc-url']
            self.trac = xmlrpc.client.ServerProxy(url)

        self.color_arg = self.options['--color']
        if self.color_arg == 'auto':
            if self.term.is_a_tty:
                self.color_arg = 'always'
            else:
                self.color_arg = 'never'
Пример #18
0
def main():
    parsed = parse_arguments()
    if parsed.debug:
        logging.basicConfig(level=logging.DEBUG)

    cache = get_cache_info()

    def match(item, terms):
        for i in terms:
            if i in item['name']:
                logger.debug("{} found in {}".format(i, item['name']))
                return True
            elif item['description'] is not None and i in item['description']:
                logger.debug("{} found in {}".format(i, item['description']))
                return True

    matches = [x for x in cache if match(x, parsed.search_terms)]

    # Print it
    t = blessings.Terminal()

    for i in sorted(matches, key=lambda x: x['name']):
        line = "{name} : {description}".format(**i)
        for st in parsed.search_terms:
            line = line.replace(st, t.bold + st + t.normal)
        print(line)
Пример #19
0
def setup_terminal(args, config):
    force_color = args.get('--color', False)
    if args.get('--no-color', False):
        if force_color:
            raise ValueError("cannot combine --color and --no-color")
        force_color = None
    return blessings.Terminal(force_styling=force_color)
Пример #20
0
    def domains_output(self):

        domains_title = '| Domains'

        print '-' * blessings.Terminal().width
        print self.color(domains_title, char='')
        print '-' * blessings.Terminal().width

        if self.domains != []:

            for domain in self.domains:
                if domain != None:
                    print self.color('{}'.format(domain), char='| ')

        print self.color('-' * blessings.Terminal().width, char='')
        print ''
Пример #21
0
    def __init__(self,
                 start_time=None,
                 write_interval=False,
                 write_times=True,
                 terminal=None,
                 disable_colors=False):

        if disable_colors:
            terminal = None
        elif terminal is None and blessings is not None:
            terminal = blessings.Terminal()

        if start_time is None:
            start_time = time.time()
        start_time = int(start_time * 1000)
        self.start_time = start_time
        self.write_interval = write_interval
        self.write_times = write_times
        self.status_buffer = {}
        self.has_unexpected = {}
        self.last_time = None
        self.terminal = terminal
        self.verbose = False
        self._known_pids = set()

        self.summary_values = {
            "tests": 0,
            "subtests": 0,
            "expected": 0,
            "unexpected": defaultdict(int),
            "skipped": 0
        }
        self.summary_unexpected = []
Пример #22
0
def main(first_filename, second_filename):
    term = blessings.Terminal()

    with open(first_filename) as f:
        first_data = json.load(f)

    with open(second_filename) as f:
        second_data = json.load(f)

    status_changes, naming_status_changes = compare_files(
        first_data, second_data)

    # Print changes.
    print(term.green('Update Fedora data'))
    print()

    for change, packages in sorted(status_changes.items()):
        print(term.blue('**{}** → **{}** ({})'.format(*change, len(packages))))
        for package in packages:
            print('-', package)
        print()

    print(term.green('## Naming status changes'))
    print()

    for change, packages in sorted(naming_status_changes.items()):
        print(term.blue('**{}** → **{}** ({})'.format(*change, len(packages))))
        for package in packages:
            print('-', package)
        print()
Пример #23
0
    def base_start(self):
        """Handle starting tests."""

        self._terminal = blessings.Terminal(stream=self._stream,
                                            force_styling=self._force_color)

        self.start()
Пример #24
0
 def __post_init__(self):
     # Create an initial random
     if not self.matrix:
         self.matrix = np.random.randint(len(self.colors),
                                         size=(self.x, self.y))
     if not self.term:
         self.term = blessings.Terminal()
Пример #25
0
def main(args):
    term = blessings.Terminal()

    # There's a security bug in Mavericks wrt. urllib2:
    #     http://bugs.python.org/issue20585
    if platform.system() == "Darwin":
        os.environ["no_proxy"] = "*"

    task = MASTER.task(args.task)

    cmd = [
        "ssh", "-t", task.slave["hostname"],
        "cd {0} && bash".format(task.directory)
    ]

    if args.file is not None:
        cmd = cmd[:-1] + ["-i", args.file] + [cmd[-1]]

    if args.user is not None:
        cmd = cmd[:-1] + ["-l", args.user] + [cmd[-1]]

    if task.directory == "":
        print(term.red + "warning: the task no longer exists on the " +
              "target slave. Will not enter sandbox" + term.white + "\n\n")
        cmd = cmd[:-1]

    log.fn(os.execvp, "ssh", cmd)
Пример #26
0
def matrix_from_termcolors():
    term = blessings.Terminal()
    d = int(np.ceil(np.sqrt(term.number_of_colors)))
    colors = np.arange(term.number_of_colors)
    colors.resize((d, d))
    # __import__('IPython').embed()
    return colors
Пример #27
0
 def __init__(self, fp=None, term=None, force_styling=False):
     if fp is None:
         fp = sys.stdout
     self.fp = fp
     if term is None:
         term = blessings.Terminal(force_styling=force_styling)
     self.term = term
Пример #28
0
    def __init__(self, in_file=None, out_file=None, kind=None, bg=None,
                 encoding='UTF-8'):

        in_file = hw.sys_stdin if in_file is None else in_file
        out_file = hw.sys_stdout if out_file is None else out_file

        self._in_fd = in_file.fileno()
        self._out_fd = out_file.fileno()
        self._ttyname = self._common_tty_name(self._in_fd, self._out_fd)

        self._bt = blessings.Terminal(kind=kind, stream=out_file)
        self._encoding = encoding

        self._width = None
        self._height = None
        self._update_geometry()

        self._window = window.Window(self, 0, 0, 1.0, 1.0, bg=bg)
        self._window.title = 'ppytty'

        self.input_buffer = collections.deque()

        # Speed up sub-attribute access with these attributes.
        self._bt_clear = self._bt.clear
        self._bt_save = self._bt.save
        self._bt_restore = self._bt.restore
        self._bt_move = self._bt.move
        self._window_clear = self._window.clear
        self._window_feed = self._window.feed
        self._window_render = self._window.render
        self._os_write_out_fd = functools.partial(hw.os_write_all, self._out_fd)
Пример #29
0
 def __init__(self, keyfile):
     self.term = blessings.Terminal()
     print(self.term.enter_fullscreen)
     self.sklib = SekureLib()
     self.sklib.testSelf()
     self.skkm = SKKM(self.term)
     self.connected = False
     self.socket = None
     self.runvar = True
     self.keyfile = keyfile
     self.initMainMenu()
     self.initConnectedMenu()
     print(self.term.clear)
     try:
         print("Trying to load database from file...")
         self.skkm.loadKeyDatabase(self.keyfile)
         print("DB loaded successfully.")
         time.sleep(1)
         print(self.term.clear)
     except Exception as e:
         print("Failed to load database, generating new DB -", e)
         self.skkm.generateDatabase()
         self.skkm.saveKeyDatabase()
     self.utility = Utility(self.socket, self.sklib, self.skkm)
     self.run()
     print(self.term.exit_fullscreen)
Пример #30
0
    def __init__(self,
                 start_time=None,
                 write_interval=False,
                 write_times=True,
                 terminal=None,
                 disable_colors=False,
                 summary_on_shutdown=False,
                 **kwargs):
        super(MachFormatter, self).__init__(**kwargs)

        if disable_colors:
            terminal = None
        elif terminal is None and blessings is not None:
            terminal = blessings.Terminal()

        if start_time is None:
            start_time = time.time()
        start_time = int(start_time * 1000)
        self.start_time = start_time
        self.write_interval = write_interval
        self.write_times = write_times
        self.status_buffer = {}
        self.has_unexpected = {}
        self.last_time = None
        self.terminal = terminal
        self.verbose = False
        self._known_pids = set()

        self.summary = SummaryHandler()
        self.summary_on_shutdown = summary_on_shutdown