Looking for an example to load/use a public ssh key with pysftp

Michael Linde picture Michael Linde · Apr 12, 2017 · Viewed 7.3k times · Source

I am working on a script in python using pysftp to establish an sftp connection. This script will run in Windows (Server 2012R2). The version of pysftp I have installed requires a host key, so I contacted my vendor and have acquired the public key from them. What I can't figure out is how to use this public key in my pysftp connection. I understand in pysftp 0.2.9 there is a new property (remote_server_key) but I can't find any examples of how to use it, and I can't use cnopts.hostkeys = none

Does anyone have an example of how to use/integrate a specific public key for the sftp server/host?

Please note this is not about the private key/public pair for my connection (I have those keys and they work fine) - this is about the host's public key.

Answer

Zest picture Zest · Aug 13, 2020

Please note that the .pem file format should be like the below one (I generated it via puttygen)

-----BEGIN RSA PRIVATE KEY-----
MIIEog***********************************************
*****************************************************
-----END RSA PRIVATE KEY-----

Use the below code to perform the transfer.

import pysftp
hostname = 's-ad7**********.server.transfer.us-east-1.amazonaws.com'
username = '***'
path = 'C:\\keys\\<your_private_key_file>.pem'
def sftptransfer():
    cnopts = pysftp.CnOpts()
    cnopts.hostkeys = None  
    with pysftp.Connection(hostname, username=username, private_key=path, cnopts=cnopts) as sftp:
        sftp.put('<path of input file>', '<target directory path>') # target dirctory path is optional
        sftp.close()

sftptransfer()