Skip to content

Instantly share code, notes, and snippets.

@Kautenja
Last active March 4, 2020 21:21
Show Gist options
  • Save Kautenja/328c17e086b7719025a514b7b075d726 to your computer and use it in GitHub Desktop.
Save Kautenja/328c17e086b7719025a514b7b075d726 to your computer and use it in GitHub Desktop.
Simple SFTP functions using paramiko
"""Methods for working with files and remote hosts using SFTP."""
import paramiko
def sftp_get(hostname: str, username: str, remotepath: str, localpath: str):
"""
Read a file from a remote host using SFTP over SSH.
Args:
hostname: the remote host to read the file from
username: the username to login to the remote host with
remotepath: the path of the remote file to read
localpath: the path to write the remote file to
Returns:
None
"""
# open an SSH connection
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname, username=username)
# read the file using SFTP
sftp = client.open_sftp()
sftp.get(remotepath, localpath)
# close the connections
sftp.close()
client.close()
def sftp_put(hostname: str, username: str, localpath: str, remotepath: str):
"""
Put a file to a remote host using SFTP over SSH.
Args:
hostname: the remote host to put the file to
username: the username to login to the remote host with
localpath: the localhost path to read the file from
remotepath: the remote path to write the file to
Returns:
None
"""
# open an SSH connection
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname, username=username)
# read the file using SFTP
sftp = client.open_sftp()
sftp.put(localpath, remotepath)
# close the connections
sftp.close()
client.close()
# explicitly define the outward facing API of this module
__all__ = [
sftp_get.__name__,
sftp_put.__name__,
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment