transfer.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import os
  2. import re
  3. import subprocess
  4. def generate_key(dest_name, data_dir):
  5. """Génère une paire de clés ed25519 pour cette destination si elle n'existe pas encore."""
  6. key_name = f"dest_{_slugify(dest_name)}_ed25519"
  7. os.makedirs(os.path.join(data_dir, "keys"), exist_ok=True)
  8. key_path = os.path.join(data_dir, "keys", key_name)
  9. if not os.path.exists(key_path):
  10. subprocess.run(
  11. [
  12. "ssh-keygen", "-t", "ed25519",
  13. "-f", key_path,
  14. "-N", "",
  15. "-C", f"backupmanager@{dest_name}",
  16. ],
  17. check=True,
  18. capture_output=True,
  19. )
  20. os.chmod(key_path, 0o600)
  21. return key_name
  22. def get_public_key(key_name, data_dir):
  23. """Retourne la clé publique à copier dans authorized_keys sur le serveur distant."""
  24. pub_path = os.path.join(data_dir, "keys", key_name + ".pub")
  25. try:
  26. with open(pub_path) as f:
  27. return f.read().strip()
  28. except FileNotFoundError:
  29. return None
  30. def transfer_archive(archive_name, destination, backup_dir, data_dir):
  31. """Transfère .tar + .info.json vers la destination via rsync SSH."""
  32. key_path = os.path.join(data_dir, "keys", destination.key_name)
  33. if not os.path.exists(key_path):
  34. raise FileNotFoundError(
  35. f"Clé SSH introuvable : {key_path}\n"
  36. "Accédez à la page de la destination pour afficher la clé publique."
  37. )
  38. files = []
  39. for ext in (".tar", ".info.json"):
  40. path = os.path.join(backup_dir, archive_name + ext)
  41. if os.path.exists(path):
  42. files.append(path)
  43. if not files:
  44. raise FileNotFoundError(f"Aucun fichier à transférer pour {archive_name}.")
  45. remote = f"{destination.user}@{destination.host}:{destination.remote_path}/"
  46. ssh_opts = (
  47. f"ssh -i {key_path} -p {destination.port}"
  48. " -o StrictHostKeyChecking=accept-new"
  49. " -o BatchMode=yes"
  50. " -o ConnectTimeout=30"
  51. )
  52. # sudo car les archives YNH (ynh_app/ynh_system) sont owned root
  53. cmd = ["sudo", "rsync", "-az", "--stats", "-e", ssh_opts] + files + [remote]
  54. result = subprocess.run(cmd, capture_output=True, text=True, timeout=7200)
  55. log = (result.stdout + result.stderr).strip()
  56. if result.returncode != 0:
  57. raise RuntimeError(
  58. f"rsync vers {destination.host} échoué (code {result.returncode}) :\n{log}"
  59. )
  60. return log
  61. def test_connection(destination, data_dir):
  62. """Teste la connexion SSH vers la destination. Retourne (True, msg) ou (False, msg)."""
  63. key_path = os.path.join(data_dir, "keys", destination.key_name)
  64. if not os.path.exists(key_path):
  65. return False, "Clé SSH non générée. Affichez la destination pour la créer."
  66. result = subprocess.run(
  67. [
  68. "ssh",
  69. "-i", key_path,
  70. "-p", str(destination.port),
  71. "-o", "StrictHostKeyChecking=accept-new",
  72. "-o", "BatchMode=yes",
  73. "-o", "ConnectTimeout=10",
  74. f"{destination.user}@{destination.host}",
  75. "echo ok",
  76. ],
  77. capture_output=True,
  78. text=True,
  79. timeout=20,
  80. )
  81. if result.returncode == 0:
  82. return True, f"Connexion réussie vers {destination.host}:{destination.port}."
  83. return False, result.stderr.strip() or f"Connexion échouée (code {result.returncode})."
  84. def _slugify(s):
  85. return re.sub(r'[^a-z0-9]+', '-', s.lower().strip()).strip('-')