通过SSH在服务器上执行远程脚本

通过SSH在服务器上执行远程脚本

我在远程服务器上有一个远程脚本:

#!/bin/bash
echo Parameters=$@
echo "Ciao" $1                        

我通过调用 ssh 连接来运行脚本:

❯ pippo=pluto 
❯ ssh   -i rsa_r [email protected] "deploy.sh $pippo"
Parameters=
Ciao
(base)"

为什么它没有获取参数$pippo?

添加 -v 选项以获得一些见解:

...
debug1: client_input_global_request: rtype [email protected] want_reply 0
debug1: Remote: /home/developer/.ssh/authorized_keys:6: key options: agent-forwarding command port-forwarding pty user-rc x11-forwarding
debug1: Remote: /home/developer/.ssh/authorized_keys:6: key options: agent-forwarding command port-forwarding pty user-rc x11-forwarding
debug1: Sending environment.
debug1: Sending env LANG = C.UTF-8
debug1: Sending command: deploy.sh $pippo
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug1: client_input_channel_req: channel 0 rtype [email protected] reply 0
Parameters=
Ciao
debug1: channel 0: free: client-session, nchannels 1
Transferred: sent 3264, received 3128 bytes, in 1.5 seconds
Bytes per second: sent 2228.4, received 2135.6
debug1: Exit status 0

此外,将参数更改为pippo而不是$pippo并不重要。对于持怀疑态度的人:

在此输入图像描述

答案1

本地 shell 已被阻止将变量扩展$pippo为 value pluto,并且该ssh命令看到文字字符串deploy.sh $pippo

debug1: Sending command: deploy.sh $pippo

远程 shell 评估$pippo并发现它是空的,导致它在deploy.sh没有参数的情况下执行。

我建议您正在执行的命令不是您向我们展示的命令。请仔细检查引号:您很可能实际上使用的是单引号而不是双引号。

顺便说一句,您的脚本应该用双引号引用它正在使用的变量:

#!/bin/bash
echo "Parameters=$*"
echo "Ciao $1" 

相关内容