如何使用 RemoteCommand 配置 SSH 仅用于交互式会话(即没有命令,或者没有 sftp)

Yaj*_*ajo 14 ssh sftp ssh-config

目前我在本地和远程主机上使用 Fish 作为我的主要 shell。

我通过 ssh 和 sftp 连接到远程主机。我想在每次连接时自动打开或重用远程 tmux,默认情况下;所以我将此添加到我的~/.ssh/config

Host example.com
RemoteCommand tmux a; or tmux
RequestTTY yes
Run Code Online (Sandbox Code Playgroud)

问题是现在我无法通过 连接sftp,也无法从本地 CLI 运行直接命令:

? ssh example.com ping localhost
Cannot execute command-line and remote command.

? sftp example.com
Cannot execute command-line and remote command.
Connection closed
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是:如何定义在打开新的交互式 SSH 会话时要执行的默认命令,但使其可覆盖?

Ech*_*444 9

选项1 )

您可以选择 Match (参见man ssh_config

Match Host example.com exec "test $_ = /usr/bin/ssh"
     RemoteCommand tmux a; or tmux
     RequestTTY yes
Run Code Online (Sandbox Code Playgroud)

这只会区分 ssh 和 sftp 之间的区别

选项 2

您为差异命令创建一些占位符配置,例如:

Host tmux.example.com
  HostName example.com
  HostKeyAlias example.com
  RemoteCommand tmux a; or tmux
  RequestTTY yes
Run Code Online (Sandbox Code Playgroud)

之后您仍然可以使用 example.com 为您 sftp/ping 使用。

  • 谢谢,这帮助我找到了对我有用的答案:将匹配更改为`Match exec "[[ $(ps ho args p $PPID | wc -w) -eq 2 ]]"`。当 ssh 被调用为“ssh <server>”时,该 exec 为真,但如果调用为“ssh <server> <command>”则为假 (7认同)

Lui*_*uca 5

我正在使用更复杂的东西来处理 ssh 选项和参数中的空间:

Match exec "POSIXLY_CORRECT=1 xargs -0 getopt -o 46AaCfGgKkMNnqsTtVvXxYyB:b:c:D:E:e:F:I:i:J:L:l:m:O:o:p:Q:R:S:W:w: --  </proc/$PPID/cmdline | perl -pe 's|.*? -- ||' | { read -r c; eval a=($c); [ ${#a[@]} -le 2 ]; }"
    RemoteCommand my-command-here
    RequestTTY yes
Run Code Online (Sandbox Code Playgroud)

另外,如果有人想对某些机器使用 RemoteCommand(例如在“host xxxx”内部),可以在反向逻辑中使用相同的技巧(匹配在主机之后评估):

Match exec "POSIXLY_CORRECT=1 xargs -0 getopt -o 46AaCfGgKkMNnqsTtVvXxYyB:b:c:D:E:e:F:I:i:J:L:l:m:O:o:p:Q:R:S:W:w: -- </proc/$PPID/cmdline | perl -pe 's|.*? -- ||' | { read -r c; eval a=($c); [ ${#a[@]} -gt 2 ]; }"
     RemoteCommand none
     RequestTTY auto

Host machine1 machine2 ...
     RemoteCommand my-command-here
     RequestTTY yes
Run Code Online (Sandbox Code Playgroud)

如果有人好奇,我目前正在使用 RemoteCommand 来调用屏幕:

RemoteCommand which screen &>/dev/null && TERM=xterm screen -q -RR "%u-%C" $SHELL -l || $SHELL -l
Run Code Online (Sandbox Code Playgroud)

  • 如果 ssh 简单地认为 cmdline 中的命令比 -o RemoteCommend 具有更高的优先级,那么它可以为我们减轻一些痛苦 (3认同)

Yaj*_*ajo 0

这并没有直接回答问题。然而,对我来说,它已经成为解决根本问题的方法,所以我认为它值得发一篇文章。

我真正想要的是自动输入 tmux。相反,我刚刚开始使用 byobu,它构建在 tmux 之上,但更舒适。例如,它开箱即用地支持此用例。

安装 byobu 后,只需运行:

byobu-enable
Run Code Online (Sandbox Code Playgroud)

你就完成了。下一个交互会话将自动进入 byobu,无论 shell 是什么。非交互式连接将照常工作。