SSH密钥登录

1.使用 ssh-keygen 创建一个密钥对

服务器和本地都可以生成(此处在服务器上生成)

1
2
3
4
5
6
7
[root@host ~]$ ssh-keygen -t rsa
Enter file in which to save the key (/root/.ssh/id_rsa): <== 按 Enter(选择默认路径)
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase): <== 输入密钥锁码,或直接按 Enter 留空
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. <== 公钥

密钥锁码在使用私钥时必须输入,这样就可以保护私钥不被盗用。当然,也可以留空,实现无密码登录

2.服务器安装公钥

1
2
[root@host ~]$ cd .ssh
[root@host .ssh]$ cat id_rsa.pub >> authorized_keys <== 追加公钥内容到authorized_keys文件中

没有 authorized_keys 文件就自己创建一个
然后修改权限

1
2
[root@host .ssh]$ chmod 600 authorized_keys
[root@host .ssh]$ chmod 700 ~/.ssh <== 至少700,一定要x权限

3.设置 SSH,打开密钥登录功能

编辑 /etc/ssh/sshd_config 文件

RSA 认证

RSAAuthentication yes

开启公钥验证

PubkeyAuthentication yes

验证文件路径

AuthorizedKeysFile .ssh/authorized_keys

禁止密码认证

PasswordAuthentication no

最后重启 sshd

systemctl restart sshd

4.私钥下载

下载私钥到本地的 C:\Users\Username\.ssh 目录,并删除服务器的私钥

5.补充

root 用户也是类似的操作,不过要将公钥放进对应用户的 .ssh 目录(~/.ssh/)。如果在本地生成密钥,则要在服务器自建 .ssh 目录