在Google Colab中使用Paramiko加载SSH密钥报错:OpenSSH私钥校验值不匹配
问题:Colab中使用Paramiko加载OpenSSH私钥报错"checkints do not match"
我正尝试从Google Colab建立SSH隧道连接到远程Linux服务器上的MySQL实例,服务器要求用SSH密钥而非密码连接。该密钥在本地机器上可正常连接服务器、建立隧道并访问MySQL,但在Colab中配置时,使用Paramiko加载存储在Google Drive中的id_rsa私钥时出现错误:SSHException: OpenSSH private key file checkints do not match。
配置代码
#Import Modules Needed to connect to server and mysql !pip install paramiko import paramiko from paramiko import SSHClient import ssl !pip install sshtunnel import sshtunnel from sshtunnel import SSHTunnelForwarder !pip install pymysql import pymysql import logging #set up access to drive from google.colab import drive #mount google drive drive.mount('/content/drive/') #get glob to work with files in drive import glob #get the shh key files from drive (private and file with ssh key file) sshfolder_files = glob.glob('drive/MyDrive/.ssh/*') for file_path in sshfolder_files: if 'pass.txt' in file_path: passfile_path = file_path if 'id_rsa' in file_path and 'pub' not in file_path: id_rsa_path = file_path #get the pass for the id_rsa private key passfile = open(passfile_path, "r") passcode = passfile.read() #set up the key so it can be used to to the the server mypkey = paramiko.RSAKey.from_private_key_file(id_rsa_path, passcode) # <-- 报错位置
错误信息
/usr/local/lib/python3.10/dist-packages/paramiko/pkey.py in _read_private_key_openssh(self, lines, password) 664 665 if checkint1 != checkint2: --> 666 raise SSHException( 667 "OpenSSH private key file checkints do not match" 668 ) SSHException: OpenSSH private key file checkints do not match
解决方案
转换私钥格式:Paramiko对新版OpenSSH格式私钥(开头为
-----BEGIN OPENSSH PRIVATE KEY-----)兼容性不佳,将私钥转换为传统PEM格式后重新上传到Drive。在本地终端执行:ssh-keygen -p -m PEM -f ~/.ssh/id_rsa执行时输入原密码,完成格式转换。
验证私钥完整性:检查Drive中的id_rsa文件是否损坏,比如上传时丢失换行符。在Colab中添加代码打印文件内容,和本地私钥对比:
with open(id_rsa_path, 'r') as f: print(f.read())处理密码换行符:
passfile.read()会读取文件中的换行符,导致密码验证失败,添加strip()处理:passcode = passfile.read().strip()换用SSHClient直接加载密钥:尝试用Paramiko的SSHClient类直接连接,绕过单独加载密钥的步骤:
ssh = SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect( hostname="你的服务器IP", username="你的用户名", key_filename=id_rsa_path, password=passcode.strip() )
内容的提问来源于stack exchange,提问作者Francisco Cortes
相关产品推荐
相关产品推荐

