transfer.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. from jobs.utils import sudo_exists
  39. files = []
  40. for ext in (".tar", ".info.json"):
  41. path = os.path.join(backup_dir, archive_name + ext)
  42. if sudo_exists(path):
  43. files.append(path)
  44. if not files:
  45. raise FileNotFoundError(f"Aucun fichier à transférer pour {archive_name}.")
  46. remote = f"{destination.user}@{destination.host}:{destination.remote_path}/"
  47. ssh_opts = (
  48. f"ssh -i {key_path} -p {destination.port}"
  49. " -o StrictHostKeyChecking=accept-new"
  50. " -o BatchMode=yes"
  51. " -o ConnectTimeout=30"
  52. )
  53. # sudo car les archives YNH (ynh_app/ynh_system) sont owned root
  54. cmd = ["sudo", "rsync", "-az", "--stats", "-e", ssh_opts] + files + [remote]
  55. result = subprocess.run(cmd, capture_output=True, text=True, timeout=7200)
  56. log = (result.stdout + result.stderr).strip()
  57. if result.returncode != 0:
  58. raise RuntimeError(
  59. f"rsync vers {destination.host} échoué (code {result.returncode}) :\n{log}"
  60. )
  61. return log
  62. def test_connection(destination, data_dir):
  63. """Teste la connexion SSH vers la destination. Retourne (True, msg) ou (False, msg)."""
  64. key_path = os.path.join(data_dir, "keys", destination.key_name)
  65. if not os.path.exists(key_path):
  66. return False, "Clé SSH non générée. Affichez la destination pour la créer."
  67. result = subprocess.run(
  68. [
  69. "ssh",
  70. "-i", key_path,
  71. "-p", str(destination.port),
  72. "-o", "StrictHostKeyChecking=accept-new",
  73. "-o", "BatchMode=yes",
  74. "-o", "ConnectTimeout=10",
  75. f"{destination.user}@{destination.host}",
  76. "echo ok",
  77. ],
  78. capture_output=True,
  79. text=True,
  80. timeout=20,
  81. )
  82. if result.returncode == 0:
  83. return True, f"Connexion réussie vers {destination.host}:{destination.port}."
  84. return False, result.stderr.strip() or f"Connexion échouée (code {result.returncode})."
  85. def _slugify(s):
  86. return re.sub(r'[^a-z0-9]+', '-', s.lower().strip()).strip('-')