"Failed to load HostKeys" warning while connecting to SFTP server with pysftp
Asked Answered
G

3

6

I wrote a Python script to connect to SFTP server using key authentication. It connects to server successfully but shows the following warning (see below). What does it mean and how to remove it. What changes has to made in code?

My code:

import os
import pysftp
import socket
import paramiko
import time
import os.path
import shutil

IP = "127.0.X.X"
myUsername = "USERNAME"
port = 22

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

import os
privatekeyfile = os.path.expanduser("C:\\Users\\Rohan\\.ssh\\cool.prv")
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)

try:
    with pysftp.Connection(host=IP, username=myUsername,private_key=mykey,cnopts=cnopts) as sftp:
        try:
            r=str(socket.gethostbyaddr(IP))
            print("connection successful with "+r)

        except socket.herror:
            print("Unknown host")
except:
    print("connection failed")

Warning:

UserWarning: Failed to load HostKeys from C:\Users\Rohan\.ssh\known_hosts.  You will need to explicitly load HostKeys (cnopts.hostkeys.load(filename)) or disableHostKey checking (cnopts.hostkeys = None).
  warnings.warn(wmsg, UserWarning)
Giule answered 10/6, 2019 at 6:34 Comment(0)
C
4

I believe it's a bug in pysftp. You get this everytime you use cnopts.hostkeys = None (despite the warning actually suggesting to use that).

Anyway, you should not use cnopts.hostkeys = None, you lose security by doing so.
For the correct solution, see Verify host key with pysftp.


By your reference to key authentication, I assume you mistake your account key with host key. Read my article about SSH key pairs to understand the difference.

Celestyna answered 10/6, 2019 at 7:33 Comment(0)
F
6

Also I am using version 0.2.9 and have the same issue. If your only concern is the warning message (that in my case keeps showing up also explicitly setting hostkeys = none) and you only want to get rid of it without messing with the code of the module, you can use the appropiate method filterwarnings of the module warnings that's used for print the message.
This will suppress all the warnings

import warnings
warnings.filterwarnings('ignore')

This instead will suppress all the warning messages that begin with "Failed to load HostKeys" that, i believe, is only that one that is happening in this case:

import warnings
warnings.filterwarnings('ignore','.*Failed to load HostKeys.*')
Farly answered 18/11, 2021 at 23:16 Comment(0)
C
4

I believe it's a bug in pysftp. You get this everytime you use cnopts.hostkeys = None (despite the warning actually suggesting to use that).

Anyway, you should not use cnopts.hostkeys = None, you lose security by doing so.
For the correct solution, see Verify host key with pysftp.


By your reference to key authentication, I assume you mistake your account key with host key. Read my article about SSH key pairs to understand the difference.

Celestyna answered 10/6, 2019 at 7:33 Comment(0)
M
4

It's a bug in the latest pysftp, even though you set CnOpts.hostkeys = None, just the act of instantiating CnOpts() makes pysftp look for the known_hosts file and then raise the warning if it's not found. So I just went in the code and commented out the warning and threw in some passes. I didn't have a choice because the warning messages were causing errors downstream. The point is you can implement your own clever solution here:

##C:\Python38\Lib\site-packages\pysftp\__init__.py


class CnOpts(object):   # pylint:disable=r0903
        def __init__(self, knownhosts=None):
            self.log = False
            self.compression = False
            self.ciphers = None
            if knownhosts is None:
                knownhosts = known_hosts()
            self.hostkeys = paramiko.hostkeys.HostKeys()
            try:
                self.hostkeys.load(knownhosts)
            except IOError:
                # can't find known_hosts in the standard place
                # wmsg = "Failed to load HostKeys from %s.  " % knownhosts
                # wmsg += "You will need to explicitly load HostKeys "
                # wmsg += "(cnopts.hostkeys.load(filename)) or disable"
                # wmsg += "HostKey checking (cnopts.hostkeys = None)."
                # warnings.warn(wmsg, UserWarning)
                pass
            else:
                pass
                # if len(self.hostkeys.items()) == 0:
                    # raise HostKeysException('No Host Keys Found')
Memberg answered 26/2, 2021 at 22:2 Comment(3)
hey is this for pysftp version 0.2.9?Siderolite
@Siderolite - yeah that's the version I'm using. Again, this is a hack, but I had to get rid of that warning as it was causing an issue.Memberg
But make sure you understand that you should not use this to allow you to set CnOpts.hostkeys = None without getting a warning. You should not set hostkeys = None. That's a security flaw.Celestyna

© 2022 - 2024 — McMap. All rights reserved.