2016-05-16 200 views
1

我想使用$ 1,$ 2變量,我通過命令行傳遞給bash shell腳本。我在ssh調用中使用了這些變量。但它似乎在ssh中的變量沒有被替換,外部的變量正在被替換。任何解決方法?這裏是代碼命令行參數在bash shell腳本中的嵌套ssh

#!/bin/bash 

ssh -t "StrictHostKeyChecking=no" -i $1 [email protected]<<'EOF1' 

ssh -t -i $1 [email protected] <<'EOF2' 

exit 
EOF2 

exit 
EOF1 

這裏第一個$ 1被替換,但第二個沒有。它的密碼基本鍵名少認證

+0

如果你想要比我已經提供的更好的答案,你需要問一個更好的問題。顯示代碼來重現問題,也許? –

+1

請查看[如何創建一個最小,完整和可驗證的示例](http://stackoverflow.com/help/mcve)。 – Cyrus

+0

已添加代碼。 –

回答

3

使用printf %q生成的參數列表的eval -safe的字符串形式:

# generate a string which evals to list of command-line parameters 
printf -v cmd_str '%q ' "[email protected]" 

# pass that list of parameters on the remote shell's command line 
ssh "$host" "bash -s $cmd_str" <<'EOF' 
    echo "This is running on the remote host." 
    echo "Got arguments:" 
    printf '- %q\n' "[email protected]" 
EOF 

對於你真正做,最好的做法可能會使用ProxyCommand - 請參閱the relevant documentation - 並通過代理轉發將您的私鑰暴露出來,而不是讓它位於磁盤上的反彈主機上。這就是說,它是直截了當採用上面給出以適應問題的代碼答案:

#!/bin/bash 
printf -v args '%q ' "[email protected]" 
echo "Arguments on original host are:" 
printf '- %q\n' "[email protected]" 
ssh -t "StrictHostKeyChecking=no" -i "$1" [email protected] "bash -s $args" <<'EOF1' 
    printf -v args '%q ' "[email protected]" 
    echo "Arguments on ip1 are:" 
    printf '- %q\n' "[email protected]" 
    ssh -t -i "$1" [email protected] "bash -s $args" <<'EOF2' 
    echo "Arguments on ip2 are:" 
    printf '- %q\n' "[email protected]" 
EOF2 
EOF1 
+0

已添加特定問題的代碼。謝謝 –

+0

@ user3780835,...據此展開。 –

+0

謝謝你的時間。我也會研究ProxyCommand。 –

1

簡單多了,就是讓ssh處理隧道爲您服務。

ssh -o ProxyCommand="ssh [email protected] nc -w 10 %h %p" [email protected] 

(這個例子在http://undeadly.org/cgi?action=article&sid=20070925181947找到)。

+0

肯定是正確的 - 爲什麼我在我的回答中提到了它[在OpenSSH Cookbook部分中關於這個主題的一個鏈接],在OP擴展他們的問題以使他們的工作變得清晰之後。更明確一些 - 就像你在這裏做的那樣 - 不會受到傷害。 –

+0

嗨charles/chepner,是否有可能ip2的密鑰在我的主服務器上,而不是在ip1上? (只能通過ip1登錄到ip2) –

+0

如果你在本地機器上運行'ssh-agent',並使用'-A'選項('ssh -A -o ProxyCommand。 ..')。 – chepner