Linux下快速配置SSH免密码登录

有机器A(192.168.221.128),B(192.168.221.129)。现想A和B想要通过SSH免密码登录。

安装openssh

首先我们需要先查看本机是否已安装openssh服务器(openssh-server)或者客户端(openssh-clients),我们可以通过rpm命令和grep命令查询,在此之前我们要区分服务器和客户端的区别

  • 服务器(openssh-server):控制端,可控制安装客户端的主机
  • 客户端(openssh-clients):被控制端,可被服务器端控制

[root@promote ~]# rpm -qa|grep openssh
openssh-6.6.1p1-22.el7.x86_64
openssh-clients-6.6.1p1-22.el7.x86_64
openssh-server-6.6.1p1-22.el7.x86_64

此处可以看到我们这台主机服务器和客户端都安装了,也就意味着我们可以通过SSH控制别人的主机,别人也可以通过SSH控制我的主机
那如果本机没有安装openssh呢,没事,通过yum命令即可

[root@promote ~]# yum install openssh

这样就可以了。
然后通过service sshd start 命令即可启动服务

[root@promote ~]# service sshd start
Redirecting to /bin/systemctl start sshd.service

出现以上提示即表明启动成功
注意:只要想通过SSH免密码登录的主机都要安装openssh

生成密匙

服务启动成功,我们就可以来生成密匙了,因为我们如果想要SSH免密码登录,那么我们必须要先有密码,我们可以通过ssh-keygen命令来生成密码

[root@promote ~]# 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:
f2:64:e8:ae:5d:7d:af:ea:0c:7a:7e:20:2e:e7:51:d2 [email protected]
The key’s randomart image is:
+–[ RSA 2048]—-+
| |
| |
| |
| o |
| + E |
| ..B.. |
| .o.+.. . |
| .oo+.o.. . |
| .==o.o+…. |
+—————–+

在打完ssh-keygen命令后一路回车就可以了
接下来我们打开根目录下的.ssh文件夹

[root@promote ~]# cd .ssh
[root@promote .ssh]# ll
总用量 16
-rw——-. 1 root root 410 5月 2 22:21 authorized_keys
-rw——-. 1 root root 1675 5月 2 22:19 id_rsa
-rw-r–r–. 1 root root 410 5月 2 22:19 id_rsa.pub
-rw-r–r–. 1 root root 177 5月 2 22:21 known_hosts

我们可以看到有两个文件分别是id_rsa和id_rsa.pub,他们一个是私钥一个是公匙,在SSH免密码登录的时候我们需要要到的是id_rsa.pub(公匙)。
注意:A和B都要生成密匙

添加公匙

我们此处的添加公匙是相当于远程主机而言的,因为我们光产生密码没有用,必须要添加到远程主机里,这样我们才可以通过SSH免密码登录到远程主机上,接下来我们看操作

[root@promote 桌面]# ssh-copy-id 192.168.221.129
The authenticity of host ‘192.168.221.129 (192.168.221.129)’ can’t be established.
ECDSA key fingerprint is be:5c:73:c5:c9:33:6c:90:6b:06:82:46:d2:8d:b2:16.
Are you sure you want to continue connecting (yes/no)? yes
/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
[email protected]’s password:
Number of key(s) added: 1
Now try logging into the machine, with: “ssh ‘192.168.221.129’”
and check to make sure that only the key(s) you wanted were added.

我们通过ssh-copy-id 命令后面加指定的主机ip,就可以自动将我们的公匙赋值到指定的ip主机上了,这样你就可以在本机远程登录添加过公匙的主机了,前提是你必须在添加公匙的时候输入远程主机的密码。
注意:A和B必须都要互相添加公匙

测试

[root@bogon 桌面]# ssh 192.168.221.129
Last login: Tue May 2 22:21:20 2017 from 192.168.221.128
[root@bogon ~]#

我们可以通过ssh命令并加上指定ip(必须要进行过上述步骤),登录到远程主机,并且可以通过exit命令退出。

猜你喜欢

转载自blog.csdn.net/mrliqifeng/article/details/71104741