How to make a shell script that connects to a VM a

2019-07-29 10:20发布

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

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?

2条回答
走好不送
2楼-- · 2019-07-29 10:27
gcloud compute instances start instance-1  #start instance
gcloud compute ssh my_username@instance-1  #ssh into it

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

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"
查看更多
Anthone
3楼-- · 2019-07-29 10:46

You can also use the SSHPass utility to automate execution of commands on a remote server. https://linux.die.net/man/1/sshpass

查看更多
登录 后发表回答