Centos关闭账号密码登录,生成密钥并使用密钥登录
服务器开启账号密码登录容易被暴力破解,使用密钥登录会更安全。
生成公钥和私钥:
ssh-keygen -t rsa
基本上一路回车即可:
[root@user ~]# ssh-keygen -t rsa
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:sYGraime8IxjhgchvZc8QM1q9pLa2l0d/W2gJ1flfiw root@domain.com
The key's randomart image is:
+---[RSA 2048]----+
+----[SHA256]-----+
将公钥追加到authorized_keys:
cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
编辑sshd_config文件:
vi /etc/ssh/sshd_config
注意以下项的值:
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
重启SSH服务:
systemctl restart sshd.service
下载/root/.ssh目录中的id_rsa和id_rsa.pub文件,其中id_rsa是私钥,测试使用私钥登录服务器,如果登录成功,则编辑sshd_config文件,修改以下参数的值,将账号密码登录关闭:
PasswordAuthentication no
重启SSH服务:
systemctl restart sshd.service