#!/usr/bin/env python3 """ Sync SSH public keys from database to /home/tunnel/.ssh/authorized_keys Run this script when devices register or keys change. """ import asyncio from pathlib import Path from sqlalchemy import select from app.core.database import async_session_maker from app.models.device import Device AUTHORIZED_KEYS_PATH = Path("/home/tunnel/.ssh/authorized_keys") async def sync_ssh_keys(): """Sync all device SSH keys to authorized_keys file.""" async with async_session_maker() as session: # Get all devices with SSH public keys result = await session.execute(select(Device)) devices = result.scalars().all() keys = [] for device in devices: if device.config and 'ssh_public_key' in device.config: ssh_key = device.config['ssh_public_key'].strip() if ssh_key: # Add comment with device MAC keys.append(f"{ssh_key} # {device.mac_address}") print(f"Found {len(keys)} SSH keys in database") # Write to authorized_keys authorized_keys_content = "\n".join(keys) + "\n" if keys else "" # Need sudo to write import subprocess subprocess.run( ["sudo", "tee", str(AUTHORIZED_KEYS_PATH)], input=authorized_keys_content.encode(), stdout=subprocess.DEVNULL, check=True ) # Set permissions subprocess.run( ["sudo", "chmod", "600", str(AUTHORIZED_KEYS_PATH)], check=True ) subprocess.run( ["sudo", "chown", "tunnel:tunnel", str(AUTHORIZED_KEYS_PATH)], check=True ) print(f"Synced {len(keys)} keys to {AUTHORIZED_KEYS_PATH}") return len(keys) if __name__ == "__main__": asyncio.run(sync_ssh_keys())