SFTP Client with Paramiko
This guide demonstrates how to transfer files securely using SFTP (SSH File Transfer Protocol). Unlike standard FTP, SFTP encrypts both commands and data. This script uses the paramiko library, which is the standard for SSH/SFTP in Python.
Modules Used:
paramiko: Implementation of the SSHv2 protocol.- argparse: To handle command-line arguments.
Installation
pip install paramiko
The Code
Save this as sftp_tool.py.
import paramiko
import argparse
import os
import sys
def sftp_transfer(host, user, password, local_path, remote_path, action):
# 1. Initialize SSH Transport
try:
print(f"Connecting to {host}...")
transport = paramiko.Transport((host, 22))
transport.connect(username=user, password=password)
# 2. Create SFTP Client
sftp = paramiko.SFTPClient.from_transport(transport)
print("Connection established.")
# 3. Perform Action
if action == "upload":
if not os.path.exists(local_path):
print(f"Error: Local file '{local_path}' not found.")
return
print(f"Uploading {local_path} -> {remote_path}...")
sftp.put(local_path, remote_path)
print("Upload complete.")
elif action == "download":
print(f"Downloading {remote_path} -> {local_path}...")
try:
sftp.get(remote_path, local_path)
print("Download complete.")
except FileNotFoundError:
print(f"Error: Remote file '{remote_path}' not found.")
# 4. Close Connection
sftp.close()
transport.close()
except paramiko.AuthenticationException:
print("Authentication failed. Check credentials.")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="SFTP File Transfer Tool")
parser.add_argument("host", help="SFTP Server Address")
parser.add_argument("user", help="Username")
parser.add_argument("password", help="Password")
parser.add_argument("action", choices=["upload", "download"], help="Action to perform")
parser.add_argument("local", help="Local file path")
parser.add_argument("remote", help="Remote file path")
args = parser.parse_args()
sftp_transfer(args.host, args.user, args.password, args.local, args.remote, args.action)
Usage
# Upload a file
python sftp_tool.py example.com myuser mypass upload ./index.html /var/www/html/index.html
# Download a log file
python sftp_tool.py example.com myuser mypass download ./error.log /var/log/apache2/error.log