SSH公钥登录原理(参考:https://www.cnblogs.com/scofi/p/6617394.html):
主要有两种登录方式:第一种为密码口令登录,第二种为公钥登录
一、密码口令登录
通过密码进行登录,主要流程为:
1、客户端连接上服务器之后,服务器把自己的公钥传给客户端
2、客户端输入服务器密码通过公钥加密之后传给服务器
3、服务器根据自己的私钥解密登录密码,如果正确那么就让客户端登录
二、公钥登录
公钥登录是为了解决每次登录服务器都要输入密码的问题,流行使用RSA加密方案,主要流程包含:
1、客户端生成RSA公钥和私钥
2、客户端将自己的公钥存放到服务器
3、客户端请求连接服务器,服务器将一个随机字符串发送给客户端
4、客户端根据自己的私钥加密这个随机字符串之后再发送给服务器
5、服务器接受到加密后的字符串之后用公钥解密,如果正确就让客户端登录,否则拒绝。这样就不用使用密码了。
理解了原理之后配置就很简单了,以下使用环境为EHEL 7 系统
一、Linux端的配置
1、客户端生成密钥,传送到服务器:
[root@localhost ~]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): //密钥文件保存的路径,不修改,直接回车
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase): //是否为密钥设置密码,不设置直接回车
Enter same passphrase again: //再次确认密码
[root@localhost ~]# cat .ssh/id_rsa.pub //查看生成的公钥信息
[root@localhost ~]# cat .ssh/id_rsa //查看生成密钥信息
2、将生成的公钥传送到服务器:
[root@localhost ~]# ssh-copy-id 192.168.10.10
A key fingerprint is e4:bd:ba:43:01:23:ae:67:05:aa:d3:85:c5:78:60:68.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.10.10's password: //输入远程服务器的root密码
Number of key(s) added: 1
Now try logging into the machine, with: "ssh '192.168.10.10'"
and check to make sure that only the key(s) you wanted were added.
3、服务器端无需任何操作就可以不使用密码ssh远程服务器了。
[root@localhost ~]# ssh 192.168.10.10
二、windows端使用xshell工具(或用puttygen生成密钥)
4、打开Xshell软件,点击菜单栏的工具 > 用户密钥管理者 > 生成,弹出生成密钥对话框,默认即可,点击下一步:
5、生成密钥对完成后,下一步;
6、密钥名称先不修改,这里的密码是对密钥进行加密,这样别人拿到你的密钥没有密码也使用不了,这里只是做个演示,不修改了,下一步:
7、提示你没有修改密码,点击是,仍然继续:
8、点击 保存为文件 ,把公钥保存到本地电脑:
9、先远程Linxu系统,将电脑上的公钥文件拖至会话窗口,将文件传送到Linux系统里:
三、服务器端配置:
10、在root目录下创建带有.ssh隐藏属性的目录,在Linux端上传公钥至服务器会自动创建该目录,如果已经存在改目录,这一步跳过:
[root@localhost .ssh]# mkdir /root/.ssh
11、将公钥文件移动到.ssh/目录下,因为在Linux端已上传了一份公钥文件(上传时会自动重命名为:authorized_keys)到服务器,所以移动公钥文件的同时必须重命名为别的名字来与之区别,这里就重命名为:authorized_1_keys
[root@localhost ~]# mv id_rsa_2048.pub .ssh/authorized_1_keys
12、因为公钥是从windows系统上传,所以需要修改.ssh目录下的所有文件与.ssh目录SElinux上下文的值一致,当然也可以关闭SElinux:
[root@localhost ~]# /sbin/restorecon -Rv /root/.ssh
或:临时关闭SElinux
[root@localhost ~]# setenforce 0
13、[root@localhost ~]# vim /etc/ssh/sshd_config
1)、增加一行从Windows端上传过来的公钥文件(指定文件的路径):
2)、将78行的使用密码认证的配置把yes改成no,这样就仅能使用密钥这台服务器。
14、重启sshd服务并加入开机自启动:
[root@localhost .ssh]# systemctl restart sshd
[root@localhost .ssh]# systemctl enable sshd
15、这样不管Linux或Windows端都可以通过SSH远程Linux的时候使用密钥登录: