伺服器之間,相同帳號,實現免金鑰登入

vboy1010發表於2016-10-27

使用場景

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

相關文章