SSH 是 Linux 遠端管理的標準協定。本文以 CentOS 為服務端、macOS 為客戶端,涵蓋:OpenSSH Server 安裝、服務啟用、防火牆放行、sshd_config 強化 (禁用 root、限制用戶、修改埠、金鑰認證)、關閉 GUI 節省資源、macOS 終端機連線驗證、SSH 金鑰對生成與免密登入、SSH Agent 轉發、常見連線問題排解,打造安全高效的遠端運維環境。
# 1. 安裝
yum install -y openssh-server openssh-clients
# 2. 設定開機自啟並啟動
systemctl enable --now sshd
# 3. 防火牆放行 SSH 埠 (預設 22)
firewall-cmd --permanent --add-service=ssh
firewall-cmd --reload
# 或 iptables:
# iptables -I INPUT -p tcp --dport 22 -j ACCEPT
# service iptables save
vi /etc/ssh/sshd_config
| 參數 | 建議值 | 說明 |
|---|---|---|
Port | 2222 | 修改預設埠減少掃描噪音 (需同步防火牆) |
PermitRootLogin | no | 禁止 root 直接登入 |
PubkeyAuthentication | yes | 啟用金鑰認證 |
PasswordAuthentication | no | 禁用密碼認證 (需先部署金鑰) |
PermitEmptyPasswords | no | 禁止空密碼 |
MaxAuthTries | 3 | 限制嘗試次數 |
ClientAliveInterval | 300 | 5 分鐘無操作發送保活 |
ClientAliveCountMax | 2 | 保活失敗 2 次斷線 |
AllowUsers | admin deploy | 僅允許指定用戶登入 (空格分隔) |
DenyUsers | root daemon | 明確拒絕用戶 |
LoginGraceTime | 30 | 登入逾時秒數 |
Banner | /etc/ssh/banner | 登入前顯示法律警告 |
Protocol | 2 | 僅支援 SSH-2 |
修改後重啟:systemctl restart sshd
vi /etc/inittab
# 將 id:5:initdefault: 改為 id:3:initdefault:
# 或 systemd 方式:
systemctl set-default multi-user.target
# 重啟生效
reboot
ssh-keygen -t ed25519 -C "admin@macbook"
# 一路 Enter,產生 ~/.ssh/id_ed25519 (私鑰) 與 ~/.ssh/id_ed25519.pub (公鑰)
# 方法 A:ssh-copy-id (需暫時開啟 PasswordAuthentication)
ssh-copy-id -p 2222 admin@centos-host
# 方法 B:手動
cat ~/.ssh/id_ed25519.pub | ssh -p 2222 admin@centos-host "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
ssh -p 2222 admin@centos-host
# 應直接進入 Shell,無需輸入密碼
Host myserver
HostName 192.168.1.100
Port 2222
User admin
IdentityFile ~/.ssh/id_ed25519
ServerAliveInterval 60
ServerAliveCountMax 3
之後只需 ssh myserver 即可連線。
# macOS 啟動 agent 並加入金鑰
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
# 連線時帶上 -A 參數
ssh -A admin@jump-host
# 在 jump-host 上再 ssh 目標主機,將使用本地金鑰認證
semanage port -a -t ssh_port_t -p tcp 2222| 現象 | 可能原因 | 解決 |
|---|---|---|
| Permission denied (publickey) | 公鑰未正確部署、authorized_keys 權限非 600、.ssh 目錄權限非 700 | chmod 700 ~/.ssh; chmod 600 ~/.ssh/authorized_keys; 檢查擁有者 |
| Connection refused | sshd 未啟動、埠號錯誤、防火牆攔截 | systemctl status sshd; firewall-cmd --list-all |
| Host key verification failed | 遠端主機金鑰變更 (重裝系統) | ssh-keygen -R hostname 移除 known_hosts 舊紀錄 |
| macOS 終端機顯示亂碼 | locale 不匹配 | export LANG=zh_TW.UTF-8; export LC_ALL=zh_TW.UTF-8 |