LoginSignup
88

More than 5 years have passed since last update.

多段sshを行うときに、ローカルの秘密鍵を参照し続ける

Last updated at Posted at 2014-09-04

目的: sshを使い複数のサーバーにログインする

要請

  • 複数のサーバーを経由した場合でも楽に目的のサーバーにログインしたい
  • ユーザー名,ホスト名の入力を省略したい
  • 鍵認証を利用する場合目的のサーバーによって鍵を自動で使い分けたい
  • 多段sshで鍵を利用するときに、常に自分のローカルマシンの秘密鍵を参照したい ((A→B→C)でログインするときにCはBではなくAの鍵を参照するようにしたい)
  • 長時間サーバーにログインしていても通信が切れないようにしたい
  • X11を利用したい
  • 2つ目の接続は1つ目の接続を利用し認証をスキップしたい

※公開鍵認証とはパスワード認証ではない認証方式である(安全性が高い)。

公開鍵の概念http://www.adminweb.jp/web-service/ssh/index4.html
公開鍵の利用http://qiita.com/lasta/items/41e95a2fdded18c34dae

ssh設定ファイルの構造

ファイル名 役割
~/.ssh/config ssh設定ファイル
~/.ssh/id_rsa 秘密鍵(鍵の役割)
~/.ssh/id_rsa.pub 公開鍵(鍵穴の役割)
~/.ssh/authorized_keys 公開鍵の鍵束(実際、公開鍵の中身がテキストで羅列してある)
~/.ssh/known_hosts 過去に利用したサーバーのリスト

鍵穴(公開鍵)をサーバ設置して、手元の鍵(秘密鍵)でログインする

解決策

~/.ssh/configの設定

設定

各マシーン

ローカルPC = macbook
サーバーA : ユーザー名=usernama1 ドメイン=aaa.ac.jp
サーバーB : ユーザー名=username2 ドメイン=bbb.ac.jp

つまりサーバーAにログインするには

shell
ssh username1@aaa.ac.jp

公開鍵と秘密鍵(macbook 上で生成)

秘密鍵:macbook_rsa
公開鍵:macbook_rsa.pub

やりたいこと

ローカルPC → サーバーA
ローカルPC → サーバーA → サーバーB

config
Host A
HostName aaa.ac.jp
User username1
IdentityFile ~/.ssh/macbook_rsa
ForwardAgent yes
ForwardX11 yes
ServerAliveInterval 300
ForwardX11Timeout 596h
ControlMaster auto
ControlPath ~/.ssh/mux-%r@%h:%p
ControlPersist 30m

Host B
HostName bbb.ac.jp
User username2
ProxyCommand ssh A nc %h %p
IdentityFile ~/.ssh/macbook_rsa
ForwardAgent yes
ForwardX11 yes
ServerAliveInterval 300
ForwardX11Timeout 596h
ControlMaster auto
ControlPath ~/.ssh/mux-%r@%h:%p
ControlPersist 30m

※Hostは自由に名前をつけて下さい

使い方

まず鍵をssh-agentに鍵を登録する

shell
sudo ssh-add ~/.ssh/macbook_rsa

Aにログイン

shell
ssh A

Aを経由してBにログイン

shell
ssh B

解説

変数 意味
Host サーバーのニックネーム
IdentityFile 使用する秘密鍵を指定
ForwardAgent yes ssh-agentを利用する
ForwardX11 yes X11の転送を行う
ProxyCommand ssh A nc %h %p Bに行くときはまずAを経由する
ServerAliveInterval 300 300秒おきにシグナルを送り通信が自動で切断されるのを防ぐ
ForwardX11Timeout 596h X11のタイムアウト時間を596時間にして、自動でX11の転送が途切れるのを防ぐ
ControlMaster auto
ControlPath ~/.ssh/mux-%r@%h:%p
ControlPersist 30m
同じサーバーに2つ目のsshを行った時に、1つ目のsshを利用して接続時間を高速にする(認証をスキップ)。
注:ControlPersist 30mを使い30mでタイムアウトを設定しておかないと、sshをログアウトした後も裏で通信が続いている状態になる

ssh-agent http://www.unixuser.org/~euske/doc/openssh/book/chap4.html#make-life-easy-with-ssh-agent
ssh-agentの注意点 [4.4.4. 認証エージェントを使う際の注意を参照] http://www.unixuser.org/~euske/doc/openssh/book/chap4.html#notice-with-ssh-agent
ControlMaster http://d.hatena.ne.jp/tmatsuu/20120707/1341677472

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
88