1
votes

When attempting to use pysftp to retrieve/send a file from/to an SFTP server (over a dedicated connection), I'm attempting to disable hostkey checking but I'm still receiving a warning that pysftp is failing to load the hostkeys from the known_hosts file. Despite the warning, the file transfer process is completing as expected.

I know it's not best practice to skip key checking, but the host doesn't publish keys and it's communication taking place on a private network transferring pre-encrypted files so the risk is relatively low in this particular case.

That said, I've attempted to put an empty known_hosts file in the correct directory, only to get a more severe error.

The following sample code works just fine for me...except for the warning below.

import sys
import pysftp

hostname = "123.123.123.123"
username = "abc"       
password = "xyz"  

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None

with pysftp.Connection(hostname, username=username, password=password, cnopts=cnopts) as sftp:
    sftp.get('/test.get', preserve_mtime=True)
    sftp.put('test.put', preserve_mtime=True)

The following warning is generated when executing that script:

UserWarning: Failed to load HostKeys from C:\Users\eah036\.ssh\known_hosts.  
You will need to explicitly load HostKeys (cnopts.hostkeys.load(filename)) 
or disableHostKey checking (cnopts.hostkeys = None).
  warnings.warn(wmsg, UserWarning)

I could live with the warning messages being generated, but I'd sure prefer a clean terminal output when the code executes. Any thoughts on why the cnopts.hostkeys parameter appears to be being "ignored"?

1

1 Answers

0
votes

The warning cannot be suppressed, as of pysftp 0.2.9.

All you can do is to create an known_hosts file with at least one entry (it does not have to be a correct entry, just any entry with a valid syntax). You can create the file in either the standard location, or anywhere else, if you provide its path explicitly in CnOpts constructor.


Though, even if you cannot get the keys from a reliable source ("but the host doesn't publish keys"), using the public key that you get from the server at the time of developing the code is still way better than not verifying the key at all.

See my answer to Verify host key with pysftp.