paramiko 主机密钥问题 - BadHostKeyException

问题描述 投票:0回答:1

这是我用来连接到 SFTP 服务器的脚本。

sftp.pem
host.pem
是OpenSSH格式的私钥。我自己创建了用户并将主机密钥添加到服务器。

我使用这种方法不断收到错误(请参阅下面的错误消息)。添加

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
就可以成功登录。但我的理解是这不是一个好的做法。

使用私钥连接SFTP服务器的正确方法是什么?

import paramiko


private_key_path = "./sftp.pem"
host_key_path = "./host.pem"
client = paramiko.SSHClient()
hostname = '##.###.##.#'
username = 'username'

key_obj = paramiko.RSAKey(filename=host_key_path)
client.get_host_keys().add(hostname, "ssh-rsa", key_obj)

client.connect(hostname=hostname,
               username=username,
               key_filename=private_key_path)

错误

paramiko.ssh_exception.BadHostKeyException:服务器的主机密钥 '##.###.##.#' 不匹配:得到 'AAAAB3NzaC1yc2EAAAADAQABAAABAQ...+jCkEL',预期 'AAAAB3NzaC1yc2EAAAADAQABAAABAQ...feZ6l'

python paramiko
1个回答
0
投票

似乎对于paramiko.RSAKey的使用可能存在误解。 paramiko.RSAKey 类通常用于客户端的私钥,而不是服务器的主机密钥。如果要指定客户端的私钥,则应直接在

connect
方法中使用 key_filename 参数。

这里

import paramiko

private_key_path = "./sftp.pem"
hostname = '##.###.##.#'
username = 'username'

client = paramiko.SSHClient()

# Load the private key for the client
private_key = paramiko.RSAKey(filename=private_key_path)

# Automatically add the server's host key (this is not recommended for production)
# client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# Connect to the SFTP server
client.connect(
    hostname=hostname,
    username=username,
    pkey=private_key  # Use the private key for authentication
)

# Now you can perform SFTP operations using the 'client' object

# Close the connection when done
client.close()

connect方法中的这个pkey参数直接指定客户端的私钥。另请注意,set_missing_host_key_policy 行已被注释掉。虽然在开发过程中使用 AutoAddPolicy 很方便,但不建议在生产环境中使用它,因为它会使客户端面临潜在的中间人攻击。

确保

sftp.pem 对应于您尝试在 SFTP 服务器上进行身份验证的用户。如果您仍然遇到问题,请仔细检查私钥和服务器主机密钥是否正确。

© www.soinside.com 2019 - 2024. All rights reserved.