五步轻松实现linux免密登录

SSH英文全程Secure SHELL,是被广泛用于linux系统安全可靠的远程命令执行程序,而用来进行安全文件传输的SCP同样基于SSH的安全协议。

当服务器比较多的时候,每次都要频繁输入密码显得特别麻烦,那么怎样免密码登录且做到安全可靠呢,当然是可以的。这里我们将分为五步完成RHEL/CentOS 7.x/6.x/5.x and Fedora等linux类型服务器的免密码登录。

《五步轻松实现linux免密登录》

先看一下环境


SSH 客户端 : 192.168.1.12 ( Mac )
SSH 远程主机 : 192.168.1.11 ( CentOS 7 )

本文将介绍从mac免密码登录到远程centos 7服务器。

1.在本地mac上生成SSH-Kegen秘钥对

首先在自己的mac终端使用下面命令生成秘钥对


➜  Desktop ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/yourname/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /Users/yourname/.ssh/id_rsa.
Your public key has been saved in /Users/yourname/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:BEkeApPIU8NG4bmzDwF/KSG97N7CyS7+4nQpt3+M2+w tengbozhang@tengbos-Air
The key's randomart image is:
+---[RSA 2048]----+
|..*Bo.+.         |
|.o++oo.o         |
| oo=  . .        |
|  = + ..         |
|   O o  S        |
|  . B            |
| ooB. o          |
|.o===.oo         |
|oo==o=+E         |
+----[SHA256]-----+

2.在远程linux主机centos 7 上创建.ssh目录

使用下面命令从mac终端登录到centos 7 并执行创建.ssh并使用创建文件夹命令


➜  Desktop ssh root@192.168.1.11
root@192.168.1.11's password:
Permission denied, please try again.
root@192.168.1.11's password:
Last failed login: Wed Jan  2 09:35:47 CST 2019 from 192.168.1.12 on ssh:notty
There was 1 failed login attempt since the last successful login.
Last login: Wed Jan  2 09:34:52 2019 from 192.168.1.12
➜  ~ ll .ssh
总用量 4.0K
-rw-r--r--. 1 root root 368 12月 17 11:07 known_hosts
#如果没有显示的话,就使用mkdir .ssh创建,我这里有目录就不用创建

3.上传生成的公钥到远程主机centos7上

使用ssh上传第一步在本地生成的公钥到远程主机centos7上的.ssh目录下的authorized_keys文件中


➜  Desktop cat ~/.ssh/id_rsa.pub | ssh root@192.168.1.11 'cat >> .ssh/authorized_keys'
root@192.168.1.11's password:
➜  Desktop

4.设置远程主机.ssh及authorized_keys权限


➜  Desktop ssh root@192.168.1.11 "chmod 700 .ssh; chmod 640 .ssh/authorized_keys"
root@192.168.1.11's password:

5.mac免密码登录远程主机centos7


➜  Desktop ssh root@192.168.1.11
Last login: Wed Jan  2 09:35:52 2019 from 192.168.1.12
➜  ~

至此,大功告成,如果有多台服务器的话那么只需要同样的方法,上传公钥到远程主机用户目录下.ssh文件夹下的authorized_keys下,设置好文件夹及文件权限后就可以免密码登录了。

点赞

Leave a Reply

Your email address will not be published. Required fields are marked *