簡體   English   中英

如何使用參數通過 ssh 執行遠程命令?

[英]How to execute a remote command over ssh with arguments?

在我的.bashrc中,我定義了一個稍后可以在命令行上使用的函數:

function mycommand() {
    ssh user@123.456.789.0 cd testdir;./test.sh "$1"
}

使用此命令時,只是在遠程主機上執行cd命令; test.sh命令在本地主機上執行。 這是因為分號分隔了兩個不同的命令: ssh命令和test.sh命令。

我嘗試按如下方式定義函數(注意單引號):

function mycommand() {
    ssh user@123.456.789.0 'cd testdir;./test.sh "$1"'
}

我試圖將cd命令和test.sh命令放在一起,但參數$1沒有解析,與我給函數的內容無關。 總是嘗試執行命令

./test.sh $1

在遠程主機上。

我如何正確定義mycommand ,以便在更改為目錄testdir后在遠程主機上執行腳本test.sh ,並能夠將給mycommand的參數傳遞給test.sh

這樣做是這樣的:

function mycommand {
    ssh user@123.456.789.0 "cd testdir;./test.sh \"$1\""
}

您仍然必須將整個命令作為單個字符串傳遞,但在該單個字符串中,您需要在將其發送到ssh之前展開$1 ,因此您需要使用""

更新

實際上這樣做的另一種正確方法是使用printf %q來正確引用參數。 即使它有空格,單引號,雙引號或任何其他可能對shell有特殊含義的字符,這也會使參數安全解析:

function mycommand {
    printf -v __ %q "$1"
    ssh user@123.456.789.0 "cd testdir;./test.sh $__"
}
  • 使用function聲明函數時, ()不是必需的。
  • 不要僅因為你是POSIXist而對它發表評論。

恢復舊的線程,但沒有列出這個非常干凈的方法。

function mycommand() {
    ssh user@123.456.789.0 <<+
    cd testdir;./test.sh "$1"
+
}

這是適用於AWS Cloud的示例。 方案是,從自動擴展啟動的某台計算機需要在另一台服務器上執行某些操作,通過SSH傳遞新生成的實例DNS

# Get the public DNS of the current machine (AWS specific)
MY_DNS=`curl -s http://169.254.169.254/latest/meta-data/public-hostname`


ssh \
    -o StrictHostKeyChecking=no \
    -i ~/.ssh/id_rsa \
    user@remotehost.example.com \
<< EOF
cd ~/
echo "Hey I was just SSHed by ${MY_DNS}"
run_other_commands
# Newline is important before final EOF!

EOF

我正在使用以下命令在本地計算機上執行遠程命令:

ssh -i ~/.ssh/$GIT_PRIVKEY user@$IP "bash -s" < localpath/script.sh $arg1 $arg2

對我來說是一個小技巧,使用“bash -s”,他們說他們允許 POSITIONAL ARGS 但顯然 $0 已經出於某種原因保留了......然后使用兩次相同的 args 岩石就像這樣:

ssh user@host "bash -s" < ./start_app.sh -e test -e test -f docker-compose.services.yml 

解決方案:您希望能夠使用 ssh 協議遠程連接到機器並在外部觸發/運行一些操作。

在 ssh 上使用-t標志,來自文檔:

-t Force pseudo-terminal allocation.
This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, eg when implementing menu services. Multiple -t options force tty allocation, even if ssh has no local tty. when implementing menu services. Multiple -t options force tty allocation, even if ssh has no local tty.

公式

ssh -i <key-path> <user>@<remote-machine> -t '<action>'

示例:作為管理員,我希望能夠遠程連接到 ec2 機器,並針對多台原始機器上的錯誤部署觸發恢復過程,此外,您最好將此操作實現為使用 ips 作為參數並運行的自動化腳本在不同的機器上並行。

ssh -i /home/admin/.ssh/key admin@10.20.30.40 -t 'cd /home/application && make revert'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM