三步实现Linux下主机之间SSH免密登录

2022-06-22 15:08:29 浏览数 (14)

环境:

系统版本:

代码语言:javascript复制
[root@localhost ~]# cat /etc/redhat-release 
CentOS Linux release 7.5.1804 (Core)       //Centos 7.5系统

安装SSH:

代码语言:javascript复制
[root@localhost ~]# rpm -qa | grep ssh    //是否安装ssh
openssh-7.4p1-16.el7.x86_64
openssh-clients-7.4p1-16.el7.x86_64
openssh-server-7.4p1-16.el7.x86_64
libssh2-1.4.3-10.el7_2.1.x86_64

主机:

代码语言:javascript复制
目标服务器:192.168.2.161
源服务器:192.168.2.195

配置免密:

1.在源服务器端生成密钥

代码语言:javascript复制
[root@localhost ~]# ssh-keygen -t rsa     //无需配置,一路回车
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
/root/.ssh/id_rsa already exists.
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:`[root@localhost ~]# ls ./.ssh/
authorized_keys  id_rsa  id_rsa.pub  known_hosts`
SHA256:8vvhVMFr1nPngJkod CoCBfDxD2aCcO1duiXW9dZE6Y root@localhost.localdomain
The key's randomart image is:
 ---[RSA 2048]---- 
| . oo.        o  |
|   o.oo    . o . |
|   oB ..  . E o  |
|   o   . o   X . |
|  . o   S = %   o|
|   o o *   =   =.|
|    . o . o     .|
|           .     |
|        ..o      |
 ----[SHA256]----- 

2.查看生成的公私钥

代码语言:javascript复制
[root@localhost ~]# ls ./.ssh/
authorized_keys  id_rsa  id_rsa.pub  known_hosts
  • id_rsa 私钥
  • id_rsa.pub 公钥

3.上传公钥至目标服务器端

代码语言:javascript复制
[root@localhost ~]# ssh-copy-id -i ./.ssh/id_rsa.pub root@192.168.2.161
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "./.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.2.161's password: 

Number of key(s) added: 1

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

4.测试免密登录目标服务器端

代码语言:javascript复制
[root@localhost ~]# ssh root@192.168.2.161    //成功免密登录
Last login: Tue Mar 24 17:03:27 2020 from 192.168.2.161

小结:  以上配置只是单向免密,如果需要配置目标服务器与源服务器之间互相免密登录,需要在目标服务器上做同样的操作,将公钥上传至源服务器端即可。

0 人点赞