Exemplo n.º 1
0
def main():
    logger.debug("Hello.")
    query = arguments['QUERY']
    # file_location = "~/.nbssh-cache"
    # filename = os.path.expanduser("%s" % file_location)

    # if arguments['--refresh']:
    #     print("Refreshing from Netbox API...")
    #     all_devices = get_all_devices(config.get('main', 'API_ADDRESS'),
    #                                config.get('main', 'API_TOKEN'))
    #     save_devices_to_file(all_devices, filename)
    #     sys.exit()

    # all_devices = read_devices_from_file(filename)

    # i = 1
    # displayed_device_list_length = 20
    # devices = []
    # for device in all_devices:
    #     if i < displayed_device_list_length:
    #         if query in  device.name:
    #             devices.append(device)
    #             i += 1
    # if i >= displayed_device_list_length:
    #     print("Displaying the first %s results only. You might want to try a more specific search." % displayed_device_list_length)

    check_for_update()

    term = Terminal()

    term_height = get_terminal_size()[1]

    try:
        config.get('main', 'NO_OF_RESULTS')
        try:

            if 1 <= int(config.get('main', 'NO_OF_RESULTS')) <= 100:
                displayed_device_list_length = int(
                    config.get('main', 'NO_OF_RESULTS'))
            else:
                print(
                    "NO_OF_RESULTS must be an positive integer between 1 and 100. Using terminal height instead."
                )
                displayed_device_list_length = term_height - 5

        except Exception as e:
            print(
                "%s\nNO_OF_RESULTS must be an positive integer between 1 and 100. Using terminal height instead."
                % e)
            displayed_device_list_length = term_height - 6

    except Exception as e:
        displayed_device_list_length = term_height - 4

    devices = get_devices_by_query(config.get('main', 'API_ADDRESS'),
                                   config.get('main', 'API_TOKEN'), query,
                                   displayed_device_list_length)

    if len(devices) >= displayed_device_list_length:
        print(
            "Displaying the first %s results only. You might want to try a more specific search."
            % displayed_device_list_length)
    # if there's a single result, just SSH directly without displaying the menu
    elif len(devices) == 1:
        print(
            term.bright_magenta("Single result. Going directly to %s..." %
                                devices[0].name))
        os.system("ssh root@%s" % devices[0].primary_ip_address)
        sys.exit()
    elif len(devices) == 0:
        print("No results.")
        sys.exit()

    pick_options = []
    desired_length = 0
    for device in devices:
        if len(device.name) > desired_length:
            desired_length = len(device.name)
    for device in devices:
        #pick_options.append("%s  →  %s" % (make_string_this_length(device.name, 30), device.primary_ip_address))
        pick_options.append(
            make_string_this_length(device.name, desired_length))

    jon_theme = {
        "List": {
            "selection_color": "black_on_cyan",
            "selection_cursor": " ",
            "unselected_color": "normal"
        },
        "Question": {
            "mark_color": "white",
            "brackets_color": "bright_magenta",
            "default_color": "white_on_magenta",
        }
    }

    questions = [
        inquirer.List(
            'selection',
            message="Which device?",
            choices=pick_options,
        ),
    ]
    answers = inquirer.prompt(
        questions, theme=inquirer.themes.load_theme_from_dict(jon_theme))
    if answers is None:
        exit()
    selection = answers['selection']

    for device in devices:
        # selection is the column width, so removing whitespace
        if device.name == selection.replace(" ", ""):
            logger.info("SSHing into %s..." % device.primary_ip_address)
            os.system("ssh root@%s" % device.primary_ip_address)