generated from Luis/nextjs-python-web-template
clan-cli: split out ssh subcommand, add more tests
This commit is contained in:
80
pkgs/clan-cli/clan_cli/ssh.py
Normal file
80
pkgs/clan-cli/clan_cli/ssh.py
Normal file
@@ -0,0 +1,80 @@
|
||||
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)
|
||||
Reference in New Issue
Block a user