關於SSH免密登錄不生效問題


關於SSH免密登錄不生效問題采坑

問題描述

在部署本地博客到服務器時,按照步驟首先創建密鑰,然后把公鑰粘貼到到服務器文件中vim .ssh/authorized_keys,按理來說已經配置成功了。事實上來說也應該這樣,但是!早晚有一天會發現事情不是這么簡單,明明已經配置好了公鑰,卻由於各種原因會導致我運行hexo g -d還是需要密碼登錄。

踩坑歷程

由於我不止一個遠程倉庫,所以我本地保存了多對密鑰,最開始我以為問題出在密鑰混淆。於是我按照這篇博客的方法,配置了config文件,卻發現還是不行。於是我把重心放到日志文件上,想通過日志看出一些端倪。

ssh -vvv 用戶名@服務器ip

-vvv選項可進入ssh調試模式,v越多調試信息越詳細,將日志復制到編輯器中查看,截取如下:

debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug1: Trying private key: /c/Users/hiltay/.ssh/id_ed25519_sk
debug3: no such identity: /c/Users/hiltay/.ssh/id_ed25519_sk: No such file or directory
debug1: Trying private key: /c/Users/hiltay/.ssh/id_xmss
debug3: no such identity: /c/Users/hiltay/.ssh/id_xmss: No such file or directory
debug2: we did not send a packet, disable method
debug3: authmethod_lookup password
debug3: remaining preferred: ,password
debug3: authmethod_is_enabled password
debug1: Next authentication method: password

可以看到這一行debug2: we did not send a packet, disable method,說明數據包沒有發送過去,而下一行debug3: authmethod_lookup password由於公鑰驗證未通過,就直接換成密碼登錄了。我找來了正確登錄的ssh(數據已經脫敏)

debug1: Offering public key: /c/Users/hiltay/.ssh/id_rsa RSA SHA256:AbgluAsmuuOstZ08mBP0F3P4+5xMilAUFF5Sm91k9hE
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 60
debug1: Server accepts key: /c/Users/hiltay/.ssh/id_rsa RSA SHA256:AbgluAsmuuOstZ08mBP0F3P4+5xMilAUFF5Sm91k9hE
debug3: sign_and_send_pubkey: RSA SHA256:AbgluAsmuuOstZ08mBP0F3P4+5xMilAUFF5Sm91k9hE
debug3: sign_and_send_pubkey: signing using rsa-sha2-512 SHA256:AbgluAsmuuOstZ08mBP0F3P4+5xMilAUFF5Sm91k9hE
debug3: send packet: type 50
debug3: receive packet: type 52
Authenticated using "publickey".

可以看到正確登錄的時候會直接提示Authenticated using "publickey".二者的差別就在於服務器到底收沒收到公鑰。

為了驗證這一點,我們登錄服務器,監聽系統安全日志,在這里會記錄SSH登錄相關的日志。

tail -f /var/log/secure

再次本地連接服務器:

ssh -vvv 用戶名@服務器ip

查看服務器日志,會發現有這一條(數據已脫敏):

Authentication refused: bad ownership or modes for directory /home/用戶名

那就豁然開朗了,是文件的權限問題導致了遠程無法連接。

我們查看/home/用戶名路徑的權限,並且查看屬主和屬組是否是用戶

cd /home/
ll -a

然后查看.ssh目錄的權限,正常的話權限應該是700,如果不是,則修改

chmod 700 .ssh

修改屬組

chgrp [group] .ssh
# 這里group換成你用戶的屬組

修改屬主

chown 用戶名 /home/用戶名

再次登錄,免密成功。

排查方法

下面總結出一個常用的排查事項:

檢查 操作示例 說明
.ssh目錄的屬主、屬組是否為要登陸的用戶與用戶組 ll -a /home/[username]/ username為用戶名,下同
.ssh目錄的權限是否為 700 ll -a /home/[username]/
.ssh目錄下authorized_keys的權限是否為644 ll -a /home/[username]/.ssh/
[username]目錄的權限是否為755 ll -a /home/ 700也可以,確保其他人沒有w權限

圖示:

檢查.ssh目錄

image-20211119150246084

檢查authorized_keys

image-20211119150509961

檢查[username]目錄權限

image-20211119150624696

感想

該踩的坑還是要踩,最大的收獲就是看日志太有用了,本地的日志看不出,但是服務器上的系統安全日志把問題描述得清清楚楚。

希望對大家有幫助。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM