【问题标题】:Can't connect SSH with paramiko to a Google Compute Engine instance无法使用 paramiko 将 SSH 连接到 Google Compute Engine 实例
【发布时间】:2018-02-25 03:03:36
【问题描述】:

我在SO中发现了很多类似的问题,但其中任何一个都帮助了我,甚至这个问题似乎很简单。

我正在尝试使用 paramiko 通过 SSH(我想使用 SFTP)连接到远程 Google Compute Engine 实例。以下是我的代码:

        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.connect('External_IP_Get_In_GCE_panel', username='myuser')
        stdin, stdout, stderr = client.exec_command('ls')
        for line in stdout:
            print('... ' + line.strip('\n'))
        client.close()

使用此代码,我有错误

PasswordRequiredException: 私钥文件已加密

当我尝试client.connect('External_IP_Get_In_GCE_panel', username='myuser', password='') 时,错误是:

BadAuthenticationType: ('Bad authentication type', [u'publickey']) (allowed_types=[u'publickey'])

我用于访问 Google Compute 引擎的 SSH 密钥没有密码。我可以使用gcloud compute ssh instance-name,也可以毫无问题地通过 Filezilla 访问 SFTP。

正如我所说,我尝试了很多在 SO 中找到的替代方案,但其中任何一个都对我有帮助。以下是其他 3 个版本的代码:

使用钥匙

    key = paramiko.RSAKey(data=base64.b64decode(b"""AAAAB3Nza..."""))
    client = paramiko.SSHClient()
    client.get_host_keys().add('External_IP_Get_In_GCE_panel', 'ssh-rsa', key)
    client.connect('External_IP_Get_In_GCE_panel', username='myuser', password='')
    # I got the key using ssh-keyscan `External_IP_Get_In_GCE_panel`in my local machine

使用另一个库

    key = paramiko.RSAKey(data=decodebytes(keydata))
    cnopts = pysftp.CnOpts()
    cnopts.hostkeys.add('External_IP_Get_In_GCE_panel', 'ssh-rsa', key)

    with pysftp.Connection('External_IP_Get_In_GCE_panel', username='myuser', cnopts=cnopts) as sftp:
        with sftp.cd('../directory'):
            sftp.get('remote_file')'''

使用 ssh 密钥文件

    self.client = paramiko.SSHClient()
    self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    self.client.connect(hostname="External_IP_Get_In_GCE_panel", username="myuser", key_filename=os.path.expanduser('~/.ssh/ssh_key_file'), password='') # also tried ssh_key_file.pub

在所有这些版本(和其他一些版本)中,我尝试使用 password=''password=None 并且不发送密码参数。结果总是和上面一样。

关于我做错了什么的任何提示?

【问题讨论】:

    标签: python ssh google-compute-engine sftp paramiko


    【解决方案1】:

    密钥已加密,您需要decrypt the private key 的密码(并且可能非空),即

    key = paramiko.RSAKey(data=base64.b64decode(b"""AAAAB3Nza..."""), password='my key password')
    

    那里的服务器只允许公钥认证,所以将passwordclient.connect 没有任何意义。

    【讨论】:

    • 正如我所说,SSH密钥是在没有密码的情况下创建的,所以我没有任何东西可以填充这个参数,password='' 带有空白字符串会引发与加密私钥相同的错误。
    • @James 它似乎有密码 - 也许您将“无密码”与“sshagent 记住密码”混淆了
    • @James 或尝试使用空密码调用RSAKey
    • 我创建了密钥并且没有为密码输入任何内容,所以我很确定这个密钥没有密码。无论如何,我会尝试您的解决方案,并可能创建一个带有密码的新密钥以避免此类问题。感谢您的帮助。
    最近更新 更多