You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GCP是否有类似Azure Invoke-AzVMRunCommand的可在Cloud Shell运行VM脚本的命令

GCP Cloud Shell 远程执行VM脚本相关解答

对应Azure Invoke-AzVMRunCommand的等效功能

GCP完全支持在Cloud Shell中直接对虚拟机执行脚本,核心通过预装在Cloud Shell中的gcloud CLI实现,最常用的方式是结合gcloud compute ssh命令的--command参数,不需要手动登录进虚拟机实例即可完成脚本执行,和Azure Invoke-AzVMRunCommand的使用体验基本一致。

基础使用示例

执行单行命令/简单脚本

命令格式:

gcloud compute ssh <你的虚拟机实例名> --zone <实例所在可用区> --command "<需要执行的脚本内容>"

举个实际用例,在名为web-server-01、可用区为us-east1-b的实例上执行系统包更新:

gcloud compute ssh web-server-01 --zone us-east1-b --command "sudo apt update && sudo apt upgrade -y"

执行本地多行脚本

如果你要运行的脚本较长,可以先把脚本文件上传到Cloud Shell,再通过以下命令推送到虚拟机并执行:

# 先把本地脚本传到虚拟机用户根目录
gcloud compute scp ./my_script.sh <你的虚拟机实例名>:~ --zone <实例所在可用区>
# 给脚本加执行权限后运行
gcloud compute ssh <你的虚拟机实例名> --zone <实例所在可用区> --command "chmod +x ~/my_script.sh && ~/my_script.sh"

无公网IP虚拟机的适配方案

如果你的虚拟机没有分配公网IP,可以添加--tunnel-through-iap参数通过GCP的身份感知代理隧道访问,不需要额外调整网络配置:

gcloud compute ssh web-server-01 --zone us-east1-b --tunnel-through-iap --command "echo '私网VM也可以直接执行'"

前置要求

  • 你使用的GCP账号拥有对应虚拟机的SSH访问权限(compute.instances.ssh权限)
  • 虚拟机已启用OS Login(默认配置即可满足),或你的SSH公钥已提前导入到虚拟机元数据中

内容的提问来源于stack exchange,提问作者codinmach

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 22:57:04