实现
基于密钥的安全验证必须为用户自己创建一对密钥,并把共有的密钥放在需要访问的服务器上。当需要连接到SSH服务器上时,客户端软件就会向服务器发出请求,请求使用客户端的密钥进行安全验证。服务器收到请求之后,先在该用户的根目录下寻找共有密钥,然后把它和发送过来的公有密钥进行比较。如果两个密钥一致,服务器就用公有的密钥加密“质询”,并把它发送给客户端软件(putty,xshell等)。客户端收到质询之后,就可以用本地的私人密钥解密再把它发送给服务器,这种方式是相当安全的。
步骤:
1、在客户端生成一对密钥
2、将公钥传输至服务器端某用户的家目录下的 cd .ssh 文件中(多个公钥需要进行追加)
3、测试登录
首先,我们需要生成一对密钥
[root@localhost ~]# ssh-keygen -t rsa -P '' -f "/root/.ssh/id_rsa"
Generating public/private rsa key pair.
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:
f3:80:b8:7e:39:66:e5:6b:6f:f7:b6:5a:c5:50:6d:78 root@localhost.localdomain
The key's randomart image is:
+--[ RSA 2048]----+
| .o|
| ..E|
| .o |
| . . o |
| . . S o|
| . .+ . |
| . + . . |
| . * o . ... |
| .+ o.+...+o. |
+-----------------+
[root@localhost ~]#ssh-copy-id -i /root/.ssh/id_rsa.pub root@172.20.66.6
/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@172.20.66.6's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@172.20.66.6'"
and check to make sure that only the key(s) you wanted were added.
不需要输⼊密码直接登录成功,ssh基于公钥验证
ssh root@172.20.66.8
由于ssh基于公钥验证的⽅式依赖于公私钥,因此私钥的安全性需要的到保障,可以通过加密私钥的⽅法提⾼安全性
[root@CentOS8 ~]#ssh-keygen -p
Enter file in which the key is (/root/.ssh/id_rsa):
Key has comment 'root@CentOS8.localdomain'
Enter new passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved with the new passphrase.
批量部署基于key验证脚本
NET=172.20.66
ssh-keygen -P "" -f /root/.ssh/id_rsa &> /dev/null
rpm -q sshpass &> /dev/null || yum -y install sshpass &> /dev/null
for i in {1..254};do
{
sshpass -p 123456 ssh-copy-id -i /root/.ssh/id_rsa.pub $NET.$i &> /dev/null
}&
done
wait