Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Linux SSH 遠端登入與免密碼認證完整設定指南

編輯:Linux 系統常見問題解答

一、SSH 遠端登入基本用法

SSH (Secure Shell) 為加密網路協定,預設埠號 22。常見連線指令:

# 使用當前使用者登入
ssh host

# 指定使用者
ssh user@host
ssh -p 2222 user@host   # 指定非預設埠

首次連線信任流程

The authenticity of host 'host (192.168.0.21)' can't be established.
RSA key fingerprint is 98:2e:d7:e0:de:9f:ac:67:28:c2:42:2d:37:16:58:4d.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'host,192.168.0.21' (RSA) to the list of known hosts.
user@host's password: ********

輸入 yes 後,主機公鑰會寫入 ~/.ssh/known_hosts,後續連線不再提示。

二、免密碼登入(公開金鑰認證)設定步驟

1. 本地端產生金鑰對

ssh-keygen -t rsa
# 一路 Enter(或自訂路徑/密語)
# 產生:~/.ssh/id_rsa(私鑰)、~/.ssh/id_rsa.pub(公鑰)

2. 將公鑰複製到遠端主機

ssh-copy-id user@host
# 若遠端 SSH 埠非 22:
ssh-copy-id -p 2222 "user@host"

此命令會將公鑰追加至遠端 ~/.ssh/authorized_keys。

3. 驗證免密碼登入

ssh user@host  # 應直接進入,無需輸入密碼

三、常見問題排除

1. 設定完成仍需輸入密碼

檢查遠端 /etc/ssh/sshd_config 確保下列選項開啟:

RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys

修改後重啟 SSH 服務:

# Ubuntu/Debian
sudo systemctl restart ssh
# 或
sudo service ssh restart

# CentOS/RHEL
sudo systemctl restart sshd

2. 權限問題

確保遠端使用者家目錄與 .ssh 權限正確:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

3. 指定非預設金鑰檔案

ssh-copy-id -i ~/.ssh/id_rsa.pub user@host
# 或手動複製:
cat ~/.ssh/id_rsa.pub | ssh user@host "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

四、SSH 服務端安全性加固(/etc/ssh/sshd_config)

設定項建議值說明
Port22 (或修改為非標準埠)監聽埠
Protocol2僅啟用 SSH v2
PermitRootLoginno禁止 root 直接登入
PermitEmptyPasswordsno禁止空密碼
LoginGraceTime2m登入逾時
MaxAuthTries6最大嘗試次數
PasswordAuthenticationno (改用金鑰)停用密碼認證
PubkeyAuthenticationyes啟用金鑰認證
UseDNSno關閉 DNS 反解,加速連線
AllowUsersuser1 user2僅允許特定使用者

修改完成後執行 sudo systemctl restart sshd 生效。

五、實用指令速查

# 查看 SSH 服務狀態
systemctl status sshd

# 查看 SSH 版本
ssh -V

# 測試連線(除錯模式)
ssh -vvv user@host

# 產生 ED25519 金鑰(更安全、更短)
ssh-keygen -t ed25519 -C "comment"

結語

掌握 SSH 金鑰認證與服務端加固,是 Linux 伺服器管理的基本功。建議生產環境**完全停用密碼登入**,改用金鑰加上 fail2ban 或 sshguard 防暴力破解。

Copyright © Windows教程網 All Rights Reserved