LoginSignup
773
740

More than 5 years have passed since last update.

多段SSHの設定を.ssh/configにまとめる

Last updated at Posted at 2014-04-23

概要

  • 踏み台サーバを経由した多段SSHの設定をconfigにまとめる方法
  • 接続するマシンは、WANやゲートウェイ内のネットワークのいずれにも属する可能性があると想定(ノートPC等)

ネットワーク図

network-image.png

  • 図のようにゲートウェイ経由でしかアクセスできないネットワーク内にさらにゲートウェイがあるネットワークを想定

単純な多段SSHの書き方

host gateway
   HostName sshgate.hoge
   User hoge

Host RemoteHost-out
  HostName RemoteHost
  User fuga
  ProxyCommand ssh -W %h:%p gateway

上記の設定を~/.ssh/configに書いた後、
ssh RemoteHost-out
でgateway経由でのアクセスが可能

複数に同時に設定を適応する場合

.ssh/configには複数の設定をワイルドカードでまとめて書くことができる

例えば、以下の様なconfigを設定する。

host gateway
   HostName sshgate.hoge
   User hoge

Host RemoteHost*
  HostName RemoteHost
  User fuga

host *-none
   ProxyCommand none

Host *-out*
   ProxyCommand ssh -W %h:%p gateway

この時、上から順にヒットしたHostに記載されている項目だけ適応され、以下は適応されていない項目だけ適応される。
例えば、
ssh RemoteHost-out
と実行すると、gateway経由でRemoteHostに接続される。

  • HostName,UserはHost RemoteHost*から
  • ProxyCommandはHost *-out*から

ssh RemoteHost-out-none
とすると、
直接、RemoteHostに接続される。

  • HostName,UserはHost RemoteHost*から
  • ProxyCommandはHost *-noneから
  • *-out*のProxyCommandは*-noneで設定済みなので無視される

最終的な.ssh/config

上記を踏まえた上で、設定をまとめる。

~/.ssh/config
host gateway
   HostName sshgate.hoge
   User hoge

host *-none
   ProxyCommand none

Host LocalB-*-out
   ProxyCommand ssh -W %h:%p Bgateway-out

Host LocalC-*-out
   ProxyCommand ssh -W %h:%p Cgateway-out

Host LocalB-*
   ProxyCommand ssh -W %h:%p Bgateway

Host LocalC-*
   ProxyCommand ssh -W %h:%p Cgateway

Host *-out
   ProxyCommand ssh -W %h:%p gateway

Host *RemoteHost*
  HostName RemoteHost
  User fuga

Host *Bgateway*
  HostName Bgateway
  User hogehoge

Host *Cgateway*
  HostName Cgateway
  User hogehoge

Host *HostA*
  HostName HostA
  User hogehoge

Host *HostB*
  HostName HostB
  User hogehoge

Host *HostC*
  HostName HostC
  User hogehoge

Host *HostD*
  HostName HostD
  User hogehoge

ゲートウェイ間の通信の処理を書いておけば、これでどの経路のゲートウェイを通る設定も網羅できる。

利用例

例えば、WANからHostAにアクセスする場合、
ssh LocalB-HostA-out
でgateway->Bgateway->HostAの多段SSHが可能

LocalAやLocalCのネットワークからHostBにアクセスする場合は、
ssh LocalB-HostB

LocalCのネットワークからHostDにアクセスする場合は、通常通り
ssh HostD
もしくは、
ssh HostD-out-none
のように最後に-noneをつけることでProxyCommandを無視する設定も可能

この書式で書けば、ホストを追加する時にgatewayの設定等を個別に書く必要がなく、ホスト名(+ユーザ名・鍵ファイル指定等必要情報)だけを指定することで、そのHostに対しても多段SSHを行うことができる。

ホスト名補完用設定

ただし、この設定をするとzshのホスト名補完が聞かなくなったので、
私は、configの最初に以下のようによく利用するホスト名の補完用の空設定を書いている。

Host LocalB-HostA-out HostA LocalB-HostA-out RemoteHost-out

Host gateway
…

もっとスマートな方法があったら教えて下さい。

773
740
7

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
773
740