Bootstrap FreeKB - Python (Scripting) - SFTP using paramiko
Python (Scripting) - SFTP using paramiko

Updated:   |  Python (Scripting) articles

paramiko can be used to:

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 Buy Me A Coffee



Comments


Add a Comment


Please enter ae8961 in the box below so that we can be sure you are a human.