如何使用参数在ssh上执行远程命令?

时间:2013-08-29 05:30:48

标签: linux bash ssh

在我的.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,以便在更改到目录test.sh后在远程主机上执行脚本testdir,并能够传递给{的参数{1}}到mycommand

4 个答案:

答案 0 :(得分:65)

请这样做:

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

您仍然必须将整个命令作为单个字符串传递,但在该单个字符串中,您需要先将$1展开,然后才能将其发送到ssh,因此您需要使用""

更新

另一种实际做法的正确方法是使用printf %q来正确引用参数。即使它有空格,单引号,双引号或任何其他可能对shell有特殊含义的字符,这也会使参数安全解析:

function mycommand {
    printf -v __ %q "$1"
    ssh user@123.456.789.0 "cd testdir;./test.sh $__"
}
  • 使用function声明功能时,不需要()
  • 不要因为你是POSIXist而对它发表评论。

答案 1 :(得分:4)

恢复旧线程,但没有列出这种非常干净的方法。

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

答案 2 :(得分:3)

这是适用于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

答案 3 :(得分:2)

我正在使用以下命令在本地计算机上的远程计算机上执行命令:

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