Reputation: 1665
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?
Upvotes: 1
Views: 1776
Reputation: 3763
You can also use the SSHPass utility to automate execution of commands on a remote server. https://linux.die.net/man/1/sshpass
Upvotes: 2
Reputation: 70223
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"
Upvotes: 3