PySFTP

0.2.9 · abandoned · verified Mon Apr 06

PySFTP is a Python library that provides a simplified, high-level interface for Secure File Transfer Protocol (SFTP) operations. It acts as a wrapper around the lower-level Paramiko library, aiming to make common SFTP tasks more approachable. The current version, 0.2.9, was released in July 2016, and the project appears to be unmaintained with no new releases since then.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish an SFTP connection using `pysftp.Connection` with a context manager, upload a local file, download a remote file, and list the contents of the current remote directory. It highlights the importance of host key verification, showing a common (but insecure for production) method to disable it for testing purposes. Credentials are retrieved from environment variables for security.

import pysftp
import os

# It is highly recommended to NOT disable host key checking in production.
# For proper security, manage known_hosts or explicitly add server keys.
cnopts = pysftp.CnOpts()
# !!! In production, configure hostkeys properly. DO NOT SET TO NONE. !!!
# For demonstration, we disable it here for easier local testing. 
cnopts.hostkeys = None 

HOSTNAME = os.environ.get('SFTP_HOSTNAME', 'sftp.example.com')
USERNAME = os.environ.get('SFTP_USERNAME', 'user')
PASSWORD = os.environ.get('SFTP_PASSWORD', 'secret_password')

try:
    with pysftp.Connection(host=HOSTNAME, username=USERNAME, password=PASSWORD, cnopts=cnopts) as sftp:
        print(f"Connection successfully established with {HOSTNAME}!")
        print(f"Current remote directory: {sftp.pwd}")

        # Example: Upload a file
        local_file = 'local_test_file.txt'
        remote_path = f'/remote/{local_file}'
        with open(local_file, 'w') as f:
            f.write('Hello, SFTP World!')

        sftp.put(local_file, remote_path)
        print(f"Uploaded {local_file} to {remote_path}")

        # Example: Download a file
        downloaded_file = 'downloaded_test_file.txt'
        sftp.get(remote_path, downloaded_file)
        print(f"Downloaded {remote_path} to {downloaded_file}")

        # Example: List remote directory
        print(f"Files in remote directory {sftp.pwd}:")
        for entry in sftp.listdir():
            print(f"- {entry}")

except pysftp.ConnectionException as e:
    print(f"SFTP connection failed: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
finally:
    # Clean up local test file if it was created
    if os.path.exists(local_file):
        os.remove(local_file)
    if os.path.exists(downloaded_file):
        os.remove(downloaded_file)

view raw JSON →