SFTP Guide¶
The SSH File Transfer Protocol (SFTP) provides secure file transfer capabilities over SSH connections. This guide covers all aspects of using SFTP with SpindleX.
Basic SFTP Operations¶
Opening SFTP Connection¶
File Transfer Operations¶
Uploading Files¶
Downloading Files¶
Directory Operations¶
Listing Directories¶
Creating and Removing Directories¶
File Attributes and Permissions¶
Reading File Attributes¶
import stat
with client.open_sftp() as sftp:
attrs = sftp.stat('/remote/file.txt')
print(f"File size: {attrs.st_size} bytes")
print(f"Permissions: {oct(attrs.st_mode)}")
Setting File Permissions¶
SFTP Server¶
In addition to the client, SpindleX provides an SFTPServer implementation that can be used within an SSHServer to provide secure file access.
Implementing an SFTP Server¶
To enable SFTP in your custom SSH server, you need to handle the "sftp" subsystem request.
from spindlex.server import SSHServer, SFTPServer
class MyServer(SSHServer):
def check_channel_subsystem_request(self, channel, name):
if name == "sftp":
# root_path defines the base directory for SFTP clients
handler = SFTPServer(channel, root_path="/srv/sftp/data")
return True
return False
The SFTPServer handler will automatically process all SFTP packets (reading, writing, directory listing, etc.) relative to the specified root_path.
Best Practices¶
Security Considerations¶
- Use secure authentication: Prefer public key over password.
- Validate file paths: Prevent directory traversal attacks.
- Set proper permissions: Use restrictive file permissions.
- Implement access controls: Limit user access to specific directories.
Performance Tips¶
- Use appropriate chunk sizes: Balance memory usage and performance.
- Use concurrent transfers: For multiple files using
asyncio.gather. - Clean up resources: Always use context managers to close SFTP sessions and files.