LoginSignup
0
4

More than 3 years have passed since last update.

ラズパイにSSHするときに毎回パスワードを入力するのが面倒くさいので鍵認証の設定をしてみた。(mac/Windows)

Last updated at Posted at 2020-10-18

やってみると意外と簡単。
パスワード入力が不要になるので、やって見る価値はあるかと。

SSHされる側(ホスト側のRaspberry Pi)での設定

SSHサーバーの設定変更

デフォルトでは鍵認証が有効になっていないので、設定を変更します。

RaspberryPi
sudo sed -i 's/#PubkeyAuthentication/PubkeyAuthentication/g' /etc/ssh/sshd_config
sudo sed -i 's/#AuthorizedKeysFile/AuthorizedKeysFile/g' /etc/ssh/sshd_config

sudo systemctl restart sshd.service

SSHで使用する鍵の作成

RaspberryPi
pi@raspberrypi4:~ $ ssh-keygen -t rsa -b 4096 -C "moritalous"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/pi/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/pi/.ssh/id_rsa.
Your public key has been saved in /home/pi/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:xxxxxxxxx
The key's randomart image is:
+---[RSA 4096]----+
|xxxxxxxxxxxxxxxxx|
|xxxxxxxxxxxxxxxxx|
|xxxxxxxxxxxxxxxxx|
|xxxxxxxxxxxxxxxxx|
|xxxxxxxxxxxxxxxxx|
|xxxxxxxxxxxxxxxxx|
|xxxxxxxxxxxxxxxxx|
|xxxxxxxxxxxxxxxxx|
|xxxxxxxxxxxxxxxxx|
+----[SHA256]-----+
pi@raspberrypi4:~ $ 

~/.ssh/にid_rsa(秘密鍵)とid_rsa.pub(公開鍵)が作成されます。

公開鍵の方をauthorized_keysに登録します。

RaspberryPi
cat .ssh/id_rsa.pub >>  ~/.ssh/authorized_keys

SSHする側(クライアント側のmac/Windows)での設定

秘密鍵の配置と権限変更

ホスト側で作成したid_rsa(秘密鍵)を持ってきます。
私は~/.ssh/raspberrypi4/の配下(Windowsの場合は%USERPROFILE%\.ssh\raspberrypi4)に保存しました。

権限変更はmacの場合のみ。Windowsの場合は不要でした。

macのみ
chmod 600 ~/.ssh/raspberrypi4/id_rsa

設定ファイルの作成

macの場合もWindowsの場合も、IdentityFileの指定は同じです。Windowsだからといって%USERPROFILE%と書いたり、エスケープ文字が\(円)になったりしません。

~/.ssh/config
Host raspberrypi4.local
  HostName raspberrypi4.local
  User pi
  IdentityFile ~/.ssh/raspberrypi4/id_rsa

Host raspberrypi3.local
  HostName raspberrypi3.local
  User pi
  IdentityFile ~/.ssh/raspberrypi3/id_rsa

これで、パスワードなしでSSH接続できます。

mac/Windows
$ ssh pi@raspberrypi4.local
Linux raspberrypi4 5.4.51-v8+ #1333 SMP PREEMPT Mon Aug 10 16:58:35 BST 2020 aarch64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
You have new mail.
Last login: Sun Oct 18 16:26:01 2020 from 192.168.0.8

pi@raspberrypi4:~ $ 

VSCodeのSSH接続の拡張機能(Remote - SSH)を使った場合もパスワード無しで、接続されます。
わーい
EC2の接続に必要な鍵もこうやって管理すればいいんですね。

0
4
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
0
4