ssh_keys.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. """
  2. SSH keys management utilities.
  3. """
  4. import subprocess
  5. from sqlalchemy import select
  6. from app.core.database import async_session_maker
  7. from app.models.device import Device
  8. async def sync_authorized_keys():
  9. """
  10. Sync all device SSH keys to /home/tunnel/.ssh/authorized_keys
  11. This should be called:
  12. - After device registration (to add new key)
  13. - After device deletion (to remove key)
  14. """
  15. try:
  16. async with async_session_maker() as session:
  17. result = await session.execute(select(Device))
  18. devices = result.scalars().all()
  19. keys = []
  20. for device in devices:
  21. if device.config and 'ssh_public_key' in device.config:
  22. ssh_key = device.config['ssh_public_key'].strip()
  23. if ssh_key:
  24. keys.append(f"{ssh_key} # {device.mac_address}")
  25. authorized_keys_content = "\n".join(keys) + "\n" if keys else ""
  26. # Write using sudo
  27. subprocess.run(
  28. ["sudo", "tee", "/home/tunnel/.ssh/authorized_keys"],
  29. input=authorized_keys_content.encode(),
  30. stdout=subprocess.DEVNULL,
  31. check=True
  32. )
  33. subprocess.run(
  34. ["sudo", "chmod", "600", "/home/tunnel/.ssh/authorized_keys"],
  35. check=True
  36. )
  37. subprocess.run(
  38. ["sudo", "chown", "tunnel:tunnel", "/home/tunnel/.ssh/authorized_keys"],
  39. check=True
  40. )
  41. print(f"[SSH] Synced {len(keys)} keys to authorized_keys")
  42. except Exception as e:
  43. print(f"[SSH] Failed to sync authorized_keys: {e}")