ID/PASS認証でしかsshを使ったことがないので、鍵認証による接続を学びます。
フロー
1. サーバで秘密鍵と公開鍵を作成
2. クライアントに秘密鍵をコピー
3. 秘密鍵を使ってサーバに接続
サーバで鍵を作成します。-t
は鍵方式、-b
が暗号強度。2048以上を指定。キーファイルとパスフレーズを聞かれますが、今回はデフォルト、ノンパスで作成。
サーバ
# ssh-keygen -t rsa -b 4096
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:gNoQTdPhsMwaUrZaglLFCuSRRj+B3PsGJ730Bjz7AJs root@vm1
The key's randomart image is:
+---[RSA 4096]----+
|++O*=... |
|+Oo*+*. |
|*o=+O o |
|.=.@.B . |
|. o @ * S |
| E * o |
| . + |
| . |
| |
+----[SHA256]-----+
デフォルトでは id_rsa
:秘密鍵 id_rsa.pub
:公開鍵が作成されます。
サーバ
# ls -la ~/.ssh
total 8
drwx------. 2 root root 38 May 12 19:35 .
dr-xr-x---. 3 root root 147 May 12 19:35 ..
-rw-------. 1 root root 3247 May 12 19:35 id_rsa
-rw-r--r--. 1 root root 734 May 12 19:35 id_rsa.pub
公開鍵の名前をauthorized_keys
に変更し、権限を600
に変更します。
サーバ
# mv ~/.ssh/id_rsa.pub ~/.ssh/authorized_keys
# chmod 600 ~/.ssh/authorized_keys
# ls -la ~/.ssh
total 12
drwx------. 2 root root 61 May 12 19:36 .
dr-xr-x---. 3 root root 147 May 12 19:35 ..
-rw-------. 1 root root 734 May 12 19:35 authorized_keys
-rw-------. 1 root root 3247 May 12 19:35 id_rsa
sshd_config
を編集して、鍵認証によるssh接続を有効化します。有効化後はsshdを再起動。
サーバ
# vim -R /etc/ssh/sshd_config
PubkeyAuthentication no
# grep -E Pubkey /etc/ssh/sshd_config
PubkeyAuthentication yes
# systemctl restart sshd.service
以上でサーバの設定は終了。秘密鍵をクライアントにコピーします。(ファイルの中身をコピペでも可)
サーバ
# scp ~/.ssh/id_rsa 192.168.100.100:/work
root@192.168.100.100's password:
id_rsa 100% 3247 7.3KB/s 00:00
クライアントから接続してみます。ログインできれば成功です。
クライアント
# ssh -i /work/id_rsa 192.168.100.137
Last login: Sun May 12 19:41:05 2019 from 192.168.100.100
[root@vm1 ~]#
パスワードによるssh接続を無効化する場合は、サーバのPasswordAuthentication
をno
に変更します。
サーバ
# grep -E Password /etc/ssh/sshd_config
PasswordAuthentication yes
おまけ。sshで接続できない際にフィンガープリントをクリアする方法。
# ssh-keygen -R vm1