SSH-key-Manager/add_host.py

110 lines
4 KiB
Python

# ssh_manager/add_host.py
import os
import subprocess
from .utils import print_error, print_warning, print_info, safe_input
def add_host(conf_dir):
"""
Interactive prompt to create a new SSH host in ~/.ssh/conf/<label>/config.
Offers to generate a new SSH key pair (ed25519) quietly (-q),
and then prompt to copy that key to the remote server via ssh-copy-id.
"""
print_info("Adding a new SSH host...")
host_label = safe_input("Enter Host label (e.g. myserver): ")
if host_label is None:
return # User canceled (Ctrl+C)
host_label = host_label.strip()
if not host_label:
print_error("Host label cannot be empty.")
return
hostname = safe_input("Enter HostName (IP or domain): ")
if hostname is None:
return
hostname = hostname.strip()
if not hostname:
print_error("HostName cannot be empty.")
return
user = safe_input("Enter username (default: 'root'): ")
if user is None:
return
user = user.strip() or "root"
port = safe_input("Enter SSH port (default: 22): ")
if port is None:
return
port = port.strip() or "22"
# Create subdirectory: ~/.ssh/conf/<label>
host_dir = os.path.join(conf_dir, host_label)
if os.path.exists(host_dir):
print_warning(f"Directory {host_dir} already exists; continuing anyway.")
else:
os.makedirs(host_dir, mode=0o700, exist_ok=True)
print_info(f"Created directory: {host_dir}")
config_path = os.path.join(host_dir, "config")
if os.path.exists(config_path):
print_warning(f"Config file already exists: {config_path}; it will be overwritten/updated.")
gen_key_choice = safe_input("Generate a new ed25519 SSH key for this host? (y/n): ")
if gen_key_choice is None:
return
gen_key_choice = gen_key_choice.lower().strip()
identity_file = ""
if gen_key_choice == 'y':
key_path = os.path.join(host_dir, "id_ed25519")
if os.path.exists(key_path):
print_warning(f"{key_path} already exists. Skipping generation.")
identity_file = key_path
else:
cmd = ["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", key_path]
try:
subprocess.check_call(cmd)
print_info(f"Generated new SSH key at {key_path}")
identity_file = key_path
# Prompt to copy the key
copy_key = safe_input("Would you like to copy this key to the server now? (y/n): ")
if copy_key is None:
return
if copy_key.lower().strip() == 'y':
ssh_copy_cmd = ["ssh-copy-id", "-i", key_path]
if port != "22":
ssh_copy_cmd += ["-p", port]
ssh_copy_cmd.append(f"{user}@{hostname}")
try:
subprocess.check_call(ssh_copy_cmd)
print_info("Key successfully copied to remote server.")
except subprocess.CalledProcessError as e:
print_error(f"Error copying key to server: {e}")
except subprocess.CalledProcessError as e:
print_error(f"Error generating SSH key: {e}")
else:
existing_key = safe_input("Enter existing IdentityFile path (or leave empty to skip): ")
if existing_key is None:
return
existing_key = existing_key.strip()
if existing_key:
identity_file = os.path.expanduser(existing_key)
config_lines = [
f"Host {host_label}",
f" HostName {hostname}",
f" User {user}",
f" Port {port}"
]
if identity_file:
config_lines.append(f" IdentityFile {identity_file}")
try:
with open(config_path, "w") as f:
for line in config_lines:
f.write(line + "\n")
print_info(f"Created/updated config at: {config_path}")
except Exception as e:
print_error(f"Failed to write config to {config_path}: {e}")