设置ssh经过密钥免密码登陆Linux服务器

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

(本文永久地址:http://woymk.blog.51cto.com/10000269/1919130安全

1. 产生密钥服务器

执行ssh-keygen -t rsadom

[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 p_w_picpath is:
+--[ RSA 2048]----+
|          . .    |
|         + . .   |
|        = +   E  |
|       * O o     |
|      o S X .    |
|       o B + .   |
|        o o .    |
|         .       |
|                 |
+-----------------+
ssh

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

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

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

[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:blog

  .ssh/authorized_keysip

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

wKioL1j-tPnysIovAAC_rn-AHjs798.png-wh_50

点[Load]打开私钥文件id_rsa

点[Save private key]保存

运行putty,输入远程主机ip

wKiom1j-tgfQLkLDAACsIXpbvaQ025.png-wh_50

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

wKioL1j-tvjhScJ7AAC7IlQWTQQ202.png-wh_50

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

wKiom1j-t5aRwlCGAACrUjsN5fg245.png-wh_50

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

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

wKiom1j-uCzQQdagAAClbhewyGg271.png-wh_50

最后点[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