Files
clan-core/pkgs/clan-cli/clan_cli/ssh.py

81 lines
2.0 KiB
Python

import argparse
import json
import subprocess
from typing import Optional
def ssh(
host: str,
user: str = "root",
password: Optional[str] = None,
ssh_args: list[str] = [],
) -> None:
if ssh_args is None:
ssh_args = []
nix_shell_args = []
password_args = []
if password:
nix_shell_args = [
"nix",
"shell",
"nixpkgs#sshpass",
"-c",
]
password_args = [
"sshpass",
"-p",
password,
]
_ssh_args = ssh_args + [
"ssh",
"-o",
"UserKnownHostsFile=/dev/null",
"-o",
"StrictHostKeyChecking=no",
f"{user}@{host}",
]
cmd = nix_shell_args + ["torify"] + password_args + _ssh_args
subprocess.run(cmd)
def qrcode_scan(pictureFile: str) -> dict:
subprocess.Popen(
[
"nix",
"shell",
"nixpkgs#zbar",
"-c",
"zbarimg",
"--quiet",
"--raw",
pictureFile,
],
stdout=subprocess.PIPE,
).stdout.read()
def main(args: argparse.Namespace) -> None:
if args.json:
with open(args.json) as file:
ssh_data = json.load(file)
ssh(host=ssh_data["address"], password=ssh_data["password"])
elif args.png:
ssh_data = json.loads(qrcode_scan(args.png))
ssh(host=ssh_data["address"], password=ssh_data["password"])
def register_parser(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"-j",
"--json",
help="specify the json file for ssh data (generated by starting the clan installer",
)
parser.add_argument(
"-P",
"--png",
help="specify the json file for ssh data as the qrcode image (generated by starting the clan installer",
)
# TODO pass all args we don't parse into ssh_args, currently it fails if arg starts with -
parser.add_argument("ssh_args", nargs="*", default=[])
parser.set_defaults(func=main)