Parser: config to yaml parser
This commit is contained in:
parent
69f342fcab
commit
fe2d1cfa14
1 changed files with 58 additions and 0 deletions
58
src/ssh_config_to_yaml.py
Normal file
58
src/ssh_config_to_yaml.py
Normal file
|
@ -0,0 +1,58 @@
|
|||
import argparse
|
||||
import json
|
||||
import re
|
||||
import yaml
|
||||
from pathlib import Path
|
||||
|
||||
parser = argparse.ArgumentParser(description="Process some integers.")
|
||||
parser.add_argument("file", type=Path, help="yaml config")
|
||||
parser.add_argument("--json", action="store_true", help="output parse as json")
|
||||
parser.add_argument("--out", type=Path, help="write into file")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
|
||||
def parse_sshconfig(lines):
|
||||
parse = dict()
|
||||
hostname = None
|
||||
host = dict()
|
||||
|
||||
re_host = re.compile(r"^\s*Host (.+)$")
|
||||
re_prop = re.compile(r"^\s*([A-Za-z]+)[ =](.+)$")
|
||||
|
||||
for line in lines:
|
||||
m_host = re_host.match(line)
|
||||
m_prop = re_prop.match(line)
|
||||
|
||||
if m_host:
|
||||
if hostname is not None:
|
||||
parse[hostname] = host
|
||||
|
||||
hostname = m_host[1]
|
||||
host = dict()
|
||||
elif m_prop and host.get(m_prop[1]):
|
||||
host[m_prop[1]].append(m_prop[2])
|
||||
elif m_prop:
|
||||
host[m_prop[1]] = [m_prop[2]]
|
||||
|
||||
if hostname is not None:
|
||||
parse[hostname] = host
|
||||
|
||||
return parse
|
||||
|
||||
|
||||
# ╔───────────────────────────────────────────────────────────────────────────╗
|
||||
# │ Mαiη |
|
||||
# ╚───────────────────────────────────────────────────────────────────────────╝
|
||||
with open(args.file, "r") as f:
|
||||
lines = f.read().splitlines()
|
||||
|
||||
parse = parse_sshconfig(lines)
|
||||
|
||||
if args.json:
|
||||
print(json.dumps(parse))
|
||||
elif args.out:
|
||||
with open(args.out, "w") as f:
|
||||
f.write(yaml.dump(parse))
|
||||
else:
|
||||
print(yaml.dump(parse), end="")
|
Loading…
Reference in a new issue