summaryrefslogtreecommitdiff
path: root/src/utils/vyos-config-to-json
diff options
context:
space:
mode:
authorDaniil Baturin <daniil@baturin.org>2019-10-27 15:22:49 +0100
committerDaniil Baturin <daniil@baturin.org>2019-10-27 15:22:49 +0100
commit2673f4790e19531fba719810a3a38e1917e57214 (patch)
tree66b805d1d93cd65da917e3bc7a0c6cef7119991a /src/utils/vyos-config-to-json
parent556b528ef9cc1eca9d142ebe1f8f88cd02d536da (diff)
downloadvyos-1x-2673f4790e19531fba719810a3a38e1917e57214.tar.gz
vyos-1x-2673f4790e19531fba719810a3a38e1917e57214.zip
T1773: add a script for converting the config to JSON.
It also exposes those functions in vyos.configtree
Diffstat (limited to 'src/utils/vyos-config-to-json')
-rwxr-xr-xsrc/utils/vyos-config-to-json40
1 files changed, 40 insertions, 0 deletions
diff --git a/src/utils/vyos-config-to-json b/src/utils/vyos-config-to-json
new file mode 100755
index 000000000..e03fd6a59
--- /dev/null
+++ b/src/utils/vyos-config-to-json
@@ -0,0 +1,40 @@
+#!/usr/bin/python3
+
+import sys
+import json
+
+from signal import signal, SIGPIPE, SIG_DFL
+from vyos.configtree import ConfigTree
+
+signal(SIGPIPE,SIG_DFL)
+
+config_string = None
+if (len(sys.argv) == 1):
+ # If no argument given, act as a pipe
+ config_string = sys.stdin.read()
+else:
+ file_name = sys.argv[1]
+ try:
+ with open(file_name, 'r') as f:
+ config_string = f.read()
+ except OSError as e:
+ print("Could not read config file {0}: {1}".format(file_name, e), file=sys.stderr)
+
+# This script is usually called with the output of "cli-shell-api showCfg", which does not
+# escape backslashes. "ConfigTree()" expects escaped backslashes when parsing a config
+# string (and also prints them itself). Therefore this script would fail.
+# Manually escape backslashes here to handle backslashes in any configuration strings
+# properly. The alternative would be to modify the output of "cli-shell-api showCfg",
+# but that may be break other things who rely on that specific output.
+config_string = config_string.replace("\\", "\\\\")
+
+try:
+ config = ConfigTree(config_string)
+ json_str = config.to_json()
+ # Pretty print
+ json_str = json.dumps(json.loads(json_str), indent=4, sort_keys=True)
+except ValueError as e:
+ print("Could not parse the config file: {0}".format(e), file=sys.stderr)
+ sys.exit(1)
+
+print(json_str)