一、需求背景
在linux测试服务器经常涉及到登陆到另一台服务器,每次输入密码比较繁琐,且root密码会定期修改。
二、基本原理
Linux ssh免密登录的原理基于非对称加密技术。
ssh免密登录的过程如下:
在客户端生成密钥对:用户首次使用ssh时会在客户端(本地计算机)生成一对密钥,包括一个私钥和一个公钥。私钥需要妥善保管,而公钥则用于后续的认证过程。
将公钥拷贝到服务器:用户需要将自己的公钥拷贝到服务器上,并将其重命名为
authorized_keys
,放置在服务器上相应用户的.ssh
目录下。这个文件的名字暗示了它的作用——授权密钥。发起连接请求:当用户从客户端向服务器发起ssh连接请求时,服务器会询问用户的身份。
服务器验证身份:服务器收到连接请求后,会根据请求中的用户名查找对应的
authorized_keys
文件。如果找到了匹配的公钥并且该公钥来自于受信任的客户端IP地址,服务器就会进行下一步。服务器挑战:服务器会随机生成一个字符串,并使用客户端的公钥对它进行加密,然后将加密后的字符串发送回客户端。
客户端响应:客户端收到加密的字符串后,使用自己的私钥进行解密,并将解密后的字符串发回给服务器。
服务器确认:服务器收到解密后的字符串并与自己原先生成的随机字符串进行比对。如果两者一致,服务器就确认客户端的身份无误,并允许其登录,从而完成了免密登录的过程。
ssh免密登录利用了非对称加密的特点,即公钥加密的信息只能通过私钥解密,而私钥仅持有者拥有。即使公钥被他人获取,没有对应的私钥也无法解密信息,从而确保了安全性。此外,整个过程还依赖于服务器端的authorized_keys
文件中存储的公钥与客户端的公钥是否匹配以及客户端的IP地址是否受信任。这些机制共同保障了ssh免密登录的安全性和便捷性。
三、配置流程
1、ssh客户端生成密钥
ssh-keygen -t rsa
[
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
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.
The key fingerprint is:
SHA256:qe7X3XIV267CCxdvIwXyA1r/8H3lvjNVbxSs0KLv48s root@XAYL
The key's randomart image is:
+---[RSA 3072]----+
| . . |
| o . o |
| = + . .|
| = = o .o|
| S . * ..B|
| . . O +B|
| . .ooo.*+=|
| . . o==oo=o|
| .o. .E+=.o=|
+----[SHA256]-----+
2、上传公钥到需要连接的服务器
ssh-copy-id -i id_rsa.pub root@需要连接的服务器IP
[root@XAYL .ssh]# ssh-copy-id -i id_rsa.pub root@39.x.x.21
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "id_rsa.pub"
The authenticity of host '39.x.x.21 (39.x.x.21)' can't be established.
ECDSA key fingerprint is SHA256:MJZ8OZtamIX6rrbp1eMAfnWYapKnD0I9M+WpbBsukCI.
Are you sure you want to continue connecting (yes/no/[fingerprint])? 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@xxxx's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@39.105.206.21'"
and check to make sure that only the key(s) you wanted were added.
3、效果验证
ssh root@39.105.206.21 #发现可以无需输入密码直接登陆
[
Last login: Wed Apr 17 16:16:12 2024 from 122.51.215.96
Welcome to Alibaba Cloud Elastic Compute Service !
[
backup.db logs namesrv output.log startMD.sh store tmp
dump.rdb markdown nohup.out startDM8SQL.sh startRedis.sh test
[
[
logout
Connection to 39.x.x.21 closed.