ssh-key认证的原理就是用户将自己的公钥发送给远程主机上;登录的时候,远程主机会向用户发送一段随机字符串,用户用自己的私钥加密后,再发回来;远程主机用事先的公钥进行解密,如果成功就证明用户是可信的,直接允许登录shell,不再要求密码。
实验环境:
server1 172.25.55.1 本地主机
server2 172.25.55.2 远程主机
一、key的生成
** ssh-keygen
[root@server1 ~]# ssh-keygen
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:
92:78:88:f2:5b:5f:62:70:95:43:38:b8:06:16:30:8f root@server1.example.com
The key’s randomart image is:
+–[ RSA 2048]—-+
|o… . .. |
| +o . o. . |
|E… . .+ |
| .oo o . |
|. ..+ = S |
| o + . |
| . . o . |
| o o o |
| . . |
+—————–+
生成过程中,会提示输入密钥和公钥的存放位置和密码,直接按回车键跳过就好了;
生成的密钥和公钥就存放在用户家目录下的.ssh目录下:
** cd /root/.ssh
** ls
[root@server1 ~]# cd /root/.ssh/
[root@server1 .ssh]# ls
id_rsa id_rsa.pub known_hosts
二、sshd的服务配置:
** vim /etc/ssh/sshd_config
PermitEmptyPasswords no ##是否允许root用户通过sshd的认证
PasswordAuthentication no ##开启或关闭用户密码认证
AllowUsers westos ##用户白名单,只允许在名单中出现的用户使用sshd服务
重新启动sshd服务:
** /etc/init.d/sshd restart
[root@server1 .ssh]# /etc/init.d/sshd restart
Stopping sshd: [ OK ]
Starting sshd: [ OK ]
三、上传公钥给远程主机
** ssh-copy-id -i /root/.ssh/id_rsa.pub westos@172.25.55.2
[root@server1 .ssh]# ssh-copy-id -i /root/.ssh/id_rsa.pub westos@172.25.55.2
westos@172.25.55.2’s password:
Now try logging into the machine, with “ssh ‘westos@172.25.55.2’”, and check in:
.ssh/authorized_keys
to make sure we haven’t added extra keys that you weren’t expecting.
查看上传是否成功:
** cd /home/westos/.ssh
** ls
[westos@server2 ~]
cd/home/westos/.ssh/[westos@server2.ssh]
ls
authorized_keys
上传成功;
四、测试(server1)
** ssh westos@172.25.55.1
[root@server1 .ssh]# ssh westos@172.25.55.2
Last login: Tue Jan 2 16:22:51 2018 from server1.example.com
[westos@server2 ~]$
这时可以看见正在登录的用户已经变成server2的westos用户了;