在Linux服务器、客户端中构建密钥对验证进行远程连接

构建密钥对验证SSH体系的基本过程包括四步:
在Linux服务器、客户端中构建密钥对验证进行远程连接

SSH客户端:192.168.1.1
SSH服务器:192.168.1.2

1、在客户端创建密钥对:

[root@localhost /]# ssh-keygen -t ecdsa           
# “ -t ” 用来指定加密算法,这里使用ecdsa,还有一个是dsa。
Generating public/private ecdsa key pair.
Enter file in which to save the key (/root/.ssh/id_ecdsa):      
#指定私钥存放位置,若直接按enter,则默认保存在宿主目录中的隐藏文件夹中.ssh下。
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):       #设置私钥短语
Enter same passphrase again:      #确认所设置的短语

                ..........................
+---[ECDSA 256]---+
|     .. =oo.+o.  |
|      .=.= *.o.oo|
|      +.= = B oo+|
|     . = = B . = |
|    . o S o . =  |
|     + o = o . . |
|      = = . .    |
|       + E .     |
|          .      |
+----[SHA256]-----+
当出现以上提示,则表示创建成功。

私钥短语用来对私钥文件进行保护,在进行远程连接时必须要输入正确的私钥短语。若不设置私钥短语,那么在连接时,就实现了无口令登录,不建议这样做。

2、将公钥文件上传至SSH服务器(这里使用简单的方法,一条命令搞定上图中的第二步和第三步):

[root@localhost /]# ssh-copy-id -i ~/.ssh/id_ecdsa.pub [email protected]
#  “ -i ” 用来指定公钥文件,“ lisi”是SSH服务器的用户
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_ecdsa.pub"
The authenticity of host '192.168.1.2 (192.168.1.2)' can't be established.
ECDSA key fingerprint is SHA256:uArLTW6MJOgdp+OZQbywwJdlGUEKDmOC62CnU6zyCgA.
ECDSA key fingerprint is MD5:b8:ca:d6:89:a2:42:90:97:02:0a:54:c1:4c:1e:c2:77.
Are you sure you want to continue connecting (yes/no)? yes              #输入“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
[email protected]'s password:                  #输入用户“lisi” 的密码

#验证密码后,会自动将公钥文件添加到SSH服务器“ lisi ”用户的宿主目录下的.ssh/authorized_key
Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '[email protected]'"
and check to make sure that only the key(s) you wanted were added.
出现上述提示后,则表示上传成功。

4、在客户端使用密钥对验证:

[root@localhost /]# ssh [email protected]            #请求连接
Enter passphrase for key '/root/.ssh/id_ecdsa':             
#输入生成密钥时设置的私钥短语,而不是lv用户的密码了
Last login: Sat May 18 22:13:51 2019
[lv@localhost ~]$ id               #查询当前用户的id,结果为登录成功
uid=1000(lisi) gid=1000(lisi) 组=1000(lisi),10(wheel) 环境=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

若在配置中遇到错误,则要注意是否与sshd服务的配置文件中发生了冲突,因为sshd服务的配置项是否启用了密钥对验证和指定的公钥库文件位置都对远程连接有影响。sshd服务配置项的解释具体参考这里: https://blog.51cto.com/14154700/2402246

猜你喜欢

转载自blog.51cto.com/14154700/2402273