Centos 设置密钥登陆并禁用密码
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
打开windows中xshell,尝试使用密钥进行连接
可以看到如上页面,已经不允许通过密码进行登陆了,我们浏览将刚刚下载保存的文件密钥上传至登陆界面,然后点击确定即可登陆。
如有问题请留言,看到后会及时回复!