SFTP mit Python und der Paramiko-Bibliothek – Download
Aktuell benötige ich Funktionen, um mit Python Dateien von SFTP Servern zu holen bzw. Dateien auf diese hochzuladen. Chat GPT hatte folgenden Code für mich, der sehr gut funktioniert.
import os import paramiko # Replace these variables with your specific values host = '192.168.0.238' port = 22 username = '<user>' private_key_path = '<keyfile>' remote_directory_path = '/home/uwe/downloadtest' local_directory_path = 'E:/downloadtest' # Establish SSH connection try: # Create a new SSH client ssh_client = paramiko.SSHClient() # Automatically add the server's host key ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Load the private key for authentication private_key = paramiko.RSAKey.from_private_key_file(private_key_path) # Connect to the server ssh_client.connect(hostname=host, port=port, username=username, pkey=private_key) # Open an SFTP session on the SSH connection sftp = ssh_client.open_sftp() # Change to the remote directory sftp.chdir(remote_directory_path) # List all files in the remote directory files = sftp.listdir() # Download each CSV file in the remote directory for file_name in files: # os path join uses system slashes, must make sure they are right remote_file_path = os.path.join(remote_directory_path, file_name).replace("\\","/") local_file_path = os.path.join(local_directory_path, file_name).replace("\\","/") print(remote_file_path, local_file_path) # Check if the file is a CSV file if file_name.lower().endswith('.txt'): sftp.get(remote_file_path, local_file_path) print(f"File '{file_name}' downloaded successfully to '{local_directory_path}'") # Close the SFTP session and SSH connection sftp.close() ssh_client.close() except paramiko.AuthenticationException: print("Authentication failed. Please check your credentials or SSH key path.") except paramiko.SSHException as e: print(f"SSH connection failed: {e}") except FileNotFoundError: print("File not found. Please provide the correct file paths.") except Exception as e: print(f"An error occurred: {e}") |