diff --git a/src/ssh_config_to_yaml.py b/src/ssh_config_to_yaml.py new file mode 100644 index 0000000..121bd78 --- /dev/null +++ b/src/ssh_config_to_yaml.py @@ -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="")