Home > Software engineering >  I can't connect to a server with pysftp
I can't connect to a server with pysftp

Time:06-24

I would like to read files on a remote server using pysftp. For this I generated an ssh key on the server I want to connect to and added the public key to my code. It worked fine before I changed my VM (debian 10). Now I have as error :

"SSHException: Bad host key from server"

If someone has an idea it would help me a lot !

Here is my code :

from base64 import decodebytes
import os
import pysftp 
import paramiko

host = os.getenv('host')
username = os.getenv('username')
password = os.getenv('password')

#public key
keydata = bytes(os.getenv('key'),'UTF-8')
key = paramiko.RSAKey(data=decodebytes(keydata))
cnopts = pysftp.CnOpts()
cnopts.hostkeys.add(host,'ssh-rsa', key)

with pysftp.Connection(host=host, username=username, password=password, cnopts=cnopts, port=22) as sftp:
    sftp.cwd('/home/user/') 
    for attr in sftp.listdir(): 
        print(attr)

CodePudding user response:

You can debug this in following ways:

  • Check if your key have any white spaces at the beginning or at the end.
  • Then ssh to that server with your key directly from terminal make sure you use -v option to verbose logs.
  • Check /etc/ssh/sshd_config if sftp is allowed or not (good approach is to have diffrent sftp user for secure communication).

Thanks

  • Related