[Python] Cannot establish SSH Connection with String Public Key in Python

Discussão em 'Python' iniciado por Stack, Abril 25, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to establish an SSH connection to a remote server with paramiko using a public key as a string and am getting a paramiko.ssh_exception.BadHostKeyException error.

    Here is the code I am using:

    import paramiko
    import base64
    from paramiko import RSAKey
    from base64 import decodebytes

    ssh = paramiko.SSHClient()

    hostname = "hostname"
    username = "user"
    password = "password"
    host_key = "AAAAB3NHKZ1FTmw+KBIe..."


    keyObj = RSAKey(data=decodebytes(host_key.encode()))
    ssh.get_host_keys().add(hostname=hostname, keytype="ssh-rsa", key=keyObj)
    ssh.connect(hostname = hostname, username = username, password = password)
    sftp = ssh.open_sftp()


    The error details indicate that my original host key is correct, but the RSA key that is passed changed in the process of decoding and encoding the string:

    Host key for server 'hostname' does not match: got 'AAAAB3NHKZ...', expected 'AAAAB3NHKZ1FTmw+KBIe...'

    Continue reading...

Compartilhe esta Página