ssh除了密码验证外,还有一种比较常用的验证方式:key;他的好处除了安全外,还可以实现linux之间的免密码登陆 ,方便管理或者批量维护。
本文介绍一下windows/linux下如何配置key免密码登陆linux服务器
01 |
[root@A ~] # ssh-keygen -t rsa |
02 |
03 |
Generating public/private rsa key pair. |
04 |
05 |
Enter file in which to save the key (/root/. ssh /id_rsa): |
06 |
//key保存的路径和文件名 |
07 |
08 |
Enter passphrase (empty for no passphrase): |
09 |
10 |
//key的密码,免密码登陆的话留空 |
11 |
12 |
Enter same passphrase again: |
13 |
14 |
Your identification has been saved in /root/. ssh /id_rsa |
15 |
16 |
//生成了私钥/root. ssh /id_rsa |
17 |
18 |
Your public key has been saved in /root/. ssh /id_rsa.pub |
19 |
20 |
//生成了公钥 /root/. ssh /id_rsa.pub |
21 |
22 |
The key fingerprint is: |
23 |
24 |
82:8c:2c:52:06:c6:f3:c4:1c:1c:35:b7: cd :5b:42:a2 root@A |
25 |
26 |
[root@A ~] # ls /root/.ssh/ //查看一下目录,已经有了这两个文件 |
27 |
28 |
authorized_keys id_rsa id_rsa.pub known_hosts |
29 |
30 |
[root@A ~] # |
查看一下服务器ssh服务公钥存放的路径
1 |
[root@A ~] # cat /etc/ssh/sshd_config |grep AuthorizedKeysFile |
2 |
3 |
#AuthorizedKeysFile .ssh/authorized_keys |
默认服务器保存公钥的位置是.ssh/AuthorizedKeysFile
所以需要将生成的公钥文件通过scp或者任何方法拷贝到你需要远程登录的服务器的这个文件中
01 |
[root@B ~] # cd .ssh/ |
02 |
03 |
[root@B . ssh ] # cat id_rsa.pub >authorized_keys |
04 |
05 |
//服务器本地 ssh 客户端默认读取的私钥路径已经包含了/. ssh /id_rsa |
06 |
07 |
[root@A . ssh ] # cat /etc/ssh/ssh_config |grep IdentityFile |
08 |
09 |
# IdentityFile ~/.ssh/identity |
10 |
11 |
# IdentityFile ~/.ssh/id_rsa |
12 |
13 |
# IdentityFile ~/.ssh/id_dsa |
至此你可以直接从A 执行命令ssh ipB
登录到服务器B了,就这么简单。
有一种简单的方法:使用命令ssh-copy-id 直接将本机的key加入到对方服务器的验证文件中
01 |
[root@A . ssh ] # ssh-copy-id |
02 |
03 |
Usage: /usr/bin/ ssh -copy- id [-i [identity_file]] [user@]machine |
04 |
05 |
[root@A . ssh ] # ssh-copy-id -i /root/.ssh/id_rsa root@ipB |
06 |
07 |
The authenticity of host 'ipB (ipB)' can't be established. |
08 |
09 |
RSA key fingerprint is 17:21:32:02:da:3b:a1:d1:a2:69:12:36:a2:d7:59:ad. |
10 |
11 |
Are you sure you want to continue connecting ( yes /no)? yes |
12 |
13 |
root@ipB's password: |
14 |
15 |
Now try logging into the machine, with "ssh 'root@ipB'" , and check in : |
16 |
17 |
. ssh /authorized_keys |
18 |
19 |
[root@A ~] # ssh ipB |
20 |
21 |
Last login: Sun Dec 15 19:33:07 2013 from ipA |
22 |
23 |
[root@B ~] # |
这样执行之后,就可以直接登陆服务器了。
上面都是通过linux的ssh客户端来连接,如果通过本地来使用key登陆的话方法大同小异;
将私钥id_rsa下载到本地,然后导入到客户端的密钥认证配置的地方即可;
以SecureCRT为例,配置位置如下图选择下载下来的私钥文件即可。