【问题标题】:How to make a shell script that connects to a VM and executes commands?如何制作连接到 VM 并执行命令的 shell 脚本?
【发布时间】:2017-12-04 03:05:31
【问题描述】:

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

【问题讨论】:

    标签: linux bash shell google-cloud-platform gcloud


    【解决方案1】:
    gcloud compute instances start instance-1  #start instance
    gcloud compute ssh my_username@instance-1  #ssh into it
    

    此时,您与正在等待输入的虚拟机建立了 SSH 连接。这不是你想要的。

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

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2016-12-20
        • 2020-12-14
        • 2011-10-04
        • 1970-01-01
        • 2011-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-13
        相关资源
        最近更新 更多