upload_tf_files_to_server.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #!/usr/bin/env python3
  2. """
  3. Upload Terraform files to server
  4. This script uploads all .tf files from the terraform directory to a remote server via SSH
  5. """
  6. import os
  7. import sys
  8. from pathlib import Path
  9. import paramiko
  10. from scp import SCPClient
  11. def upload_tf_files(server_ip, username, password, local_dir="./", remote_dir="/tmp/terraform"):
  12. """
  13. Upload the entire tfs folder to remote server
  14. Args:
  15. server_ip (str): Remote server IP address
  16. username (str): Username for SSH connection
  17. password (str): Password for SSH connection
  18. local_dir (str): Local directory containing the tfs folder
  19. remote_dir (str): Remote directory to upload files to
  20. """
  21. try:
  22. # Create SSH client
  23. ssh_client = paramiko.SSHClient()
  24. ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  25. # Connect to server
  26. print(f"Connecting to {server_ip}...")
  27. ssh_client.connect(hostname=server_ip, username=username, password=password)
  28. # Create SCP client
  29. with SCPClient(ssh_client.get_transport()) as scp_client:
  30. # Upload the entire tfs folder
  31. local_path = Path(local_dir)
  32. if not local_path.exists():
  33. print(f"Local directory {local_dir} does not exist")
  34. return
  35. print(f"Uploading directory: {local_dir}")
  36. # Create remote directory if it doesn't exist
  37. stdin, stdout, stderr = ssh_client.exec_command(f'mkdir -p {remote_dir}')
  38. stdout.channel.recv_exit_status() # Wait for command to complete
  39. # Upload the entire directory
  40. print(f"Uploading {local_dir} to {server_ip}:{remote_dir}/...")
  41. scp_client.put(str(local_path), remote_dir, recursive=True)
  42. print(f" [SUCCESS] Directory uploaded successfully")
  43. print(f"\nDirectory uploaded to {server_ip}:{remote_dir}/")
  44. except Exception as e:
  45. print(f"Error uploading directory: {str(e)}")
  46. raise
  47. finally:
  48. if 'ssh_client' in locals():
  49. ssh_client.close()
  50. def main():
  51. # Configuration
  52. SERVER_IP = "47.113.186.215" # Pre-set server IP
  53. USERNAME = "root" # Pre-set username
  54. PASSWORD = "Xs261617" # Pre-set password
  55. LOCAL_DIR = r"E:\myaliyun\cicd_yamls\terraform\tfs" # Directory containing the tfs folder
  56. REMOTE_DIR = "/root/cicd_yamls/terraform" # Remote directory to upload files to
  57. print(f"\nUploading tfs folder from {LOCAL_DIR} to {SERVER_IP}:{REMOTE_DIR}\n")
  58. upload_tf_files(SERVER_IP, USERNAME, PASSWORD, LOCAL_DIR, REMOTE_DIR)
  59. if __name__ == "__main__":
  60. main()