一、serverA 生成秘钥,遇到提示直接敲回车即可
CentOS7 默认使用RSA加密算法生成密钥对,保存在~/.ssh目录下的id_rsa(私钥)和id_rsa.pub(公钥)。也可以使用“-t DSA”参数指定为DSA算法,对应文件为id_dsa和id_dsa.pub, 密钥对生成过程会提示输入私钥加密密码,可以直接回车不使用密码保护。
1 [root@localhost ~]# ssh-keygen 2 Generating public/private rsa key pair. 3 Enter file in which to save the key (/root/.ssh/id_rsa): 4 Enter passphrase (empty for no passphrase): 5 Enter same passphrase again: 6 Your identification has been saved in /root/.ssh/id_rsa. 7 Your public key has been saved in /root/.ssh/id_rsa.pub. 8 The key fingerprint is: 9 SHA256:/gGrlDJN5euMS5aai5feBkEI/0WjEnzPzx1xGtdkKG4 root@localhost.localdomain 10 The key's randomart image is: 11 +---[RSA 2048]----+ 12 |.o.. o +o | 13 | .o.oo . + +.. | 14 | oo.o. .. B | 15 | o..oo E | 16 | ...oSo . | 17 | .o +o+. | 18 | ooB + . | 19 | .oX.= . . | 20 | .o=o=.o . | 21 +----[SHA256]-----+ 22 [root@localhost ~]# ls ~/.ssh/ 23 id_rsa id_rsa.pub known_hosts 24 [root@localhost ~]#
二、解决找不到 .ssh 目录
如果在上面生成秘钥后,执行 cd ~/.ssh 找不到 .ssh 目录,是因为没有使用 ssh 登录过,使用 ssh 登录一下即可生成 .ssh 目录,之后再重新执行 ssh-keygen 生成秘钥即可
1 [root@localhost ~]# ssh localhost 2 The authenticity of host 'localhost (::1)' can't be established. 3 ECDSA key fingerprint is SHA256:DYd7538oOsqpIIDTs01C3G4S6PRE7msA91yUgk9Dzxk. 4 ECDSA key fingerprint is MD5:88:80:21:03:b2:52:6b:06:ff:c7:3b:d5:2d:47:c9:ad. 5 Are you sure you want to continue connecting (yes/no)? yes 6 Warning: Permanently added 'localhost' (ECDSA) to the list of known hosts. 7 root@localhost's password: 8 Last login: Fri Oct 26 16:15:57 2018 from localhost 9 [root@localhost ~]# ls ~/.ssh/ 10 known_hosts 11 [root@localhost ~]# exit 12 登出 13 Connection to localhost closed. 14 [root@localhost ~]#
三、在服务器上安装公钥
[root@ecs-326c-0001 .ssh]# cat id_rsa.pub >> authorized_keys
四、为了确保连接成功,需要设置文件权限
[root@ecs-326c-0001 .ssh]# chmod 600 authorized_keys
[root@ecs-326c-0001 .ssh]# chmod 700 ~/.ssh
五、设置ssh,打开秘钥登录功能
[root@ecs-326c-0001 .ssh]# vim /etc/ssh/sshd_config
去掉注释#
RSAAuthentication yes
PubkeyAuthentication yes
六、重启ssh服务
[root@ecs-326c-0001 ~]# systemctl restart sshd
七、拷贝私钥到PC端,使用软件导入秘钥,然后测试登录
这里需要 使用 使用PuTTYgen 把下载下来的key 转换ppk扩展的SSH 密钥
八、秘钥测试登录成功之后,可以禁用使用密码登录,提高服务器的安全性
[root@ecs-326c-0001 .ssh]# vim /etc/ssh/sshd_config
修改为no
PasswordAuthentication no