码迷,mamicode.com
首页 > 系统相关 > 详细

设置ssh通过密钥免密码登录Linux服务器

时间:2017-04-25 15:05:56      阅读:319      评论:0      收藏:0      [点我收藏+]

标签:密钥登陆 免密码登陆

每次登录linux时需要输入一大串密码(有时还会等很长时间才能输入密码,文章最后有解决方法),密码设的太短,安全性不高,长了很难记忆并且输入麻烦。
使用密钥登录,不仅可以省去了密码输入的步骤,而且提高了服务器的安全性。


1. 产生密钥

执行ssh-keygen -t rsa

[root@xxx ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): <==设置密钥名字,用默认名直接回车
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:
27:d9:f9:a1:c2:d0:c7:39:86:0f:58:53:ae:64:c7:f5 root@xxx
The key‘s randomart image is:
+--[ RSA 2048]----+
|          . .    |
|         + . .   |
|        = +   E  |
|       * O o     |
|      o S X .    |
|       o B + .   |
|        o o .    |
|         .       |
|                 |
+-----------------+

2. 把密钥复制到远程主机

1) 使用ssh-copy-id命令复制

执行ssh-copy-id -i .ssh/id_rsa.pub root@远程主机名或ip

[root@xxx ~]# ssh-copy-id -i .ssh/id_rsa.pub root@192.168.1.2
The authenticity of host ‘192.168.1.2 (192.168.1.2)‘ can‘t be established.
RSA key fingerprint is 68:94:ee:45:f8:58:6f:1c:e9:c6:4c:5b:11:bc:50:e6.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added ‘192.168.1.2‘ (RSA) to the list of known hosts.
root@192.168.1.2‘s password:
Now try logging into the machine, with "ssh ‘root@192.168.1.2‘", and check in:

  .ssh/authorized_keys

to make sure we haven‘t added extra keys that you weren‘t expecting.

ssh-copy-id会对远程主机用户家目录中的.ssh, 和.ssh/authorized_keys自动设置合适的权限。

2) 使用scp命令复制

也可以用scp命令把文件id_rsa.pub复制到远程主机,需要设置相应文件和目录权限

在远程主机上执行
cd ~
mkdir .ssh
chmod 700 .ssh
cd .ssh
scp root@192.168.1.1:~/.ssh/id_rsa.pub authorized_keys
chmod 600 authorized_keys

3. 登录远程主机

1) 直接登录远程主机

执行ssh 192.168.1.2
[root@xxx ~]# ssh 192.168.1.2
Last login: Sun Apr 23 17:03:39 2017 from 192.168.1.1
[root@xxx2 ~]#

2) 使用putty登陆远程主机

运行puttygen

技术分享

点[Load]打开私钥文件id_rsa

点[Save private key]保存

运行putty,输入远程主机ip

技术分享

点左边树形菜单中的[SSH->Auth],输入刚刚保存的私钥文件        

技术分享

点树形菜单中的[Connection->Data],输入登陆远程主机的用户名root

技术分享

点树形菜单中的[Session],在Host Name(or IP address)下面的空白处填上远程主机的ip和端口号,

在Saved Sessions里给远程主机起个名字,点[Save]保存一下,方便下次使用。

技术分享

最后点[Open]就可以登陆了。

4. 关闭密码验证登录

关闭密码验证后,将无法使用密码登陆,大大提高了服务器的安全性

在远程服务器上操作:
vi /etc/ssh/sshd_config

找到PasswordAuthentication将其值改为no
PasswordAuthentication no

保存后重启ssh服务
service sshd restart




ssh登陆很慢的解决办法:

只要在sshd_config中修改两个参数即可

vi /etc/ssh/sshd_config

1. 禁用DNS反向解析
找到
UseDNS
改成
UseDNS no

2. 禁用于GSSAPI的用户认证
服务器端启用了GSSAPI。登陆的时候客户端需要对服务器端的IP地址进行反解析,如果服务器的IP地址没有配置PTR记录,那么就容易在这里卡住了。

找到GSSAPIAuthentication
改成
GSSAPIAuthentication no

保存后重启ssh服务
service sshd restart


设置ssh通过密钥免密码登录Linux服务器

标签:密钥登陆 免密码登陆

原文地址:http://woymk.blog.51cto.com/10000269/1919130

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!