Search code examples
pythonpython-3.xsftpparamikopysftp

Unable to connect to a clients SFTP using Python?


I have previously connected to a clients SFTP through vb.net script with WinSCP which has worked successfully however I don't want to use WinSCP. I am newish to Python but think for my overall goal for the project will be better suited using python.

What I believe I am missing is potentially a public key and/or my privatekey is in the wrong format. Would really appreciate some help on this as I have been stuck for days trying different things.

import pysftp

myHostname = 'sftp.name.com'
myUsername = 'username'
myPassword = 'password'
myKey = 'C:\\PrivateKey.ppk'

with pysftp.Connection(host=myHostname, username=myUsername, private_key=myKey, private_key_pass=myPassword) as sftp:

Error received
UserWarning: Failed to load HostKeys from C:\Users\name\.ssh\known_hosts.

Solution

  • The library is trying to find the known_hosts file to do a host key check. You can disable it, but as is written in the docs, it is strongly discouraged.

    import pysftp
    
    myHostname = 'sftp.name.com'
    myUsername = 'username'
    myPassword = 'password'
    myKey = 'C:\\PrivateKey.ppk'
    cnopts = pysftp.CnOpts()
    cnopts.hostkeys = None
    
    with pysftp.Connection(host=myHostname,
                           username=myUsername,
                           private_key=myKey,
                           private_key_pass=myPassword,
                           cnopts=cnopts) as sftp:
        pass
    

    A better way would be to set the known_hosts path using the CnOpts. I don't have a Windows machine, but based on this SA answer, maybe the following will work:

    import os
    import pysftp
    
    myHostname = 'sftp.name.com'
    myUsername = 'username'
    myPassword = 'password'
    myKey = 'C:\\PrivateKey.ppk'
    knownhosts_path = os.path.join(os.environ['USERPROFILE'], '.ssh', 'known_hosts')
    cnopts = pysftp.CnOpts(knownhosts=knownhosts_path)
    cnopts.hostkeys = None
    
    with pysftp.Connection(host=myHostname,
                           username=myUsername,
                           private_key=myKey,
                           private_key_pass=myPassword,
                           cnopts=cnopts) as sftp:
        pass