ssh:在远程主机上执行命令而不是登录 shell

Mar*_*ter 3 shell ssh

我正在remote-server从本地主机连接,我想在remote-server.

按预期工作:

ssh remote-server "hostname"
remote-server
Run Code Online (Sandbox Code Playgroud)

我很迷惑。为什么这会返回本地主机名,而不是远程服务器的主机名?

ssh remote-server "print $HOST"
localhost
Run Code Online (Sandbox Code Playgroud)

Wie*_*and 7

您的第二个代码示例:

ssh remote-server "print $HOST"
localhost
Run Code Online (Sandbox Code Playgroud)

将被带有诊断SC2029的优秀Shellcheck工具标记:

Bash 扩展了所有未转义/单引号的参数。这意味着有问题的代码与

ssh 主机“回显客户端主机名”

并将打印出客户端的主机名,而不是服务器的主机名。

通过转义 $HOSTNAME 中的 $,它将被逐字传输并在服务器上进行评估。

通过使用

ssh host "print \$HOST"
Run Code Online (Sandbox Code Playgroud)

或者

ssh host 'print $HOST'
Run Code Online (Sandbox Code Playgroud)

您可以阻止本地shell 扩展主机,而是让 shellremote-server扩展它。


Sha*_*dur 6

因为您使用的是双引号,所以 shell$HOST在执行命令并启动之前会进行评估ssh,所以您将命令 " print localhost" 发送到远程服务器。

改用单引号:

shadur@proteus:~$ ssh axiom "echo $HOSTNAME"
shadur@axiom's password:
proteus

shadur@proteus:~$ ssh axiom 'echo $HOSTNAME'
shadur@axiom's password:
axiom
Run Code Online (Sandbox Code Playgroud)