Linux配置ssh免密登录

所有操作都是在一台机器上完成,如果需要配置“A服务器”免密登录到“B服务器”,所有操作只需要在“A服务器”上操作,只需要知道“B服务器”的密码即可,免登录是单向的

ssh-keygen生成公钥和私钥

一直回车即可,默认是rsa加密

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[root@localhost ~]# 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:
e4:81:e4:0e:2e:db:cb:5c:03:55:ca:0d:68:f0:90:81 root@localhost.localdomain
The key's randomart image is:
+--[ RSA 2048]----+
| .++ .o . |
|E .oo+ * |
| .o * + |
| . + o . |
| . o . S |
| + . |
| . . o |
| o o . |
| + |
+-----------------+

此时在你执行命令的目录下会生成一个.ssh文件夹,里面会有秘钥信息

1
2
3
4
[root@localhost ~]# ll .ssh/
total 8
-rw-------. 1 root root 1675 Sep 11 19:53 id_rsa
-rw-r--r--. 1 root root 408 Sep 11 19:53 id_rsa.pub

ssh-copy-id将公钥推送到远端服务器上

执行如下命令,root是要给远端服务器的免密登录的用户,后面是远端服务器的ip,执行过程中输入远端服务器密码即可

1
2
3
4
5
6
[root@localhost ~]# ssh-copy-id root@192.168.221.130
The authenticity of host '192.168.221.130 (192.168.221.130)' can't be established.
RSA key fingerprint is ee:b6:99:91:00:62:d7:25:4b:10:dc:e8:e6:ef:60:88.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.221.130' (RSA) to the list of known hosts.
root@192.168.221.130's password:

测试登录

发现已经登录到远端服务器,只需要输入exit即可返回

1
2
3
4
5
6
7
8
9
10
11
[root@localhost ~]# ssh 192.168.221.130
Last login: Wed Sep 11 19:46:01 2019 from 192.168.221.1
[root@localhost ~]# ifconfig
eth0 Link encap:Ethernet HWaddr 00:0C:29:7E:30:08
inet addr:192.168.221.130 Bcast:192.168.221.255 Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fe7e:3008/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:1902 errors:0 dropped:0 overruns:0 frame:0
TX packets:1181 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:197332 (192.7 KiB) TX bytes:175520 (171.4 KiB)