如何在命令行上 SSH 到 Google Cloud VM 实例

如果你想使用 SSH 从命令行连接到 Google Cloud VM 实例(在此示例中为 my-instance),你有两个选项:

直接使用 gcloud 连接

如果你的实例启用了 SSH,这将始终有效,即使它没有外部 IP:

gcloud_ssh.sh
gcloud compute ssh my-instance --zone $(gcloud compute instances list --filter="name=my-instance" --format "get(zone)" | awk -F/ '{print $NF}')

注意你必须在上述命令中将 my-instance 替换为你的实际实例名称两次。子命令(包含在 $(...) 中)查找你实例的正确区域,因为在撰写本文时 gcloud compute ssh 除非你为该实例设置正确的区域否则将不起作用。请参见如何在命令行上查找 Google Cloud VM 实例的区域了解更多详情。

使用外部 IP 连接

你也可以使用 gcloud 获取外部 IP 并使用你的标准 SSH 客户端连接到它。

ssh_via_external_ip.sh
ssh $(gcloud compute instances list --filter="name=my-instance" --format "get(networkInterfaces[0].accessConfigs[0].natIP)")

这有一个额外的优势,你将能够在其他类似 SSH 的命令中使用它,如 rsync

供参考另请参见安全连接到实例的官方手册


Check out similar posts by category: Cloud