有需要的自取
import random
from sshconf import read_ssh_config
from os.path import expanduser
import json
from datetime import datetime
c = read_ssh_config(expanduser("~/.ssh/config"))
def load_private_key(key_path):
with open(expanduser(key_path), "r") as key_file:
key = key_file.read()
return key
def rand_id(length=24, chars="abcdefghijklmnopqrstuvwxyz0123456789"):
return "".join(random.choice(chars) for i in range(length))
def utc_datetime_str():
return datetime.now().strftime("%Y-%m-%dT%H:%M:%S+08:00")
jump_hosts = {}
hosts = c.hosts()
for host in hosts:
host_config = c.host(host)
if "proxyjump" in host_config:
jump_host = host_config["proxyjump"]
jump_hosts[host] = jump_host
config = {"groups": [], "servers": []}
for host in hosts:
host_config = c.host(host)
server = {
"title": host,
"host": host_config["hostname"],
"port": host_config["port"],
"authType": "privateKey",
"connectionConfig": {"connectOptions": {"algorithms": {}}, "init": {}},
"username": host_config["user"],
"privateKey": load_private_key(host_config["identityfile"]),
"_id": rand_id(),
"createdAt": utc_datetime_str(),
"updatedAt": utc_datetime_str(),
# 自己实现sshProxy逻辑
}
config["servers"].append(server)
with open("config.json", "w") as f:
json.dump(config, f, indent=4)