CentOS 6.5下设置主机之间的SSH免密登录

时间:2022-12-30 14:25:16

Environment
HostA: 172.22.35.147
HostB: 172.22.35.177


现在需要从HostA通过ssh登录到HostB上,怎么样才能不输入登录账户的密码就登陆远程主机呢?
首先:我们需要在HostA上执行

[root@Slave3 ~]# ssh-keygen -t rsa -P ''
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
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:
c2:5c:4a:a4:5e:19:00:b7:20:3e:dc:2f:5e:e3:e0:f6 root@Slave3
The key's randomart image is:
+--[ RSA 2048]----+
|. o.o.o |
|o..o + o |
| + .o + . |
| ...= o |
| o.+= S |
| o = .. |
| + . |
| . . |
| E |
+-----------------+

生成当前主机的公钥和私钥
-t 指定使用的加密算法
-P 执行密码
-f 指定生成的秘钥公钥 文件,可以省略
然后执行
ssh-copy-id root@172.22.35.177
将当前主机的公钥拷贝到远程主机上,这时候系统会提示是否将公钥加入到远程主机的受信任列表里
输入yes

[root@Slave3 ~]# ssh-copy-id root@172.22.35.177
The authenticity of host '172.22.35.177 (172.22.35.177)' can't be established.
RSA key fingerprint is 96:bc:a7:29:cd:d8:15:c9:46:fb:b9:24:4f:99:3b:5f.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '172.22.35.177' (RSA) to the list of known hosts.
root@172.22.35.177's password:
Now try logging into the machine, with "ssh 'root@172.22.35.177'", and check in:

.ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.

最后系统提示成功将当前主机的公钥加入到远程主机的受信任列表了。
然后试着登录到HostB,这时候就不用输入密码就可以登录了。

[root@Slave3 ~]# ssh 172.22.35.177
Last login: Sat Apr 2 23:45:16 2016
[root@localhost ~]# ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 172.22.35.185 netmask 255.255.255.128 broadcast 172.22.35.255
inet6 fe80::8c67:94ff:fe32:ff70 prefixlen 64 scopeid 0x20<link>
ether 8e:67:94:32:ff:70 txqueuelen 1000 (Ethernet)
RX packets 6740037 bytes 1172894756 (1.0 GiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 316115 bytes 45832039 (43.7 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

eth1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 172.22.35.177 netmask 255.255.255.128 broadcast 172.22.35.255
inet6 fe80::c8d7:31ff:fe0e:ca0d prefixlen 64 scopeid 0x20<link>
ether ca:d7:31:0e:ca:0d txqueuelen 1000 (Ethernet)
RX packets 20540422 bytes 1056445529 (1007.5 MiB)
RX errors 0 dropped 14296 overruns 0 frame 0
TX packets 12 bytes 816 (816.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

当然你也可以将当前主机的公钥使用scp 拷贝到远程主机上。然后追加到远程主机的authorized_keys里,但是第一种方法不知道比这个方法高明到哪里去了!


详细的原理可以参见这篇文章
SSH 原理和基本使用:ssh 安全配置 以及ssh key 认证登录