Typing stubs for pysftp

0.2.17.20260408 · active · verified Thu Apr 16

types-pysftp provides PEP 561 compliant type stubs for the pysftp library, a simple interface for SFTP operations based on paramiko. It allows type checkers to analyze code utilizing pysftp, improving code quality and catching potential errors during development. The current version is 0.2.17.20260408, with releases tied to the typeshed project's update cadence for pysftp==0.2.*.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish an SFTP connection using pysftp, list remote directory contents, upload a file, and download a file. It uses environment variables for credentials and explicitly disables host key checking for simplicity, though this is not recommended for production environments. The Connection object is used as a context manager to ensure the SFTP session is properly closed.

import pysftp
import os

hostname = os.environ.get('SFTP_HOSTNAME', 'your.sftp.host')
username = os.environ.get('SFTP_USERNAME', 'your_username')
password = os.environ.get('SFTP_PASSWORD', '')
private_key_path = os.environ.get('SFTP_PRIVATE_KEY_PATH', None) # e.g., '~/.ssh/id_rsa'

# Recommended: configure known hosts for security
# For testing, host key checking can be disabled (NOT RECOMMENDED for production)
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None # Disable host key checking for demonstration only

try:
    with pysftp.Connection(
        hostname, 
        username=username,
        password=password if not private_key_path else None,
        private_key=private_key_path,
        cnopts=cnopts
    ) as sftp:
        print(f"Connection successfully established with {hostname}.")
        # Example: List contents of the remote directory
        remote_path = '/'
        print(f"Listing contents of {remote_path}:")
        for entry in sftp.listdir(remote_path):
            print(f"- {entry}")

        # Example: Upload a file (create a dummy file first)
        local_file = 'test_upload.txt'
        with open(local_file, 'w') as f:
            f.write('Hello from types-pysftp!')
        remote_upload_path = f"/remote_{local_file}"
        sftp.put(local_file, remote_upload_path)
        print(f"Uploaded {local_file} to {remote_upload_path}.")
        os.remove(local_file)

        # Example: Download a file
        local_download_path = 'downloaded_file.txt'
        sftp.get(remote_upload_path, local_download_path)
        print(f"Downloaded {remote_upload_path} to {local_download_path}.")
        os.remove(local_download_path)

except pysftp.ConnectionException as e:
    print(f"SFTP Connection Error: {e}.")
    print("Ensure hostname, username, password/private key are correct and host keys are properly handled.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →