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

SSH 學習筆記之一:OpenSSH 基礎安裝、金鑰機制與遠端登入實戰

編輯:系統常見問題解答

OpenSSH 是 Linux 系統標準的遠端登入與檔案傳輸套件,取代不安全的 Telnet、FTP、R 系列工具。核心元件:

  • ssh:替代 telnet/rlogin/rsh,加密遠端 Shell。
  • scp / sftp:替代 ftp,加密檔案傳輸。

金鑰交換與驗證流程

  1. 雙方建立連線前交換公鑰。
  2. 客戶端首次連線時,sshd 送出主機公鑰,客戶端提示確認是否信任(防中間人攻擊)。
  3. 客戶端驗證主機公鑰指紋,接受後存入 ~/.ssh/known_hosts(含 IP/主機名與公鑰)。
  4. 後續連線自動比對 known_hosts,不符則報警(可能主機重裝、升級、或遭劫持)。
  5. 用戶認證階段:密碼、公開金鑰、GSSAPI、鍵盤互動等方式。

伺服器端金鑰對存放於 /etc/ssh/(ssh_host_*_key 私鑰、ssh_host_*_key.pub 公鑰)。

1. 安裝 OpenSSH Server(Ubuntu/Debian)

sudo apt-get update
sudo apt-get install openssh-server
驗證服務啟動:pidof sshd 或 systemctl status ssh。

2. SSH 遠端登入基本語法

ssh [選項] [-l 登入用戶] [用戶@]主機 [命令]
  • -l user 或 user@host 指定登入身分(預設為當前用戶)。
  • 預設連接埠 22,可用 -p 指定其他埠。
  • 範例:ssh -l webgod 192.168.1.100 或 ssh webgod@192.168.1.100。

3. 金鑰認證設定(免密登入)

  1. 客戶端生成金鑰對:ssh-keygen -t rsa -b 2048(一路 Enter)。
  2. 複製公鑰至伺服器:ssh-copy-id user@host 或手動將 ~/.ssh/id_rsa.pub 內容加入伺服器 ~/.ssh/authorized_keys。
  3. 確認伺服器 /etc/ssh/sshd_config:
    PubkeyAuthentication yes
    AuthorizedKeysFile .ssh/authorized_keys
  4. 重啟 sshd,再次連線即免密登入。

4. 常見問題排查

  • WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!:主機金鑰變更,編輯 ~/.ssh/known_hosts 刪除對應行,或用 ssh-keygen -R hostname 移除舊紀錄。
  • Permission denied (publickey).:檢查 authorized_keys 權限(600)、目錄權限(700)、SELinux 上下文(restorecon -R ~/.ssh)。
  • Connection refused:確認 sshd 運行、防火牆開放 22 埠、ListenAddress 設定正確。

掌握 OpenSSH 基礎,是 Linux 運維與開發的入門必修課。

Copyright © Windows教程網 All Rights Reserved