Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
829 views
in Technique[技术] by (71.8m points)

python - "Failed to load HostKeys" warning while connecting to SFTP server with pysftp

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:UsersRohan.sshknown_hosts.  You will need to explicitly load HostKeys (cnopts.hostkeys.load(filename)) or disableHostKey checking (cnopts.hostkeys = None).
  warnings.warn(wmsg, UserWarning)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...