1、备份文件
cd /etc/ssh/
scp sshd_config sshd_config.bak
2、生成密钥
[root@centos7-1 ssh]# ssh-keygen -t rsa
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:ERQjqOd4sCPq0XSZvS6nDPxtqKOQtV/vmP79hbzNd4o root@centos7-1
The key's randomart image is:
+---[RSA 2048]----+
| ...=. |
| . . o |
| . . |
| o . + . |
| .B + .S |
|.oB.+ . . . |
|+o.* o. o . |
|o .o++o* . * o|
|.o..+=O=+ ..E +o.|
+----[SHA256]-----+
[root@centos7-1 ssh]# ll /root/.ssh/
total 8
-rw-------. 1 root root 1675 Jun 12 10:37 id_rsa
-rw-r--r--. 1 root root 396 Jun 12 10:37 id_rsa.pub
3、安装公钥
[root@centos7-1 ssh]# cd /root/.ssh/
[root@centos7-1 .ssh]# cat id_rsa.pub >> authorized_keys
[root@centos7-1 .ssh]# chmod 600 authorized_keys
[root@centos7-1 .ssh]# chmod 700 ~/.ssh
[root@centos7-1 .ssh]# ll
total 12
-rw-------. 1 root root 396 Jun 12 10:39 authorized_keys
-rw-------. 1 root root 1675 Jun 12 10:37 id_rsa
-rw-r--r--. 1 root root 396 Jun 12 10:37 id_rsa.pub
4、修改文件
#删除以下配置行
[root@centos7-1 ~]# sed -i '/PasswordAuthentication.*/d' /etc/ssh/sshd_config
[root@centos7-1 ~]# sed -i '/PubkeyAuthentication.*/d' /etc/ssh/sshd_config
[root@centos7-1 ~]# sed -i '/RSAAuthentication.*/d' /etc/ssh/sshd_config
[root@centos7-1 ~]# sed -i '/AuthorizedKeysFile.*/d' /etc/ssh/sshd_config
#新增以下配置行
[root@centos7-1 ~]# cat >>/etc/ssh/sshd_config<<EOF
PasswordAuthentication no
PubkeyAuthentication yes
RSAAuthentication yes
AuthorizedKeysFile /root/.ssh/authorized_keys
EOF
5、重启sshd服务
[root@centos7-1 .ssh]# systemctl restart sshd
6、尝试密钥登录
将文件 id_rsa下载保存到本地
[root@centos7-1 .ssh]# ll
total 12
-rw-------. 1 root root 396 Jun 12 10:39 authorized_keys
-rw-------. 1 root root 1675 Jun 12 10:37 id_rsa
-rw-r--r--. 1 root root 396 Jun 12 10:37 id_rsa.pub
7、登录测试即可