Ssh
如何使用 RemoteCommand 配置 SSH 僅用於互動式會話(即沒有命令,或者沒有 sftp)
目前我在本地和遠端主機上使用 Fish 作為我的主要 shell。
我通過 ssh 和 sftp 連接到遠端主機。預設情況下,我想在連接時自動打開或重用遠端 tmux;所以我將此添加到我的
~/.ssh/config
:Host example.com RemoteCommand tmux a; or tmux RequestTTY yes
問題是現在我無法通過 連接
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
所以,我的問題是:如何定義打開新的互動式 SSH 會話時要執行的預設命令,但使其可覆蓋?
選項1 )
你可以選擇匹配(見man ssh_config)
Match Host example.com exec "test $_ = /usr/bin/ssh" RemoteCommand tmux a; or tmux RequestTTY yes
這只會區分 ssh 和 sftp 之間的區別
選項 2
您為您的差異命令創建一些佔位符配置,例如:
Host tmux.example.com HostName example.com HostKeyAlias example.com RemoteCommand tmux a; or tmux RequestTTY yes
並且之後您仍然可以使用 example.com 為您提供 sftp/ping 使用。
我正在使用更複雜的東西來處理 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
此外,如果有人想在某些機器上使用 RemoteCommand(比如在“主機 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
如果有人好奇,我目前正在使用 RemoteCommand 呼叫螢幕:
RemoteCommand which screen &>/dev/null && TERM=xterm screen -q -RR "%u-%C" $SHELL -l || $SHELL -l