Typing stubs for pysftp
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
-
ImportError: cannot import name 'DSSKey' from 'paramiko'
cause `pysftp` attempts to import `DSSKey` from `paramiko`, but this class was removed in `paramiko` version 4.0.0 and newer.fixDowngrade `paramiko` to a version older than 4.0.0 (e.g., `pip install 'paramiko<4.0.0'`). -
pysftp.exceptions.ConnectionException: ('your.sftp.host', 22)cause This usually indicates a failure to connect to the SFTP server. Common causes include incorrect hostname, wrong port (default is 22), firewall blocking the connection, or invalid credentials (username/password/private key).fixVerify the hostname and port. Check firewall rules. Confirm your SFTP credentials are correct. Try connecting manually with a client like FileZilla to isolate the issue. If using a private key, ensure the path is correct and permissions are set appropriately. -
UserWarning: Failed to load HostKeys from ~/.ssh/known_hosts. You will need to explicitly load HostKeys (cnopts.hostkeys.load(filename)) or disable HostKey checking (cnopts.hostkeys = None).
cause pysftp cannot find or verify the host's key in your known_hosts file, which is a security measure to prevent man-in-the-middle attacks.fixFor production, ensure the server's fingerprint is correctly added to your `known_hosts` file. For testing/development, you can bypass this by explicitly disabling host key checking: `cnopts = pysftp.CnOpts(); cnopts.hostkeys = None`. Pass `cnopts` to your `pysftp.Connection` constructor.
Warnings
- breaking `pysftp` is incompatible with `paramiko` versions 4.0.0 and above. Attempting to use `pysftp` with `paramiko>=4.0.0` will result in an `ImportError` due to `DSSKey` being removed from `paramiko`.
- gotcha By default, `pysftp` performs host key verification, which can lead to 'No hostkey for host X found' errors if the server's host key is not in `~/.ssh/known_hosts` or a specified `HostKeys` object.
- deprecated The `pysftp` library itself appears to be largely unmaintained, with its last PyPI release (0.2.9) dating back to 2016. While `types-pysftp` (from typeshed) continues to be updated, the underlying `pysftp` library may not receive future bug fixes or security updates.
Install
-
pip install types-pysftp -
pip install pysftp
Imports
- Connection
from pysftp import Connection
import pysftp conn = pysftp.Connection(...)
Quickstart
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}")