Linux上实现SSH免密码登陆远程服务器

0.说明

    平常使用SSH登陆远程服务器时,都需要使用输入密码,希望可以实现通过密钥登陆而免除输入密码,从而可以为以后实现批量自动部署主机做好准备。

    环境如下:

  IP地址 操作系统
服务器端 10.0.0.128/24 6.5 x86
客户端 10.0.0.129/24 16.04 x86

1.客户端生成密钥对

生成密钥对:

linuxidc@linuxidc:~$  ssh -keygen -t rsa -b 2048
Generating public /private  rsa key pair.
Enter  file  in  which  to save the key ( /home/linuxidc/ . ssh /id_rsa ): 
Created directory  '/home/linuxidc/.ssh' .
Enter passphrase (empty  for  no passphrase): 
Enter same passphrase again: 
Your identification has been saved  in  /home/linuxidc/ . ssh /id_rsa .
Your public key has been saved  in  /home/linuxidc/ . ssh /id_rsa .pub.
The key fingerprint is:
SHA256:eLssyXJLzUCfSN5mu6nqNH9dB /gOyXSvWBwQdNssIYE  linuxidc@linuxidc
The key's randomart image is:
+---[RSA 2048]----+
|         o=oo    |
|        E .o =   |
|      o    oo o  |
|     + = .o +.   |
|      = So = +   |
|       B o+ = o  |
|    o...=. * o   |
|   ..+=..+o o    |
|   .o++==        |
+----[SHA256]-----+

查看生成的密钥对:

2.上传公钥到服务器端

    使用scp命令操作:

linuxidc@linuxidc:~$  scp  . ssh /id_rsa .pub [email protected]: /root
The authenticity of host  '10.0.0.128 (10.0.0.128)'  can't be established.
RSA key fingerprint is SHA256:0Tpm11wruaQXyvOfEB1maIkEwxmjT2AklWb198Vrln0.
Are you sure you want to  continue  connecting ( yes /no )?  yes
Warning: Permanently added  '10.0.0.128'  (RSA) to the list of known hosts.
[email protected]'s password: 
id_rsa.pub                                                    100%  393     0.4KB /s    00:00

3.服务器端操作 

    把从客户端传来的公钥添加到.ssh/authorized_keys中:

[root@linuxidc ~] # cat id_rsa.pub >> .ssh/authorized_keys
[root@linuxidc ~] # chmod 600 .ssh/authorized_keys
  
# authorized_keys的权限需要为600

    修改ssh配置文件/etc/ssh/sshd_config,找到下面一行:

PubkeyAuthentication no

    修改为:

PubkeyAuthentication  yes

4.测试 

    在客户端上使用密钥登陆到服务器上:

linuxidc@linuxidc:~$  ssh  -i . ssh /id_rsa  [email protected]
Last login: Tue May  9 15:14:01 2017 from 10.0.0.129
[root@linuxidc ~] #

5.注意事项 

  • 在服务器端需要把selinux关闭,否则最后无法使用密钥进行远程登陆;

  • 客户端使用scp命令时,在服务器端也需要安装ssh客户端,否则无法把公钥上传到服务器端,另外也可以使用ssh-copy-id [email protected]来代替scp操作(这样在服务器端也不需要执行创建.ssh目录等这些操作,即相当于该命令可以一步帮我们完成密钥的上传与配置工作);

下面关于SSH相关的文章您也可能喜欢,不妨参考下:

猜你喜欢

转载自www.linuxidc.com/Linux/2017-05/144165.htm