无法连接到 GCP VM 权限被拒绝(公钥)错误

Can't connect to GCP VM Permission denied (publickey) error

我正在创建一个新的 VM 实例。我已经清理了所有元数据。然后我在云端运行以下命令shell:

gcloud beta compute ssh --zone "europe-west2-c" "vmname"  --project "myprojectname"

然后我一直要求输入密码(我不知道)。我按回车直到出现以下错误 Permission denied (publickey) error

我已经删除并重新创建了我的实例多次,但我总是遇到同样的错误。我该怎么办?

权限被拒绝(公钥)错误的可能原因是:

  • 您的密钥已过期,Compute Engine 删除了您的 ~/.ssh/authorized_keys 个文件。
  • 您使用存储在元数据中的 SSH 密钥连接到具有 OS 已启用登录。
  • 您使用存储在 OS 登录配置文件中的 SSH 密钥连接到 VM 未启用 OS 登录。
  • 您使用第三方工具连接并且您的 SSH 命令是 配置错误。
  • sshd 守护进程 运行 或配置不正确。

您可以在此 link

中找到有关如何解决 SSH 密钥错误的更多信息

我有时也会遇到同样的问题。根据GCP troubleshootinglink的原因及解决方法是:

Your key expired and Compute Engine deleted your ~/.ssh/authorized_keys file. If you manually added SSH keys to your VM and then connected to your VM using the Google Cloud Console, Compute Engine created a new key pair for your connection. After the new key pair expired, Compute Engine deleted your ~/.ssh/authorized_keys file in the VM, which included your manually added SSH key.

To resolve this issue, try one of the following:

Connect to your VM using the Google Cloud Console or the gcloud command-line tool. Re-add your SSH key to metadata. For more information, see Add SSH keys to VMs that use metadata-based SSH keys.

我使用 terraform,所以在这种情况下,我指示工作流销毁 VM 并重建它。

故障排除步骤:

  1. 使用 UI ssh 登录。这会创建一个临时 ssh 密钥,Google 代理还会执行代码路径以刷新 .ssh/authorized_keys 并解决 .ssh/ 和 .ssh/authorized_keys 的任何无效 dir/file 权限。此方法将解决与损坏的密钥、缺少 dir/file 或无效的 dir/file 权限相关的常见 gcloud compute ssh 问题。执行 UI ssh.
  2. 后再次尝试 gcloud
  3. 确保该帐户已通过 compute instance admin role 的 IAM 用户身份向 gcloud 进行身份验证;例如,运行 gcloud auth revoke --all,gcloud auth login [IAM-USER] 然后再次尝试 gcloud compute ssh。
  4. 验证是否为项目或实例设置了 gcloud 的永久 SSH 密钥元数据。查看 Compute Engine > 元数据,然后单击 SSH 密钥。永久键 没有 expireOn 属性
  5. 可能是账号丢失了私钥,或者密钥对不匹配等。您可以通过以下方式强制gcloud生成新的SSH密钥对:
    移动 ~/.ssh/google_compute_engine 和 ~/.ssh/google_compute_engine.pub(如果存在).
    例如:
    mv ~/.ssh/google_compute_engine.pub ~/.ssh/google_compute_engine.pub.old
    mv ~/.ssh/google_compute_engine ~/.ssh/google_compute_engine.old
    再次尝试 gcloud compute ssh [INSTANCE-NAME]。将创建一个新的密钥对,并将 public 密钥添加到 SSH 密钥元数据中。
  6. 验证是否安装了 Linux Google 代理脚本,up-to-date 和 运行ning。参见 Determining Google Agent Status. If the Linux Google Agent is not installed, re-install it. See guest-environment
  7. 验证帐户主页 owner/permission 是否正确。确保帐户主目录具有正确的所有权并且不是全局可写的。如果不使用 os-login(默认),您的 .ssh 文件夹必须具有模式 0700,.ssh/authorized_keys 文件必须具有模式 0600。检查 /var/log/auth.log 是否有任何错误。
    命令:
    sudo chmod 700 /home/[user-id]/.ssh
    sudo chmod 600 /home/[user-id]/.ssh/authorized_keys
  8. 如果启用 os-login 并且虚拟机实例正在使用服务帐户(默认)。将以下角色添加到帐户。
    roles/compute.osLogin
    roles/iam.serviceAccountUser

更多信息troubleshooting SSH