如何制作连接到 VM 并执行命令的 shell 脚本?

How to make a shell script that connects to a VM and executes commands?

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

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 上执行。如何制作连接虚拟机后执行命令的脚本?

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

此时您已通过 SSH 连接到正在等待输入的 VM。那不是你想要的。

注意 gcloud compute ssh--command 选项,它...

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"

您还可以使用 SSHPass 实用程序在远程服务器上自动执行命令。 https://linux.die.net/man/1/sshpass