sync_ssh_keys.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #!/usr/bin/env python3
  2. """
  3. Sync SSH public keys from database to /home/tunnel/.ssh/authorized_keys
  4. Run this script when devices register or keys change.
  5. """
  6. import asyncio
  7. from pathlib import Path
  8. from sqlalchemy import select
  9. from app.core.database import async_session_maker
  10. from app.models.device import Device
  11. AUTHORIZED_KEYS_PATH = Path("/home/tunnel/.ssh/authorized_keys")
  12. async def sync_ssh_keys():
  13. """Sync all device SSH keys to authorized_keys file."""
  14. async with async_session_maker() as session:
  15. # Get all devices with SSH public keys
  16. result = await session.execute(select(Device))
  17. devices = result.scalars().all()
  18. keys = []
  19. for device in devices:
  20. if device.config and 'ssh_public_key' in device.config:
  21. ssh_key = device.config['ssh_public_key'].strip()
  22. if ssh_key:
  23. # Add comment with device MAC
  24. keys.append(f"{ssh_key} # {device.mac_address}")
  25. print(f"Found {len(keys)} SSH keys in database")
  26. # Write to authorized_keys
  27. authorized_keys_content = "\n".join(keys) + "\n" if keys else ""
  28. # Need sudo to write
  29. import subprocess
  30. subprocess.run(
  31. ["sudo", "tee", str(AUTHORIZED_KEYS_PATH)],
  32. input=authorized_keys_content.encode(),
  33. stdout=subprocess.DEVNULL,
  34. check=True
  35. )
  36. # Set permissions
  37. subprocess.run(
  38. ["sudo", "chmod", "600", str(AUTHORIZED_KEYS_PATH)],
  39. check=True
  40. )
  41. subprocess.run(
  42. ["sudo", "chown", "tunnel:tunnel", str(AUTHORIZED_KEYS_PATH)],
  43. check=True
  44. )
  45. print(f"Synced {len(keys)} keys to {AUTHORIZED_KEYS_PATH}")
  46. return len(keys)
  47. if __name__ == "__main__":
  48. asyncio.run(sync_ssh_keys())