20240204222141 sshを公開鍵認証にする

raspberrypiraspi ssh server

以下はwsl2のubuntu/windowsのcmd or powershellでやる。

$ ssh-keygen -t ed25519 
Generating public/private ed25519 key pair.
Enter file in which to save the key (/home/kazbo/.ssh/id_ed25519):
Enter passphrase (empty for no passphrase):(Enterを押す)
Enter same passphrase again:(Enterを押す)
Your identification has been saved in /home/kazbo/.ssh/id_ed25519
Your public key has been saved in /home/kazbo/.ssh/id_ed25519.pub
The key fingerprint is:
SHA256: ...  
The key's randomart image is:
+--[ED25519 256]--+
...
+----[SHA256]-----+

.ssh/に id_ed25519 id_ed25519.pub の2つのファイルができている。

$ cat .ssh/id_ed25519.pub

とやって表示される文字列

ssh-ed25519 ...

をコピーしておく。

raspi側で

$ mkdir .ssh
$ touch .ssh/authorized_keys
$ cat >> .ssh/authorized_keys
ssh-ed25519 ... (をコピペしてEnterを押す)
[ctrl+d]を押す
$ chmod 700 .ssh
$ chmod 600 .ssh/authorized_keys

接続確認。wsl側で

$ ssh -i .ssh/id_ed25519 saipi4(自分で設定したraspiのホスト名)
The authenticity of host 'saipi4 (192.168.1.100)' can't be established.
ECDSA key fingerprint is SHA256:UVgt3CY1o1JYPTf8CX5CLWV2UG6rtlvNHUQ4w6mLd8g.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'saipi4' (ECDSA) to the list of known hosts.

Linux saipi4 6.1.0-rpi7-rpi-v8 #1 SMP PREEMPT Debian 1:6.1.63-1+rpt1 (2023-11-24) 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.
Last login: Sun Feb  4 18:47:22 2024 from 192.168.1.62

無事接続できた。 公開鍵で認証できるようになったので、パスワードログインを無効にする。

$ sudo nano /etc/ssh/sshd_config

# PasswordAuthentication yes と書かれている所を、先頭の#を外して、 PasswordAuthentication no にする。 $ sudo service sshd restart でsshd再起動。

以降は

ssh saipi4 -p 4558 

で接続できるっぽい。最初からできたかも。.

cf.