通过ssh从您的计算机对谷歌计算实例运行bash脚本

时间:2017-03-31 02:18:59

标签: macos ubuntu ssh google-cloud-platform google-compute-engine

我正在尝试在google计算实例上运行我的计算机上的脚本。我希望脚本可以连接并完成它的业务,并且很惊讶地看到来自下面的行为:

#!/bin/bash

gcloud compute ssh myinstance

echo "blah" > /tmp/test.txt

此脚本确实连接到myinstance,但它在我的计算机上写入/tmp/test.txt,而不是计算实例。脚本结束时,ssh连接仍然存在,我的终端已连接。

我曾期望它连接,将文件写入计算实例,并断开与ssh的连接。如何在我的机器上维护脚本,然后通过ssh轻松运行各种计算实例?主要用例来自mac - > Ubuntu Linux系统。谢谢

2 个答案:

答案 0 :(得分:1)

要在远程服务器上运行的命令应作为ssh的参数:

gcloud compute ssh myinstance 'echo "blah" > /tmp/test.txt'

答案 1 :(得分:1)

WORK_PROJECTS_PATH="$HOME/path"

BACKEND_SCRIPT_NAME="redeploy_backend.sh"
LOCAL_BACKEND_SCRIPT_PATH="$WORK_PROJECTS_PATH/myproject/scripts/deploy/$BACKEND_SCRIPT_NAME"
REMOTE_BACKEND_SCRIPT_TEMP_PATH="/tmp/$BACKEND_SCRIPT_NAME"
REMOTE_BACKEND_SCRIPT_PATH="/home/path/$BACKEND_SCRIPT_NAME"

GCP_INSTANCE="myproject-staging"

gcloud config set project myproject_name
# move current version of script over each time to ensure it's up to date
gcloud compute ssh $GCP_INSTANCE --command="sudo rm -f $REMOTE_BACKEND_SCRIPT_PATH"
# sending to temp path allows you to skip entering the compute instance password
gcloud compute copy-files $LOCAL_BACKEND_SCRIPT_PATH $GCP_INSTANCE:$REMOTE_BACKEND_SCRIPT_TEMP_PATH

gcloud compute ssh $GCP_INSTANCE --command="sudo mv $REMOTE_BACKEND_SCRIPT_TEMP_PATH $REMOTE_BACKEND_SCRIPT_PATH"
gcloud compute ssh $GCP_INSTANCE --command="sudo chmod +x $REMOTE_BACKEND_SCRIPT_PATH"
# run the script on the server from your machine
gcloud compute ssh $GCP_INSTANCE --command="$REMOTE_BACKEND_SCRIPT_PATH"