SSH-key-Manager/add_host.py

94 lines
3.7 KiB
Python

# ssh_manager/add_host.py
import os
import subprocess
from .utils import print_error, print_warning, print_info
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 = input("Enter Host label (e.g. myserver): ").strip()
if not host_label:
print_error("Host label cannot be empty.")
return
hostname = input("Enter HostName (IP or domain): ").strip()
if not hostname:
print_error("HostName cannot be empty.")
return
user = input("Enter username (default: 'root'): ").strip() or "root"
port = input("Enter SSH port (default: 22): ").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.")
# Ask about generating an SSH key
gen_key_choice = input("Generate a new ed25519 SSH key for this host? (y/n): ").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:
# Generate a new SSH key (quietly, suppressing randomart)
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 to the server
copy_key = input("Would you like to copy this key to the server now? (y/n): ").lower().strip()
if copy_key == '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:
# If not generating a new key, optionally ask for an existing path
existing_key = input("Enter existing IdentityFile path (or leave empty to skip): ").strip()
if existing_key:
identity_file = os.path.expanduser(existing_key)
# Build the config lines
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}")
# Write (or overwrite) the config
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}")