LoginSignup
82
90

More than 3 years have passed since last update.

踏み台サーバを飛び越えて一発で目的のサーバへsshする方法

Last updated at Posted at 2018-06-05

はじめに

サーバにssh接続する際、踏み台サーバを経由する必要がある事例がしばしば存在します。
その際、sshのポートフォワーディングを利用することで簡単にアクセスができます。

この記事では、ポートフォワーディングの方法をまとめてみました。

登場するマシン

  • Local Machine(local)
    • 手元の端末
  • Bastion Server(bastion)
    • 踏み台サーバ
    • Local Machineからsshアクセス可能
  • Target Server(target)
    • 本当にアクセスしたいサーバ
    • Local Machineからsshアクセス不可能
    • Bastion Serverからsshアクセス可能

Target Serverへアクセスする方法

ProxyCommandを利用する方法(おすすめ!)

ProxyCommandを利用し、一発でログインする方法です。
以下のコマンドを実行します。

console
[local_user@local]$ ssh -o ProxyCommand='ssh -W %h:%p -i <bastion_id_rsa> -p <bastion_port> <bastion_user>@<bastion_server>' \ 
                         -i <target_id_rsa> -p <target_port> <target_user>@<target_server>

読みにくいので\を利用し改行を入れました。
単純に言えば、ProxyCommandに踏み台サーバへのssh接続について記述してあげれば良い、ということになります。

ただ、これを書くのは正直めんどくさいので、.ssh/configを活用しましょう。
まず、以下のように編集します。

.ssh/config
Host <alias_name>
  HostName <target_server>
  User <target_user>
  IdentityFile <target_id_rsa>
  ProxyCommand ssh -W %h:%p -i <bastion_id_rsa> -p <bastion_port> <bastion_user>@<bastion_server>

編集が終わったら、以下のコマンドを実行します。

console
[local_user@local]$ ssh <alias_name>

トンネルを掘る方法(Local Forwardを利用する方法)

同等のことをLocal Forwardを利用しても実行できます。
しかし、結局sshを2回叩くことになるのでおすすめしません。

試してないのですが、以下のような感じかと。

console
[local_user@local]$ ssh -fN <bastion_user>@<bastion_server>:<bastion_port> \
                         -L <local_port>:<target_server>:<target_port>
[local_user@local]$ ssh -p <local_port> <target_user>@localhost

勿論、.ssh/configを利用することもできます。
以下のように編集します。

.ssh/config
Host <alias_name1>
  HostName <bastion_server>
  User <bastion_user>
  IdentityFile <bastion_id_rsa>  
  LocalForward <local_port> <target_server>:<target_port>

Host <alias_name2>
  HostName localhost
  User <taget_user>
  IdentityFile <target_id_rsa>  
  Port <local_port>

編集が終わったら、以下のコマンドを実行します。

console
[local_user@local]$ ssh -fN <alias_name1>
[local_user@local]$ ssh <alias_name2>

ポートフォワーディング機能を利用しない方法

Bastion Serverへsshでログインした後に、そこからTarget Serverへログインする方法です。

console
[local_user@local]$ ssh -p bastion_port bastion_user@bastion_server
[bastion_user@bastion]$ ssh -p target_port target_user@target_server

この方法は、Bastion Server、Target Serverの両方のURLとportを記憶しておく必要があります。
.ssh/configを編集することで、その手間を省くことができますが、Local Machineと Bastion Serverの両方のconfigファイルを編集する必要があります。

参考文献

82
90
0

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
82
90