踏み台サーバで sudo ssh する場合の .ssh/config の書き方 (2023)

想定

ターゲットホスト (target1.example.com, target2.example.com, ...) に対して、普段は以下のようにログインしている場合を考える。この環境では、踏み台上にある /root/.ssh/id_hoge を local 上に保管することはできない。

# 踏み台 (bastion) に ssh する
local% ssh bastion.example.jp

# 踏み台からターゲットホスト (targetX.example.com) に ssh する
bastion% sudo ssh target1.example.com
# or     sudo ssh target2.example.com
# or     sudo ssh target3.example.com
  :

これを local 上において、以下のように直接 ssh コマンドで扱いたい。

local% ssh target1.example.com
# or   ssh target2.example.com
# or   ssh target3.example.com
  :

.ssh/config の記載方法

基本は以下の記事を参考にしている。

踏み台で sudo -u しているsshでの ssh_config https://qiita.com/shase428q/items/c796188b9840eaec9ead

ただし上記の記事の .ssh/config は、 個々のターゲットホストごとに決め打ちの Host エントリを書く形態になっている。これを複数のターゲットホストに対して記載するのは面倒なので、コマンドラインで与えたホスト名を変数として RemoteCommand 内で扱いたい。

この場合は、以下のように変数 %n が利用できる。

Host *.example.com
  Hostname bastion.example.jp
  RequestTTY force
  RemoteCommand sudo ssh -t %n

ssh_configのマニュアル には、以下のようにある。

%n    The original remote hostname, as given on the command
      line.

Appendix

なお、以下のように %h を用いるのは正しくない。

Host *.example.com
  Hostname bastion.example.jp
  RequestTTY force
  RemoteCommand sudo ssh -t %h  # <-- この場合、 %h は
                                # "bastion.example.jp" に置き換えられる

また、この RemoteCommand ssh を用いる方法では、scpを正しく扱うことが出来ない。これは未だ解決していないので、良い方法があれば誰か教えて欲しい。