スカイラボ

~ いろいろと興味のあるものを ~

ssh パスワードなしで Raspberry Pi にログインする

Raspberry Pissh でログインする際に毎回パスワードを入力するのは面倒なので、ssh 公開鍵認証するようにしたいと思います。

f:id:goegoen:20180310225757p:plain

本ページで使用している機器の情報は 環境情報 を参考にしてください。

ssh 公開鍵認証

ssh 鍵の作成

ssh の接続元で以下のコマンドを実行して鍵を作成します。 公開鍵は接続先によって鍵を使い分けることが良しとされているので、コメント の箇所に接続先のヒントとなるような情報を記載しておくと管理しやすいです。(当然、鍵作成の際にファイル名も変更する必要がありますが)
また、今回は暗号強度とパフォーマンスが良いと言われている暗号化方式 ed25519 を使用しています。

$ ssh-keygen -t ed25519 -C "コメント"
Generating public/private ed25519 key pair.
Enter file in which to save the key (/Users/user/.ssh/raspberrypi/id_ed25519): [鍵の格納場所やファイル名]
Enter passphrase (empty for no passphrase):  [パスフレーズ]
Enter same passphrase again: [パスフレーズ]
Your identification has been saved in /Users/user/.ssh/raspberrypi/id_ed25519.
Your public key has been saved in /Users/user/.ssh/raspberrypi/id_ed25519.pub.
The key fingerprint is:
SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx コメント
The key's randomart image is:
+--[ED25519 256]--+
|        ...........  |
|        ...........  |
|        ...........  |
|        ............ |
+----[SHA256]-----+

ssh 公開鍵のコピー

作成した ssh 公開鍵を Raspberry Pi にコピーします。
ssh-copy-id が使える場合は楽にコピーすることができます。

$ ssh-copy-id -i [公開鍵のファイルパス] [ユーザ名]@[raspberry pi の IP アドレス or ホスト名]

実行例
$ ssh-copy-id -i ~/.ssh/raspberrypi/id_ed25519.pub pi@raspberrypi.local
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "id_ed25519_raspberrypi.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
pi@raspberrypi.local's password:  [パスワード(デフォルトは raspberry)]

Number of key(s) added:        1

Now try logging into the machine, with:   "ssh 'pi@raspberrypi.local'"
and check to make sure that only the key(s) you wanted were added.

ためしに、Raspberry Pissh でログインし確認すると .ssh ディレクトリの作成と authorized_keys の作成、パーミションの変更(600)を自動で実行できていることが確認できます。

$ ls -l ~/.ssh
total 4
-rw------- 1 pi pi 149 Mar 10 15:22 authorized_keys

疎通確認

ssh 接続時にパスワード無しでログインできるかを確認します。

$ ssh -i [秘密鍵のファイルパス] [ユーザ名]@[raspberry pi の IP アドレス or ホスト名]

実行例
$ ssh -i ~/.ssh/raspberrypi/id_ed25519 pi@raspberrypi.local

ssh 接続設定

鍵の名前を変更した場合、ssh-i オプションを付与するのが面倒なのでコンフィグファイルに記載します。
システム全体の設定ファイル(/etc/ssh/ssh_config) と ユーザ設定ファイル(~/.ssh/config) で設定可能で、ユーザ設定が優先されます。

記入例
Host rasp1
    HostName raspberrypi.local
    User pi
    IdentityFile ~/.ssh/raspberrypi/id_ed25519
    Port 22
    TCPKeepAlive yes
    IdentitiesOnly yes

上記のように記載しておくと以下のコマンドで ssh 接続できます。

$ ssh rasp1