2017-04-26 16 views
1

我在Ubuntu 15.04,筆者的客戶端版本是SSH服務器的bash -c 「CD/tmp目錄&& git的拉動」,CD不工作,需要添加回聲第一

OpenSSH_6.9p1 Ubuntu-2ubuntu0.2, OpenSSL 1.0.2d 9 Jul 2015

當我嘗試運行以下命令ssh [email protected] bash -c 'cd /path/to/repo && git pull'裁談會不是有效的,我得到了

fatal: Not a git repository (or any of the parent directories): .git 

但是如果我做

ssh [email protected] bash -c 'echo test && cd /path/to/repo && git pull'

然後它

Already up-to-date. 

當然我很清楚echo是不應該改變什麼,但嘗試幾次,在幾個不同的服務器數天之後(雖然都是在Debian)我現在肯定有這個錯誤。 其他服務器上我試圖命令cd /tmp && pwd,並且我得到了我的主目錄,如果我做echo toto && /tmp && pwd我去/tmp印刷...

回答

3

不幸的是,SSH通過一個命令行字符串$SHELL -c遙控器上。你的報價沒有生效。

當您運行

ssh [email protected] bash -c 'cd /path/to/repo && git pull' 

這是被在遠程服務器上運行(與$SHELL -c):

bash -c cd /path/to/repo && git pull 

所以猛砸給出的單個命令(cd)和未使用的參數,然後另外,您還在主目錄中運行git pull

在另一方面,當您運行

ssh [email protected] bash -c 'echo test && cd /path/to/repo && git pull' 

這是被在遠程服務器上運行:

bash -c echo test && cd /path/to/repo && git pull 

第一部分是再沒用,但shell中運行整個命令,然後是否cd /path/to/repogit pull。哪些工作。

什麼你可能想要做的就是

ssh [email protected] 'cd /path/to/repo && git pull' 
+0

雞蛋裏挑骨頭船長檢查:在OpenSSH服務器使用該帳戶的登錄shell運行遠程命令,不一定是/ bin/sh。除此之外,我認爲你已經發現了。 – Kenster

+0

@Kenster雖然這是一個不錯的選擇,因爲它有所作爲(例如當用戶使用'chsh -s/bin/nologin'或類似的方法鎖定用戶時)。編輯。 – ephemient

2

existing answer by ephemient是在事業方面完全正確的。

要添加一個替代的解決方案 - 一個當你的遠程代碼包含構建物sh -c會曲解其中工程 - 考慮:

repo=/path/to/repo     ## here, this works even when your path contains 
            ## nonprintable or otherwise surprising characters 
printf -v repo_q '%q' "$repo"  ## ...because we're asking your local copy of bash 
            ## to generate a quoted/escaped copy of the value 
            ## that will 'eval' back to its original meaning 
            ## when interpreted by bash 

## to ensure that it's interpreted by bash, we pass 'bash -s' as the command to ssh 
## with an *unquoted* heredoc (<<EOF, vs <<'EOF'), with the escaped value expanded 
ssh [email protected] 'bash -s' <<EOF 
cd $repo_q && git pull 
EOF 
+0

是的,這是一個很好和安全的方式來做到這一點,雖然它可以煩人不能再使用stdin。但還有其他的解決方法,比如'ssh admin @ server「bash -c'cd $(printf%q」$ repo「)&& git pull'' – ephemient

+0

@ephemient,...問題在於'printf' %q''可以生成'$'''引用,而擴展外部命令的shell可能無法正常使用;因此,將結果保留在命令之外並將其限制爲標準輸入,然而,這是一種折衷。 –

+0

噢,好點,這是有問題的。我想'ssh admin @ server「bash -c $(printf%q」cd $(printf%q「$ repo」)&& git pull「)」'將是一個解決方法* that *,因爲從第一個'printf'的所有內容都應該是可打印的字符。 – ephemient