配置linux下ssh免密登录

Linux笔记 2020年05月17日

本篇笔记记录了在CentOS下配置ssh免密登录的方法

测试虚拟机

192.168.75.238
192.168.75.239

配置从238免密登录239

1:生成密钥

使用命令 ssh-keygen 生成密钥

ssh-keygen -t rsa -P ''

-P '' 表示密码为空
一路回车

[root@localhost ~]# 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:
SHA256:YP67CA4nkHspm8HC7yv+5YvQKcnRF3MVUMaVu+htssA root@localhost.localdomain
The key's randomart image is:
+---[RSA 2048]----+
|       .+=o..    |
|        o. .     |
|     oo.    .    |
| ..  o+.   .     |
|o. . .. S . .    |
|+o+.o .. . .     |
|=B=oo. Eo .      |
|.B+=+. ..+ o     |
|+.+*ooo oo+      |
+----[SHA256]-----+
[root@localhost ~]# 

以上命令会在用户家目录下的.ssh目录下生成两个密钥文件

[root@localhost ~]# ll ~/.ssh/
总用量 12
-rw-------  1 root root 1679 5月  17 18:21 id_rsa
-rw-r--r--  1 root root  408 5月  17 18:21 id_rsa.pub
-rw-r--r--. 1 root root  176 5月  17 14:46 known_hosts
[root@localhost ~]# pwd
/root

id_rsa : 生成的私钥文件
id_rsa.pub : 生成的公钥文件
know_hosts : 已知的主机公钥清单
如果希望ssh公钥生效需满足至少下面两个条件:
1:ssh目录的权限必须是700
2:ssh/authorized_keys(如果有)文件权限必须是600

2:将公钥发送给要免密登录的服务器

使用命令ssh-copy-id发送公钥到目标主机的~/.ssh目录下authorized_keys文件中

[root@localhost .ssh]# ssh-copy-id -i ~/.ssh/id_rsa.pub 192.168.75.239
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/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@192.168.75.239's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '192.168.75.239'"
and check to make sure that only the key(s) you wanted were added.

[root@localhost .ssh]#

在第5行处输入239服务器的root密码

3:免密登录239

ssh 192.168.75.239

执行ip addr

[root@localhost ~]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0c:29:4a:c5:2a brd ff:ff:ff:ff:ff:ff
    inet 192.168.75.239/24 brd 192.168.75.255 scope global noprefixroute dynamic ens33
       valid_lft 1105sec preferred_lft 1105sec
    inet6 fe80::d8a6:3175:325c:3398/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
[root@localhost ~]# 

配置完毕!