Python SFTP Script
This Python script uses paramiko to securely upload files from a specified local directory to an SFTP server. It establishes an SSH connection using a private key for authentication, iterates through
import paramiko
import os
# SFTP credentials and connection details
username = 'USERNAME_HERE'
host = 'SFTP_HOST_NAME_HERE'
private_key_path = 'PATH_TO_PRIVATE_RSA_KEY' # Update this with the path to your private key
# Directory containing files to upload
local_directory = './PATH_TO_FOLDER' # Update this with the path to the directory containing your files
def sftp_upload_files(local_directory):
# Create an SFTP client
try:
# Create SSH client
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Load the private key
private_key = paramiko.RSAKey.from_private_key_file(private_key_path)
# Connect to the SFTP server
ssh.connect(host, username=username, pkey=private_key)
# Open an SFTP session
sftp = ssh.open_sftp()
# Iterate over all files in the local directory
for filename in os.listdir(local_directory):
local_filepath = os.path.join(local_directory, filename)
if os.path.isfile(local_filepath):
try:
# Upload each file to the SFTP server
remote_filepath = f'./{filename}' # Adjust the remote path as needed
sftp.put(local_filepath, remote_filepath)
print(f'Successfully uploaded {filename} to {remote_filepath}')
except Exception as e:
print(f'Failed to upload {filename}: {e}')
# Close the SFTP session and SSH connection
sftp.close()
ssh.close()
except Exception as e:
print(f'Failed to connect to the SFTP server: {e}')
# Call the function to upload files
sftp_upload_files(local_directory)Key Points:
Last updated