服務器之間,相同賬號,實現免密鑰登陸

使用場景服務器

一、Client端機器:10.108.0.1ssh

二、Server端機器:10.108.0.二、10.108.0.三、10.108.0.一、10.108.0.四、10.108.0.5ide

目的:在Client端機器上,SSHServer端機器上,實現相同賬號,免密鑰登陸。測試

解決辦法:this

一、Client端生成公鑰和私鑰rest

執行 ssh-keygen -t rsacode

[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 子目錄裏,生成了兩個文件server

  • 私鑰:id_rsait

  • 公鑰:id_rsa.pubio

二、將生成的公鑰給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

三、測試免密鑰登陸

ssh 10.108.0.2

[xxx@10.108.0.2 ~]$

顯示登陸成功。

四、沒法登陸的緣由

  • 客戶端的私鑰和公鑰文件位置必須位於 ~/.ssh

  • 確保雙方 ~/.ssh 目錄,父目錄,公鑰私鑰,authorized_keys 文件,對當前用戶至少要有執行權限,對其餘用戶最多隻能有執行權限

  • authorized_keys 文件名確保正確

五、文件目錄權限

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

六、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
相關文章
相關標籤/搜索