SFTP is also known as the SSH File Transfer Protocol. It is a network protocol that provides file access, file transfer, and file management over any reliable data stream.
Python pysftp module is a simple interface to SFTP. It offers high-level abstractions and task-based routines to handle SFTP needs.
However, the SFTP protocol does not support authentication and security; it expects the underlying protocol to secure it.
As a result, the SFTP is most widely used as an SSH protocol version 2 implementation subsystem designed by the same working group.
Here is the command to install the pysftp module:
pip install pysftp
# or
python3 -m pip install pysftp
Here is the code example:
import pysftp
# Define the connection parameters
hostname = 'your_sftp_server.com'
username = 'your_username'
password = 'your_password' # or use a private key
# Connect to the server
with pysftp.Connection(host=hostname, username=username, password=password) as sftp:
print("Connection successfully established ... ")
# Switch to a remote directory
sftp.cwd('/path/to/remote/directory')
# Obtain structure of the remote directory '/path/to/remote/directory'
directory_structure = sftp.listdir_attr()
# Print data
for attr in directory_structure:
print(attr.filename, attr)
# Upload a file
# sftp.put('/path/to/local/file', 'remote_filename')
# Download a file
# sftp.get('remote_filename', '/path/to/local/file')
# Connection closed automatically at the end of the with-block
Please replace ‘your_sftp_server.com’, ‘your_username’, ‘your_password’, and the directory paths with your actual SFTP server details and the file paths you want to interact with.
Always put credentials inside the environment variables file. For example, the .env file.
You can perform various operations such as file uploads, downloads, checks, and even more granular file and directory manipulations.
Always refer to the official pysftp documentation for more details on what you can do with the library.