Created
November 14, 2025 00:14
-
-
Save cgoldberg/04c0d214880a41a556242a000a02909a to your computer and use it in GitHub Desktop.
Python - transferring files with SFTP using paramiko
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| # | |
| # transferring files with SFTP | |
| # https://www.paramiko.org | |
| import paramiko | |
| class SFTP: | |
| def __init__(self, host, user, password, port=22): | |
| self.host = host | |
| self.user = user | |
| self.password = password | |
| self.port = port | |
| self.sftp = None | |
| self._ssh = paramiko.SSHClient() | |
| self._ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) | |
| def __enter__(self): | |
| print(f"Connecting to server: {self.host}") | |
| self._ssh.connect( | |
| hostname=self.host, | |
| port=self.port, | |
| username=self.user, | |
| password=self.password, | |
| ) | |
| self.sftp = self._ssh.open_sftp() | |
| return self.sftp | |
| def __exit__(self, exc_type, exc_value, traceback): | |
| if self.sftp: | |
| self.sftp.close() | |
| if self._ssh: | |
| self._ssh.close() | |
| print("Connection closed.") | |
| # example usage | |
| if __name__ == "__main__": | |
| with SFTP("some-ftp-site.com", "username", "secret") as sftp: | |
| for file in sftp.listdir(): | |
| print(f" - {file}") | |
| sftp.get("example.txt") | |
| sftp.put("example.txt") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment