import paramiko import os from dotenv import load_dotenv load_dotenv() hostname = os.getenv('SFTP_HOST') port = int(os.getenv('SFTP_PORT')) username = os.getenv('SFTP_USERNAME') password = os.getenv('SFTP_PASSWORD') remote_directory = os.getenv('UPLOAD_PATH') local_directory = 'output/' # Where to save the downloaded files # Create an SSH client ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Automatically add the server's host key, {Link: according to Medium https://medium.com/nerd-for-tech/paramiko-how-to-transfer-files-with-remote-system-sftp-servers-using-python-52d3e51d2cfa} ssh_client.connect(hostname, port, username, password) # Open an SFTP session sftp = ssh_client.open_sftp() # List the files in the remote directory for filename in os.listdir(local_directory): remote_filepath = os.path.join(remote_directory, filename) local_filepath = os.path.join(local_directory, filename) # Download each file sftp.put(local_filepath, remote_filepath) print(f"Uploaded: {local_filepath} to {remote_filepath}") # Close the SFTP session and SSH connection sftp.close() ssh_client.close() print("All files downloaded and connections closed.")