无法使用 paramiko 将 SSH 连接到 Google Compute Engine 实例

Can't connect SSH with paramiko to a Google Compute Engine instance

我在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: Private key file is encrypted

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

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

我用于访问的 SSH 密钥 Google 计算引擎没有密码。我可以使用 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 而不是发送密码参数。结果总是和上面一样的错误。

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

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

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

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