SSH-key-Manager/edit_host.py

104 lines
3.4 KiB
Python

# ssh_manager/edit_host.py
import os
from collections import OrderedDict
from .utils import print_error, print_warning, print_info
def load_config_file(file_path):
"""
Parse the given config file into a list of host blocks (OrderedDict).
"""
blocks = []
host_data = None
try:
with open(file_path, 'r') as f:
lines = f.readlines()
except Exception as e:
print_error(f"Error reading SSH config file {file_path}: {e}")
return blocks
for line in lines:
stripped_line = line.strip()
if not stripped_line or stripped_line.startswith('#'):
continue
if stripped_line.lower().startswith('host '):
host_labels = stripped_line.split()[1:]
for label in host_labels:
if '*' not in label:
if host_data:
blocks.append(host_data)
host_data = OrderedDict({'Host': label})
break
elif host_data:
if ' ' in stripped_line:
key, value = stripped_line.split(None, 1)
host_data[key] = value.strip()
if host_data:
blocks.append(host_data)
return blocks
def edit_host(conf_dir):
"""
Let the user update fields for an existing host in ~/.ssh/conf/<label>/config.
"""
host_label = input("Enter the Host label to edit: ").strip()
if not host_label:
print_error("Host label cannot be empty.")
return
host_dir = os.path.join(conf_dir, host_label)
config_path = os.path.join(host_dir, "config")
if not os.path.isfile(config_path):
print_warning(f"No config file found at {config_path}; cannot edit this host.")
return
blocks = load_config_file(config_path)
if not blocks:
print_warning(f"No valid Host blocks found in {config_path}")
return
target_block = None
for b in blocks:
if b.get("Host") == host_label:
target_block = b
break
if not target_block:
print_warning(f"No matching Host '{host_label}' found in {config_path}")
return
old_hostname = target_block.get("HostName", "")
old_user = target_block.get("User", "")
old_port = target_block.get("Port", "22")
old_identity = target_block.get("IdentityFile", "")
print_info("Leave a field blank to keep its current value.")
new_hostname = input(f"Enter new HostName [{old_hostname}]: ").strip()
new_user = input(f"Enter new User [{old_user}]: ").strip()
new_port = input(f"Enter new Port [{old_port}]: ").strip()
new_ident = input(f"Enter new IdentityFile [{old_identity}]: ").strip()
final_hostname = new_hostname if new_hostname else old_hostname
final_user = new_user if new_user else old_user
final_port = new_port if new_port else old_port
final_ident = new_ident if new_ident else old_identity
new_config_lines = [
f"Host {host_label}",
f" HostName {final_hostname}",
f" User {final_user}",
f" Port {final_port}"
]
if final_ident:
new_config_lines.append(f" IdentityFile {final_ident}")
try:
with open(config_path, "w") as f:
for line in new_config_lines:
f.write(line + "\n")
print_info(f"Updated config at: {config_path}")
except Exception as e:
print_error(f"Failed to update config: {e}")