deploy_to_server.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #!/usr/bin/env python3
  2. #ident "@(#)$Format:LocalFoodAI:deploy_to_server.py:%an:%ae:%ad:%cn:%ce:%cd:%H:%D:%N$"
  3. import os
  4. import paramiko
  5. from dotenv import load_dotenv
  6. def deploy():
  7. # Load .env
  8. repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  9. env_path = os.path.join(repo_root, ".env")
  10. load_dotenv(dotenv_path=env_path)
  11. host = os.environ.get('SERVER_HOST')
  12. user = os.environ.get('SERVER_USER')
  13. password = os.environ.get('SERVER_PASS')
  14. if not all([host, user, password]):
  15. print("Error: Server credentials not found in .env file.")
  16. return
  17. print(f"Connecting to {user}@{host}...")
  18. ssh = paramiko.SSHClient()
  19. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  20. try:
  21. ssh.connect(host, username=user, password=password, timeout=10)
  22. print("Connected successfully!")
  23. command = "cd food_project && git pull && docker compose up -d --build"
  24. print(f"Executing: {command}")
  25. stdin, stdout, stderr = ssh.exec_command(command)
  26. out = stdout.read().decode('utf-8')
  27. err = stderr.read().decode('utf-8')
  28. if out: print(f"Output:\n{out}")
  29. if err: print(f"Errors:\n{err}")
  30. except Exception as e:
  31. print(f"Failed to connect or execute command: {e}")
  32. finally:
  33. ssh.close()
  34. print("Connection closed.")
  35. if __name__ == "__main__":
  36. deploy()