基礎篇
執行: ssh-keygen -t rsa
rocky@tiger:~$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/rocky/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/rocky/.ssh/id_rsa.
Your public key has been saved in /home/rocky/.ssh/id_rsa.pub.
The key fingerprint is:
02:fc:ca:a5:8b:28:d1:bf:0a:d5:40:7a:80:8d:43:b1 rocky@tiger
The key's randomart image is:
+--[ RSA 2048]----+
|+=o |
|++o. |
|.Eo o |
| . o o |
| .. . + S |
|.... + . |
|.. .+ |
|.o ... |
|o o.o. |
+-----------------+
注:提示輸入passphrase的時候,直接輸入回車,這樣登入時就無需再輸入密碼
執行後會在/home/rocky/.ssh/目錄下生成兩個檔案: id_rsa(私鑰) id_rsa.pub(公鑰)
上傳id_rsa.pub檔案到remote server的 ~/.ssh/目錄下 (沒有該目錄時,自行建立即可)
scp /home/rocky/.ssh/id_rsa.pub root@ipaddr:/root/.ssh/authorized_keys (此時要輸入密碼)
注:1.上面的指令不但會把id_rsa.pub檔案上傳到remote server的/root/.ssh目錄下,還會把檔案名替換為authorized_keys 即authorized_keys檔案就是id_rsa.pub檔案
2.如果之前remote server上已經存在了authorized_keys檔案,上面的指令會清除檔案内容在寫入.是以這個時候最好先儲存為其他某個檔案,再把檔案内容追加到authorized_keys檔案中. cat xxx.pub >> authorized_keys
重新登入測試
ssh root@ipaddress
如果仍然需要密碼,需登入到remote server檢查.ssh目錄的權限是否為700,以及authorized_keys檔案的權限是否為644
再次測試,成功
異常處理:
1.Agent admitted failure to sign using the key.
在本機執行ssh-add指令即可
rocky@tiger:.ssh$ ssh-add
Identity added: /home/rocky/.ssh/id_rsa (/home/rocky/.ssh/id_rsa)
進階篇
基礎篇中采用scp把公鑰檔案拷貝到remote server的authorized_keys檔案中,其中要注意各種檔案,比如權限,内容追加這些地方.
下面有個簡便方法搞定上訴步驟:
ssh-copy-id -i .ssh/id_rsa.pub user@IP
該指令會自動把id_rsa.pub指令追加到user使用者下的.ssh/authorized_keys檔案中.