Python (Scripting) - SFTP using paramiko

by
Jeremy Canfield |
Updated: August 25 2024
| Python (Scripting) articles
paramiko can be used to:
- SSH connect to a target system
- SCP files on a target system
- SFTP connect to a target system (this article)
At the bare minimum, the following is all that should be needed to make an SFTP connection if the SFTP server accepts basic authentication (username, password).
#!/usr/bin/python3
import paramiko
host = "server1.example.com"
port = 22
username = "john.doe"
password = "itsasecret"
transport = paramiko.Transport((host,port))
transport.connect(None,username,password)
sftp = paramiko.SFTPClient.from_transport(transport)
stat = sftp.stat("/tmp/bar.txt")
print(f"info.st_atime = {info.st_atime}")
print(f"info.st_mtime = {info.st_mtime}")
if sftp:
sftp.close()
if transport:
transport.close()
Or, better yet, using a function and error handling.
#!/usr/bin/python3
import paramiko
def sftp_connect(host, port, username, pw):
transport = paramiko.Transport((host,port))
transport.connect(None,username,pw)
sftp = paramiko.SFTPClient.from_transport(transport)
return transport, sftp
try:
transport, sftp = sftp_connect('server1.example.com', 22, 'john.doe', 'itsasecret')
except Exception as exception:
print(f"got the following exception - {exception}")
else:
stat = sftp.stat("/tmp/bar.txt")
print(f"info.st_atime = {info.st_atime}")
print(f"info.st_mtime = {info.st_mtime}")
if sftp:
sftp.close()
if transport:
transport.close()
Did you find this article helpful?
If so, consider buying me a coffee over at