有没有一种方法可以将杜松“ json”或“ xml”配置转换为“设置”或“显示”配置?

时间:2019-02-13 13:20:21

标签: juniper junos-automation pyez

我们在junos版本15中使用瞻博硬件。在此版本中,我们可以将配置导出为“ json”或“ xml”,我们希望使用其通过自动化工具对其进行编辑。 但是,只能以“设置”或“显示”格式导入。

是否有工具将“ json”或“ xml”格式转换为“ set”或“ show”格式? 我只能在“显示”和“设置”之间找到转换器。

我们无法升级到版本16,因此可以导入“ json”。

3 个答案:

答案 0 :(得分:1)

这是我在工作时制作的脚本,将其放入垃圾箱,您可以通过提供文件名或管道输出来实现。这假设是 linux 或 mac,所以 os.isatty 函数可以工作,但逻辑可以在任何地方工作:

使用演示:

person@laptop ~ > head router.cfg
## Last commit: 2021-04-20 21:21:39 UTC by vit
version 15.1X12.2;
groups {
    BACKBONE-PORT {
        interfaces {
            <*> {
                mtu 9216;
                unit <*> {
                    family inet {
                        mtu 9150;
person@laptop ~ > convert.py router.cfg | head
set groups BACKBONE-PORT interfaces <*> mtu 9216
set groups BACKBONE-PORT interfaces <*> unit <*> family inet mtu 9150
set groups BACKBONE-PORT interfaces <*> unit <*> family inet6 mtu 9150
set groups BACKBONE-PORT interfaces <*> unit <*> family mpls maximum-labels 5
<... output removed... >

convert.py:

#!/usr/bin/env python3
# Class that attempts to parse out Juniper JSON into set format
#   I think it works? still testing
#
#   TODO: 
#      accumulate annotations and provide them as commands at the end. Will be weird as annotations have to be done after an edit command
from argparse import ArgumentParser, RawTextHelpFormatter
import sys, os, re

class TokenStack():
    def __init__(self):
        self._tokens = []

    def push(self, token):
        self._tokens.append(token)

    def pop(self):
        if not self._tokens:
            return None
        item = self._tokens[-1]
        self._tokens = self._tokens[:-1]
        return item

    def peek(self):
        if not self._tokens:
            return None
        return self._tokens[-1]

    def __str__(self):
        return " ".join(self._tokens)

    def __repr__(self):
        return " ".join(self._tokens)

def main():
    # get file
    a = ArgumentParser(prog="convert_jpr_json",
            description="This program takes in Juniper style JSON (blah { format) and prints it in a copy pastable display set format",
            epilog=f"Either supply with a filename or pipe config contents into this program and it'll print out the display set view.\nEx:\n{B}convert_jpr_json <FILENAME>\ncat <FILENAME> | convert_jpr_json{WHITE}",
            formatter_class=RawTextHelpFormatter)
    a.add_argument('file', help="juniper config in JSON format", nargs="?")
    args = a.parse_args()
    if not args.file and os.isatty(0):
        a.print_help()
        die("Please supply filename or provide piped input")
    file_contents = None
    if args.file:
        try:
            file_contents = open(args.file, "r").readlines()
        except IOError as e:
            die(f"Issue opening file {args.file}: {e}")
            print(output_text)
    else:
        file_contents = sys.stdin.readlines()

    tokens = TokenStack()
    in_comment = False
    new_config = []

    for line_num, line in enumerate(file_contents):
        if line.startswith("version ") or len(line) == 0:
            continue
        token = re.sub(r"^(.+?)#+[^\"]*$", r"\1", line.strip())
        token = token.strip()
        if (any(token.startswith(_) for _ in ["!", "#"])):
            # annotations currently not supported
            continue
    
        if token.startswith("/*"):
            # we're in a comment now until the next token (this will break if a multiline comment with # style { happens, but hopefully no-one is that dumb
            in_comment = True
            continue
    
        if "inactive: " in token:
            token = token.split("inactive: ")[1]
            new_config.append(f"deactivate {tokens} {token}")
        if token[-1] == "{":
            in_comment = False
            tokens.push(token.strip("{ "))
        elif token[-1] == "}":
            if not tokens.pop():
                die("Invalid json supplied: unmatched closing } encountered on line " + f"{line_num}")
        elif token[-1] == ";":
            new_config.append(f"set {tokens} {token[:-1]}")
    if tokens.peek():
        print(tokens)
        die("Unbalanced JSON: expected closing }, but encountered EOF")
    print("\n".join(new_config))

def die(msg): print(f"\n{B}{RED}FATAL ERROR{WHITE}: {msg}"); exit(1)
RED = "\033[31m"; GREEN = "\033[32m"; YELLOW = "\033[33m"; B = "\033[1m"; WHITE = "\033[0m"
if __name__ == "__main__": main()

答案 1 :(得分:0)

答案 2 :(得分:0)

通过将内容放置在对“ junos.xsl”中定义的junos:load-configuration()模板的调用中,可以通过“ op”脚本加载XML内容。类似于以下内容:

version 1.1;

ns jcs = "http://xml.juniper.net/junos/commit-scripts/1.0";

import "../import/junos.xsl";

var $arguments = {
    <argument> {
        <name> "file";
        <description> "Filename of XML content to load";
    }
    <argument> {
        <name> "action";
        <description> "Mode for the load (override, replace, merge)";
    }
}

param $file;
param $action = "replace";

match / {
    <op-script-results> {
        var $configuration = slax:document($file);
        var $connection = jcs:open();
        call jcs:load-configuration($connection, $configuration, $action);
    }
}

谢谢,  菲尔