def gen_bootstrap(p: Panos, lifetime: str):
    """
    Gen a new Bootstrap key
    """
    params = {
        "type": "op",
        "cmd": "<request><bootstrap><vm-auth-key><generate><lifetime>{}</lifetime></generate></vm-auth-key></bootstrap></request>".format(lifetime)
    }
    r = p.send(params)
    if not p.check_resp(r):
        raise PanoramaError("Failed to generate Bootstrap key {}".format(r.content))

    regex_result = re.search("VM auth key\s+(\d+)\s+", r.content.decode())
    key = regex_result.group(1)

    return key
def show_bootstrap(p: Panos):
    """
    Get the most recently generated bootstrap key
    """
    params = {
        "type": "op",
        "cmd": "<request><bootstrap><vm-auth-key><show></show></vm-auth-key></bootstrap></request>"
    }
    r = p.send(params)
    if not p.check_resp(r):
        raise PanoramaError("Failed to show Bootstrap key.")

    root = ElementTree.fromstring(r.content.decode())
    keys = root.findall("./result/bootstrap-vm-auth-keys/entry/vm-auth-key")
    if len(keys) == 0:
        return

    return keys[0].text
예제 #3
0
def push_from_gcloud(args):
    """
    Pull snippets from Gcloud instead of Git repos.
    :param args: parsed args from argparse
    """
    if args.repopath:
        api_url = args.repopath
    else:
        api_url = DEFAULT_API_URL

    gc = Gcloud(api_url)

    if len(args.snippetnames) == 0:
        print(
            "{}New: browse the available objects via SkilletCloud: https://skilletcloud-prod.appspot.com/skillets/{}{}"
            .format(Fore.GREEN, args.repository, Style.RESET_ALL))
        snippets = gc.List(args.repository)
        names = set()
        for s in snippets:
            names.add(s['name'])

        for n in names:
            print(n)

        sys.exit(0)

    # Address must be passed, then lookup keystore if it exists.
    addr = env_or_prompt(
        "address",
        args,
        prompt_long="address or address:port of PANOS Device to configure: ")
    apikey = KEY_DB.lookup(addr)
    if not apikey:
        user = env_or_prompt("username", args)
        pw = env_or_prompt("password", args, secret=True)
        fw = Panos(addr,
                   user=user,
                   pw=pw,
                   debug=args.debug,
                   verify=args.validate)
        KEY_DB.add_key(addr, fw.key)
    else:
        fw = Panos(addr, apikey=apikey, debug=args.debug, verify=args.validate)

    t = fw.get_type()
    v = fw.get_version()

    context = create_context(args.config)
    snippets = gc.Query(args.repository, t, args.snippetstack,
                        args.snippetnames, v, context)

    if len(snippets) == 0:
        print("{}Snippets {} not found for device type {}.{}".format(
            Fore.RED, ",".join(args.snippetnames), t, Style.RESET_ALL))
    for snippet in snippets:
        print("Doing {} at {}...".format(snippet.name, snippet.rendered_xpath),
              end="")
        r = set_at_path(fw, snippet.rendered_xpath, snippet.rendered_xmlstr)
        check_resp(r)
def connect(query: dict):
    connected = False
    failures = 0
    # Retry for 10 minutes
    max_failures = 20
    while not connected:
        if failures >= max_failures:
            raise PanoramaError("Failed to connect to panorama at {}".format(query["panorama_ip"]))
        try:
            p = Panos(query["panorama_ip"], user=query["username"], pw=query["password"])
            connected = True
        except:
            failures = failures +1
            time.sleep(30)
            pass

    return p
예제 #5
0
def push_skillets(args):
    """
    Based on user configuration (cmdline args), pushes given snippets to a PANOS device.
    :param args: parsed args from argparse
    """
    if args.repotype == "git":
        github = Github()
        repo_list = github.index()
        repo_url = args.repopath
        repo_table = BeautifulTable()
        repo_table.set_style(BeautifulTable.STYLE_NONE)
        repo_table.column_headers = ['Repository Name', 'Description']
        repo_table.column_alignments[
            'Repository Name'] = BeautifulTable.ALIGN_LEFT
        repo_table.column_alignments['Description'] = BeautifulTable.ALIGN_LEFT
        repo_table.left_padding_widths['Description'] = 1
        repo_table.header_separator_char = '-'
        if args.repository is None:
            print('Available Repositories are:')
            for repo in repo_list:
                repo_table.append_row([
                    repo.github_info['name'], repo.github_info['description']
                ])
            print(repo_table)
            sys.exit(0)
        else:
            for repo in repo_list:
                if repo.github_info['name'] == args.repository:
                    repo_url = repo.github_info['clone_url']
                    break
            if repo_url is 'unset':
                print(
                    'Invalid Repository was specified. Available Repositories are:'
                )
                for repo in repo_list:
                    repo_table.append_row([
                        repo.github_info['name'],
                        repo.github_info['description']
                    ])
                print(repo_table)
                sys.exit(0)
        repo_name = args.repository
        g = Git(repo_url)
        g.clone(repo_name, ow=args.refresh, update=args.update)
        if args.branch is None:
            print("Branches available for " + args.repository + " are :")
            print("\n".join(g.list_branches()))
            sys.exit(0)
        elif args.branch == "default":
            print("Using default branch for repository.")
        elif args.branch not in g.list_branches():
            print("Invalid Branch was choosen. Please select from below list:")
            print("\n".join(g.list_branches()))
            sys.exit(0)
        else:
            g.branch(args.branch)

        sc = g.build()
    elif args.repotype == "local":
        repo_name = args.repopath
        g = Git("")
        sc = g.build_from_local(args.repopath)
    else:
        print("No other skillet types currently supported.")
        exit(1)

    if len(args.snippetnames) == 0:
        print("printing available {} snippets".format(repo_name))
        sc.print_all_skillets(elements=args.print_entries)
        sys.exit(0)
    else:
        addr = env_or_prompt(
            "address",
            args,
            prompt_long="address or address:port of PANOS Device to configure: "
        )
        apikey = KEY_DB.lookup(addr)
        if not apikey:
            user = env_or_prompt("username", args)
            pw = env_or_prompt("password", args, secret=True)
            fw = Panos(addr,
                       user=user,
                       pw=pw,
                       debug=args.debug,
                       verify=args.validate)
            KEY_DB.add_key(addr, fw.key)
        else:
            fw = Panos(addr,
                       apikey=apikey,
                       debug=args.debug,
                       verify=args.validate)

        t = fw.get_type()

        skillet = sc.get_skillet(t.lower())
        context = create_context(args.config)
        skillet.template(context)
        snippets = skillet.select_snippets(args.snippetstack,
                                           args.snippetnames)
        if len(snippets) == 0:
            print("{}Snippets {} not found for device type {}.{}".format(
                Fore.RED, ",".join(args.snippetnames), t, Style.RESET_ALL))

        for snippet in skillet.select_snippets(args.snippetstack,
                                               args.snippetnames):
            print("Doing {} at {}...".format(snippet.name,
                                             snippet.rendered_xpath),
                  end="")
            r = set_at_path(fw, snippet.rendered_xpath,
                            snippet.rendered_xmlstr)
            check_resp(r)