使用 SSH Key 登入 Raspberry Pi

Photo by Vishnu Mohanan on Unsplash
Photo by Vishnu Mohanan on Unsplash

最近入手了 Raspberry Pi 4 Model B,藉由這個機會記錄一下在設定樹莓派的瑣碎過程,至於安裝樹莓派的方式在網路上有需多資料可以查詢,這裡就不闡述安裝的方式了。

After Installation Raspaberry Pi

在完成樹莓派的安裝後,預設是透過 ssh + password 的方式登入,不過我希望可以用更安全的方式,所以想改用 ssh + key 的方式進行登入。

Generation SSH Key

首先,需要在你的電腦上使用 ssh-keygen 來產生對應的 public key(公鑰)& private key(私鑰),這產生的 ssh key 會存放在 .ssh 的目錄下, 你可以簡單地透過 ssh-keygen 產生,它會產生一組 id_rsa 以及 id_rsa.pub 的 key,目錄下的 id_rsa 已經另有其他用途,所以另外產生一組 ssh key for RPi 使用,這裡可以根據自己的狀況選擇:

$ ssh-keygen -t rsa -f ~/.ssh/rpi-test
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /Users/user/.ssh/rpi-test.
Your public key has been saved in /Users/user/.ssh/rpi-test.pub.
The key fingerprint is:
SHA256:h5D6LrHwoIz44EkbXmMoo0cRAYSo7p6Vnvk4HjCm7I0 [email protected]
The key's randomart image is:
+---[RSA 3072]----+
|=o.. |
|o . . |
|. . o |
|. . . . . |
|.+ .. S . |
|+.B o. . |
|XB @ o. |
|@=&.X. |
|oEoBoo. |
+----[SHA256]-----+

接著切換到 .ssh 目錄下可以看到產生的 rpi-test 公鑰和私鑰:

$ ls
id_rsa id_rsa.pub known_hosts rpi-test rpi-test.pub

Copying SSH Public Key To RPi

完成 SSH key 的產生後,需要透過 ssh-copy-id 的指令將 public key 複製到遠端的樹莓派上:

$ ssh-copy-id ~/.ssh/rpi-test.pub pi@your-ip
/usr/local/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "rpi-test.pub"
/usr/local/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/local/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
bash: warning: setlocale: LC_ALL: cannot change locale (en_US.UTF-8)
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'pi@your-ip'"
and check to make sure that only the key(s) you wanted were added.

接著就可以使用 ssh pi@your-ip 登入到你的樹莓派:

Linux raspberrypi 5.10.63-v7l+ #1459 SMP Wed Oct 6 16:41:57 BST 2021 armv7l
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.
Last login: Fri Oct 22 20:00:00 2021 from 192.168.1.11
pi@raspberrypi:~ $

這時候可以透過 by key 或者是 by password 的方式(如果沒有 key 的話)登入,如果想要把輸入密碼的方式關掉的話,需要進入到樹莓派設定。

Setting SSH Configuration Without Password Login

登入到遠端的樹莓派之後,切換到 /etc/ssh 的目錄下:

$ cd /etc/ssh

接著編輯 sshd_config 設定檔案,加入以下這三行:

PasswordAuthentication no
ChallengeResponseAuthentication no
UsePAM no

一旦設定儲存完成,重新啟動 SSH 服務:

$ sudo systemctl restart ssh

最後你可以在 terminal 開另外一個 tab 來驗證是否成功:

$ ssh pi@your-ip -o PubKeyAuthentication=no
pi@your-ip: Permission denied (publickey).

Reference