当需要登录管理的服务器比较多时,在手头上Linux PC里使用ssh远程就是比较麻烦,因为要每个服务器手工输入不同的密码。Linux下没找到什么好用的可以记住密码的SSH工具,shell里只能使用ssh命令再手工输入密码。还好ssh支持RSAAuthentication,我们可以使用RSA Key来代替密码,只要使用RSA Key的密码就可以了,而且我们可以为生成的RSA Key使用相同的密码,甚至不使用密码(不推荐,除非你是在部署Hadoop集群)。
要使用RSA Key进行SSH登录,首先需要确定远程Linux/Unix服务器启用了RSAAuthentication:
确定服务器上/etc/ssh/sshd_config中存在以下未被注释的两行
RSAAuthentication yes
PubkeyAuthentication yes
之后确定你本地已经安装了openssh工具
1.生成RSA Key
使用ssh-keygen命令生成一对公钥和密钥
$ ssh-keygen -t rsa -b 2048 -f server_rsa -C "xxx@company"
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in server_rsa.
Your public key has been saved in server_rsa.pub.
The key fingerprint is:
3d:20:bb:d3:18:51:77:2b:c3:1b:9a:f8:7a:b1:8b:29 xxx@company
The key's randomart image is:
+--[ RSA 2048]----+
| . . . |
| . o . . |
| o . = . |
| = = = |
| + S + |
| *. . |
| + oo |
| E =o |
| .+... |
+-----------------+
-t rsa 表示使用RSA加密得法,你也可以使用dsa代替。-b 2048表示使用2048位加密,如果你对安全性要求更高,可以使用4098位加密。-f server_rsa表示要生成的文件名为server_rsa(密钥)和server_rsa.pub(公钥)。最后的-C "xxx@company"是注释,会追加在造成的Key文件尾部,通常会写上用户或机器的身份信息备查。之后输入RSA Key的使用密码并确认,ssh-keygen命令就会造成一对密钥对。把生成的密钥对拷贝到~/.ssh/下
2.注册公钥信息
接下来需要把公钥信息注册到服务器上,使用ssh-copy-id命令
ssh-copy-id -i ~/.ssh/server_rsa.pub user@server
把server_rsa.pub替换为你要使用的公钥名,注意使用的文件一定是以.pub后缀的文件!之后user@server替换为你实际的远程登录用户地址。
$ ssh-copy-id -i ~/.ssh/server_rsa.pub user@server
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'user@server'"
and check to make sure that only the key(s) you wanted were added.
执行此命令时,会和普通ssh登录一样要求输入密码。再之后进行ssh命令登录就不需要输入服务器密码,只需要输入RSA Key密码就可以了。
为了安全,最好每个服务器使用不同的RSA Key,这样可以使密钥泄漏导致的安全风险降到最低。为了防止他人使用此机器远程登录,RSA Key最好设置密码。
本文操作环境:本地ubuntu14.04/ 远程ubuntu14.04
补充内容:文件权限
如果你注册过RSA Key后仍需要输入服务器用户密码,应该是服务器端用户文件权限问题:需要
a.服务器用户$HOME目录权限不能有用户组写权限
b.服务器用户$HOME/.ssh目录权限必须是700
c.服务器用户$HOME/.ssh/authorized_keys文件权限必须是600