使用场景

1、Client端机器:10.108.0.1

2、Server端机器:10.108.0.2、10.108.0.3、10.108.0.1、10.108.0.4、10.108.0.5

目的:在Client端机器上,SSHServer端机器上,实现相同帐号,免密钥登录。

解决办法:

1、Client端生成公钥和私钥

执行 ssh-keygen -t rsa

[xxx@sdktest01v ~/.ssh]$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/xxx/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/xxx/.ssh/id_rsa.
Your public key has been saved in /home/xxx/.ssh/id_rsa.pub.
The key fingerprint is:
b0:b0:77:9a:01:b6:c0:bc:08:05:a2:a1:f4:6d:f9:77 xxx@server-host-1

此时在当前用户的Home目录下 .ssh 子目录里,生成了两个文件

  • 私钥:id_rsa

  • 公钥:id_rsa.pub

2、将生成的公钥给Server端机器

[xxx@sdktest01v ~/.ssh]$ ssh-copy-id  -i /home/xxx/.ssh/id_rsa.pub xxx@10.108.0.2
27
xxx@10.108.0.2's password: 
Now try logging into the machine, with "ssh 'xxx@10.108.0.2'", and check in:

  .ssh/authorized_keys

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

ssh-copy-id:将公钥发到目标服务器上,并生成文件 /home/xxx/.ssh/authorized_keys

3、测试免密钥登录

ssh 10.108.0.2

[xxx@10.108.0.2 ~]$

显示登录成功。

4、无法登录的原因

  • 客户端的私钥和公钥文件位置必须位于 ~/.ssh

  • 确保双方 ~/.ssh 目录,父目录,公钥私钥,authorized_keys 文件,对当前用户至少要有执行权限,对其他用户最多只能有执行权限

  • authorized_keys 文件名确保正确

5、文件目录权限

Client端:

[xxx@10.108.0.1 ~/.ssh]$ ll
总用量 12
-rwx------ 1 xxx xxx 1675 10月 27 17:04 id_rsa
-rwx------ 1 xxx xxx  413 10月 27 17:04 id_rsa.pub
-rwx------ 1 xxx xxx  396 9月  23 10:53 known_hosts

Server端:

[xxx@10.108.0.2 ~/.ssh]$ ll
total 16
-rw------- 1 xxx xxx  413 Oct 27 18:54 authorized_keys
-rw------- 1 xxx xxx 1675 Oct 27 18:54 id_rsa
-rw-r--r-- 1 xxx xxx  413 Oct 27 18:54 id_rsa.pub
-rwx------ 1 xxx xxx  792 Oct 27 18:54 known_hosts

6、BUG

可以和Server机器通信,但是还需要密码登录(CentOS 6系统中复现,涉及ssh-copy-idSELinux

摘录一段E文的原因和解决办法:

When ssh-copy-id creates the authorized keys files it creates it with the proper permissions, but with the wrong SELinux label. 
The fix for this is restoring the labels to their policy defaults using this command:

restorecon -R ~/.ssh

vboy1010
912 声望35 粉丝

清泉石上流


引用和评论

0 条评论