开始

生成证书文件

建议服务端执行

  • 路径填写为 /root/.ssh/certificate
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
root@test:~# ssh-keygen -m pem -t rsa -b 2048
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): /root/.ssh/certificate
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/certificate
Your public key has been saved in /root/.ssh/certificate.pub
The key fingerprint is:
SHA256:gIBHeMyAlD66hhgo8daRjSxw0KTmAy/P9z3R+HHauS0 root@puzzl74364
The key's randomart image is:
+---[RSA 2048]----+
|=%= |
|=oB. . |
|+* ..+. |
|=+. = .. |
|+=oo . So |
|=++ . o o . |
|++o . o = . |
|+. . . .. o E. |
|. . .. .o. |
+----[SHA256]-----+

新版会生成 openssh 证书 个别不支持 所以加入了 -m pem -t rsa -b 2048 参数

复制证书文件到本地

/root/.ssh 目录中应该生成了 certificatecertificate.pub 这两文件

其中 certificate 就是咱们等哈要用到的证书 咱们先剪贴到本地保存起来

再把 certificate.pub 重命名成 authorized_keys

1
mv certificate.pub authorized_keys

配置服务端在证书

打开 /etc/ssh/sshd_config 文件

找到这 PubkeyAuthenticationAuthorizedKeysFile 这两行 去掉前面的注释

含义

  • PubkeyAuthentication 是否打开证书验证
  • AuthorizedKeysFile 证书验证文件 采用登录用户目录下 .ssh/authorized_keys.ssh/authorized_keys2 进行验证, 我们登录的 root 账户的话 就在 /root/.ssh/authorized_keys 这个路径查找证书,如果是其他账户 就在 /home/账户名/.ssh/authorized_keys 这个路径下查找证书进行验证,可以添加多个路径并用 空格 隔开,这样就有了多私钥可以用于登录了.

修改前

1
2
#PubkeyAuthentication yes
#AuthorizedKeysFile .ssh/authorized_keys .ssh/authorized_keys2

修改后

1
2
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys .ssh/authorized_keys2

验证是否修改成功

重启 ssh 守护进程

1
systemctl restart sshd

采用刚剪贴到本地的证书在打开新窗口的情况下进行登录

1
ssh -i ./certificate root@host

不出意外的话 这就登录成功了

其他操作

关闭密码登录

/etc/ssh/sshd_config 文件中

PasswordAuthentication

  • yes 采用密码验证 默认 未出现此字段或注释
  • no 关闭密码验证
1
PasswordAuthentication no

更改ssh端口号

1
Port 22

参考地址