sshで自動認証するには

※最近はDSAよりもRSAが推奨されます。
注)
文中において
local⇒接続元端末
remote⇒接続先端末

公開鍵と秘密鍵を使えば可能。
まず、SSHがV1とV2のどちらなのかを確認

local$ ssh -V

V2に対応しているなら

local$ cd ~
local$ mkdir .ssh
local$ chmod 700 .ssh
local$ ssh-keygen -t dsa
Generating public/private dsa key pair.
Enter file in which to save the key (/home/hoge/.ssh/id_dsa): [Enter]
Enter passphrase (empty for no passphrase) [Enter]
Enter same passphrase again: [Enter]
The key fingerprint is:
Your identification has been saved in /home/hoge/.ssh/id_dsa
Your public key has been saved in /home/hoge/.ssh/id_dsa.pub
00:00:00:00:00:00:00:00:00:00:00:00:00:00 hoge@localservername
↑パスフレーズを設定しないならEnter連打で良し。

で、DSA公開鍵と秘密鍵を生成。
次にリモートサーバに公開鍵を転送

local$ scp ~/.ssh/id_dsa.pub hoge@remote_addr:/home/hoge

ここで、一旦リモートサーバにログインし、
公開鍵の登録を行う。

local$ ssh hoge@remote_addr
remote$ mkdir .ssh
remote$ chmod 700 .ssh/
remote$ cd .ssh/
remote$ touch authorized_keys  ←authorized_keys2は非推奨なので使わないこと
remote$ chmod 600 authorized_keys
remote$ cat ~/id_dsa.pub >>authorized_keys

登録により、不要となった公開鍵を削除

remote$ rm ~/id_dsa.pub
local$ rm ~/.ssh/id_dsa.pub  ←消してもいいが、他のホストへの再登録を考えると残しておくのが無難。
なお、local$ ~/.ssh/id_dsa は消してしまうと自動認証できなくなるので、消しちゃダメ。

以上で設定は完了。

local$ ssh hoge@remote_addr

でログインできるはず。
ただし、初回の場合は、.ssh/known_hostsにRSA鍵の登録が必要なので

The authenticity of host 'remote_addr (remote_addr)' can't be established.
RSA key fingerprint is 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00.
Are you sure you want to continue connecting (yes/no)?

という確認を求められることがある。その場合はyesとタイプすればよい。
今回は、パスフレーズを設定しなかったのでこれで自動認証できるが、
パスフレーズを設定すると、sshの際にパスフレーズの入力を求められるので
自動認証が成立しない。
それを解決するには、ssh-agentを利用すれば良いようだ。
※参考サイト
ノンパスワードでログインしたい
ssh-agentでパスフレーズをキャッシュさせたい
また、Linux端末で生成した秘密鍵をWindows上のPuttyで利用する際には、
Putty用に鍵を変換しなければならない点に注意。
詳しい記述は、「FedoraCore1で作るネットワークサーバ構築ガイド」のP375付近を参照のこと。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です