如何制作连接到VM并执行命令的Shell脚本? [英] How to make a shell script that connects to a VM and executes commands?

查看:200
本文介绍了如何制作连接到VM并执行命令的Shell脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在gcloud VM实例上有一个Python脚本.我想通过以下shell脚本运行它:

I have a Python script on a gcloud VM instance. I want to run it via this shell script:

gcloud compute instances start instance-1  #start instance
gcloud compute ssh my_username@instance-1  #ssh into it
cd project_folder                          #execute command once inside VM
python my_script.py                        #run python script
sudo shutdown now                          #exit instance
gcloud compute instances stop instance-1   #stop instance

前两个命令按预期工作;但是,其余命令不会在VM上执行.连接到虚拟机后如何制作执行命令的脚本?

The first two commands work as intended; however, the rest of the commands don't execute on the VM. How can I make a script that executes commands after connecting to the VM?

推荐答案

gcloud compute instances start instance-1  #start instance
gcloud compute ssh my_username@instance-1  #ssh into it

这时,您与正在等待输入的VM建立了SSH连接.那不是你想要的.

At this point you have a SSH connection to your VM that is waiting for input. That is not what you want.

请注意gcloud compute ssh--command选项,该选项...

Note the --command option to gcloud compute ssh, which...

在目标实例上运行命令,然后退出.

Runs the command on the target instance and then exits.

gcloud compute ssh my_username@instance-1 \
    --command="cd project_folder && python my_script.py && sudo shutdown now"

这篇关于如何制作连接到VM并执行命令的Shell脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆