设置ssh通过密钥免密码登录Linux服务器
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设置ssh通过密钥免密码登录Linux服务器相关的知识,希望对你有一定的参考价值。
每次登录linux时需要输入一大串密码(有时还会等很长时间才能输入密码,文章最后有解决方法),密码设的太短,安全性不高,长了很难记忆并且输入麻烦。
使用密钥登录,不仅可以省去了密码输入的步骤,而且提高了服务器的安全性。
1. 产生密钥
执行ssh-keygen -t rsa
[[email protected] ~]# 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 [email protected]
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 [email protected]远程主机名或ip
[[email protected] ~]# ssh-copy-id -i .ssh/id_rsa.pub [email protected]
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.
[email protected]‘s password:
Now try logging into the machine, with "ssh ‘[email protected]‘", 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 [email protected]:~/.ssh/id_rsa.pub authorized_keys
chmod 600 authorized_keys
3. 登录远程主机
1) 直接登录远程主机
执行ssh 192.168.1.2
[[email protected] ~]# ssh 192.168.1.2
Last login: Sun Apr 23 17:03:39 2017 from 192.168.1.1
[[email protected] ~]#
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服务器的主要内容,如果未能解决你的问题,请参考以下文章