Linux 如何设置仅密钥才可登陆,提高安全性

作者: 王炳明 分类: Python 教程 发布时间: 2020-10-23 11:17 热度:1,804

首先你要在你的 Linux 机器上(实际上在哪生成都可以,只要你能保存好公钥就行)生成一个密钥对。

1. 生成密钥对

如何生成密钥对呢?

只要在你的云主机上,输入如下命令

[root@iswbm ~]# ssh-keygen -t rsa -C "wongbingming@163.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): /root/.ssh/wbm_rsa
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/wbm_rsa.
Your public key has been saved in /root/.ssh/wbm_rsa.pub.
The key fingerprint is:
SHA256:TmpdxaX6yJtIQqbW1mh8lL69W1rRjA0sCit3qruRZZw wongbingming@163.com
The key's randomart image is:
+---[RSA 2048]----+
|              .  |
|           o o   |
|      .   . *    |
|     . + o + *   |
|    . E S o o +  |
|     % % o o .   |
|    = @ B o +    |
|   . * + + *     |
|    +o  o Bo     |
+----[SHA256]-----+

然后首先会让你输入生成的密钥对要保存的路径,我这边输入 /root/.ssh/wbm_rsa

接下来需要你输入 passphrase(用于加密私钥),我随便设置一个:iswbm.com,当然你也可以不指定,直接回车。

不管你有没有指定,回车后都需要再确认一次。

如果你指定了 passphrase ,但是后面忘记了,也是可以取消的。

方法就是,使用 openssl 指定原来的私钥,重新生成一个

$ openssl rsa -in ~/.ssh/id_rsa -out ~/.ssh/id_rsa_new
$ mv ~/.ssh/id_rsa ~/.ssh/id_rsa.backup
$ mv ~/.ssh/id_rsa_new ~/.ssh/id_rsa
$ chomd 600 ~/.ssh/id_rsa

ssh-keygen 命令执行完成后,在目录下,会多出两个文件

[root@iswbm ~]# ls -l /root/.ssh/wbm_rsa*
-rw------- 1 root root 1766 Oct 23 10:40 /root/.ssh/wbm_rsa
-rw-r--r-- 1 root root  402 Oct 23 10:40 /root/.ssh/wbm_rsa.pub

他们就是密钥对保存的文件:

  • 私钥:保存到你想要登陆该云主机的本地电脑目录,造成不要外泄了(非常重要)
  • 公钥:保存(追加)在对应云主机的 /root/.ssh/authorized_keys 文件中

2. 配置仅密钥登陆

为了使的你的公钥生效,需要你将公钥追加到 目标云主机的 authorized_keys 文件中

$ cat /root/.ssh/wbm_rsa.pub >>/root/.ssh/authorized_keys

然后修改 sshd 的配置,只允许使用密钥才能登陆(其实就是关闭密钥验证),使用 vim 编辑/etc/ssh/sshd_config,将里面的 PasswordAuthentication 改为 no

[root@iswbm ~]# grep PasswordAuthentication /etc/ssh/sshd_config 
PasswordAuthentication no

然后重启 sshd 服务

$ systemctl restart sshd

3. 验证登陆效果

原来我的 Xshell 是可以直接使用密钥进行登陆了,现在却提示我要选择密钥文件了,说明前面的设置有生效了。

Linux 如何设置仅密钥才可登陆,提高安全性

接下来,将前面我生成的 /root/.ssh/wbm_rsa 通过 lrzsz 工具保存到我的本地电脑的目录下。

然后点上面的 浏览 ,出现如下界面,选择 导入 ,选择路径(你上一步保存的路径)

Linux 如何设置仅密钥才可登陆,提高安全性

点击确定后,再输入前面设置的 passphrase ,再点确认就可以访问了。

Linux 如何设置仅密钥才可登陆,提高安全性

文章有帮助,请作者喝杯咖啡?

发表评论