SSH配置key免密码登录

1.生成key
在本地主机输入以下命令
[root@localhost ~]# ssh-keygen
一直回车
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
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:
SHA256:wmBu68n9DlND6yn18x0T4iEZSUVDI+AhizVB1tCCaho root@localhost.localdomain
The key's randomart image is:
+---[RSA 2048]----+
| oO=o.o+* |
| .+.=oo o o |
| .+ ..o o |
|E oo o . . o |
| + o o S o o . |
|. . . = + o o . |
| . + o o . o |
| o o + o . o |
| + .oo . . |
+----[SHA256]-----+
[root@localhost ~]#
查看生成的key文件
[root@localhost ~]# cd ~/.ssh
[root@localhost .ssh]# ll
total 8
-rw------- 1 root root 1679 Aug 10 09:46 id_rsa
-rw-r--r-- 1 root root 408 Aug 10 09:46 id_rsa.pub
[root@localhost .ssh]#
2.拷贝公钥文件id_rsa.pub到远端主机的指定用户的home路径下(root用户的路径为/root)
[root@localhost .ssh]# scp id_rsa.pub root@192.168.15.129:/root
root@192.168.15.129's password:
id_rsa.pub 100% 408 379.2KB/s 00:00
如上可以看到此时需要输入密码才能拷贝
3.通过SSH登录远端主机
[root@localhost .ssh]# ssh root@192.168.15.129
root@192.168.15.129's password:
Last login: Tue Aug 10 09:45:47 2021 from 192.168.15.1
[root@yuancheng ~]#
**此下的操作在远端主机进行**
此时还需要输入手动输入密码,查看指定用户home目录下有无.ssh文件夹,没有的话创建一个,复制2.中的id_rsa.pub的内容到authorized_keys文件
[root@yuancheng ~]# cd .ssh
[root@yuancheng .ssh]# cat ../id_rsa.pub | tee -a authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDINuohcfbWG8DMHY7mwnAIkp7jglJczOrk1ie5stdSF9GLroot@yuancheng
[root@yuancheng .ssh]# ll
total 12
-rw-r--r-- 1 root root 408 Aug 10 09:58 authorized_keys
[root@yuancheng .ssh]#
4.设置authorized_keys文件的权限为600
[root@yuancheng .ssh]# chmod 600 authorized_keys
[root@yuancheng .ssh]# ll
total 12
-rw------- 1 root root 408 Aug 10 09:58 authorized_keys
[root@yuancheng .ssh]#
5.验证无输入密码登录
[root@localhost .ssh]# ssh root@192.168.15.129
Last login: Tue Aug 10 09:55:20 2021 from 192.168.15.128
[root@yuancheng ~]#
此时已经不需要密码就可以直接ssh登录远端主机了
6.用其他用户登录
[root@localhost .ssh]# ssh orcy@192.168.15.129
orcy@192.168.15.129's password:
用orcy用户登录时仍旧需要输入密码,如需orcy用户免输入密码,需要重复上述操作将公钥文件复制到orcy的home目录下。同一对key也可复制到多台远程主机实现ssh的免输入密码登录。