天天看點

在CentOS8中設定SSH密鑰

最流行的兩種SSH身份驗證機制是基于密碼的身份驗證和基于公鑰的身份驗證。使用SSH密鑰通常比傳統的密碼身份驗證更安全和友善。

環境

用戶端:CentOS8 192.168.43.137

服務端:CentOS8 192.168.43.139

建立SSH公私鑰

通過輸入以下指令,生成新的4096位的SSH密鑰對:

[[email protected] ~]# ssh-keygen -t rsa -b 4096
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
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:ycOtSDK8ud2kd6EH7OxoQuc1BFb1HJ3T/kvAQJt0LrI [email protected]
The key's randomart image is:
+---[RSA 4096]----+
|       ...oo.o o |
|      o   .+=.+ .|
|     . . . +=. o |
|   .   o.oo .o  .|
|    + .oSE.   . .|
|    .*..=o.    ..|
|   .oo.+o+ .  . .|
|    .oo== o    . |
|    .o+ooo       |
+----[SHA256]-----+
      
在CentOS8中設定SSH密鑰

想要驗證是否生成了新的SSH密鑰對,使用

ls -l

指令檢視~/.ssh目錄是否有剛才生成的檔案:

[[email protected] ~]# ll ~/.ssh/
total 8
-rw------- 1 root root 3389 May 13 08:26 id_rsa
-rw-r--r-- 1 root root  752 May 13 08:26 id_rsa.pub
      
在CentOS8中設定SSH密鑰

将公鑰複制到遠端伺服器,使用

ssh-copy-id

實用程式,輸入遠端伺服器的root密碼:

[[email protected] ~]# ssh-copy-id [email protected]
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '192.168.43.139 (192.168.43.139)' can't be established.
ECDSA key fingerprint is SHA256:7O1oIOooh4NZG87aC3v1Zz/vcTXkjOhQBnlkY0CD4y0.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
Password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '[email protected]'"
and check to make sure that only the key(s) you wanted were added.
      
在CentOS8中設定SSH密鑰

也可以使用以下指令複制公鑰:

[[email protected] .ssh]# cat ~/.ssh/id_rsa.pub | ssh [email protected] "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
      

使用密鑰登入伺服器

使用以下指令登入ssh伺服器:

[[email protected] ~]# ssh 192.168.43.139
Last login: Tue May 12 12:33:41 2020 from 192.168.43.137
      
在CentOS8中設定SSH密鑰

關閉密碼認證

登入伺服器端,關閉密碼認證:

[[email protected] ~]# ssh 192.168.43.139
Last login: Tue May 12 12:33:41 2020 from 192.168.43.137
[[email protected] ~]# vim /etc/ssh/sshd_config
搜尋一下三條,将選項改為No
PasswordAuthentication no
ChallengeResponseAuthentication no
UsePAM no
      
在CentOS8中設定SSH密鑰

重新開機sshd服務:

[[email protected] ~]# systemctl restart sshd
      

總結

可以使用同一密鑰管理多個遠端伺服器。預設情況下,SSH的端口是TCP 22。更改預設SSH端口可降低自動攻擊的風險。

繼續閱讀