Paramiko - Module of the Month


In [ ]:
# connect to localhost as an sftp user

from paramiko.client import SSHClient

client = SSHClient()
client.load_system_host_keys()
client.connect('localhost', username='sftpguest', password='sftpguest')

sftp = client.open_sftp()

In [ ]:
# connecting with a private key
# I did not setup an actual key for this user
# so this is just for display

import paramiko

# There is also DSAKey
key = paramiko.RSAKey.from_private_key_file('/Users/sftpguest/.ssh/id_rsa')
# possibly also paramiko.RSAKey('/Users/sftpguest/.ssh/id_rsa')
transport = paramiko.Transport('hostname')
transport.connect('sftpguest', key)
client = paramiko.SFTPClient.from_transport(transport)

Basic SFTP operations


In [ ]:
# SFTP commands

sftp.listdir()

In [ ]:
sftp.listdir(path='Documents')

In [ ]:
sftp.stat('a-file')

In [ ]:
sftp.normalize(path='a-file')

Remote File Operation


In [ ]:
a_file = sftp.open('a-file', 'r')
print(a_file.read().decode())
a_file.close()

In [ ]:
a_file = sftp.open('a-file', 'a')
a_file.write("let's add another line!\n")
a_file.close()

Moving Things Around


In [ ]:
import os

os.listdir('./small')

In [ ]:
sftp.get('a-file', './small/a-file')

os.listdir('./small')

In [ ]:
sftp.put('paramiko-motm.ipynb', 'small/paramiko-notebook')
sftp.listdir('small')

In [ ]:
sftp.remove('small/paramiko-notebook')
sftp.listdir('small')