升级Paramiko至2.9.0+后连接报错‘Private key file is encrypted’求助
Paramiko 2.9.0+ RSA密钥连接报错PasswordRequiredException的解决方法
问题背景
以下代码在Paramiko 2.8.1版本可正常运行,但升级到2.9.0及以上版本后,会抛出paramiko.ssh_exception.PasswordRequiredException: Private key file is encrypted异常,而SFTP主机、用户及密钥均未变更:
pkey = paramiko.RSAKey.from_private_key(pkey_str) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.WarningPolicy()) ssh.connect(host, port=int(port), username=username, pkey=pkey) return ssh.open_sftp()
已尝试但无效的操作
查阅Paramiko 2.9.0版本更新日志,得知需在SSHClient或Transport中指定disabled_algorithms={'keys': ['rsa-sha2-256', 'rsa-sha2-512']},但添加该配置后问题仍未解决:
# 依旧抛出相同的加密密钥异常 key_cfg = {'keys': ['rsa-sha2-256', 'rsa-sha2-512']} ssh.connect(host, port=int(port), username=username, pkey=pkey, disabled_algorithms=key_cfg)
可行解决方向
检查密钥加载逻辑:
- 如果私钥本身是加密状态,旧版本Paramiko校验逻辑较宽松,新版本需显式传入密钥密码:
pkey = paramiko.RSAKey.from_private_key(pkey_str, password="你的密钥密码") - 若密钥未加密,尝试改用
from_private_key_file方法加载本地密钥文件,规避字符串流加载可能出现的格式问题。
- 如果私钥本身是加密状态,旧版本Paramiko校验逻辑较宽松,新版本需显式传入密钥密码:
调整加密算法禁用时机:
不在connect方法中直接传入disabled_algorithms,先初始化Transport并配置算法规则,再绑定到SSHClient:ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.WarningPolicy()) transport = paramiko.Transport((host, int(port))) transport.disabled_algorithms = {'keys': ['rsa-sha2-256', 'rsa-sha2-512']} transport.connect(username=username, pkey=pkey) ssh._transport = transport return ssh.open_sftp()核对服务器支持的算法:
使用ssh -v user@host命令查看SFTP服务器支持的密钥算法列表,确保禁用的算法确实是服务器端不兼容的项,再调整disabled_algorithms的配置内容。
内容的提问来源于stack exchange,提问作者Kache
相关产品推荐
相关产品推荐

