LoginSignup
0
1

More than 5 years have passed since last update.

CentOS7 公開鍵認証によるssh接続の設定

Last updated at Posted at 2019-05-12

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接続を無効化する場合は、サーバのPasswordAuthenticationnoに変更します。

サーバ
# grep -E Password /etc/ssh/sshd_config
PasswordAuthentication yes


おまけ。sshで接続できない際にフィンガープリントをクリアする方法。

# ssh-keygen -R vm1
0
1
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
1