Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux (CentOS) SSH 服務安裝、強化配置與 macOS 遠端連線實戰指南

編輯:Linux 教學

SSH 是 Linux 遠端管理的標準協定。本文以 CentOS 為服務端、macOS 為客戶端,涵蓋:OpenSSH Server 安裝、服務啟用、防火牆放行、sshd_config 強化 (禁用 root、限制用戶、修改埠、金鑰認證)、關閉 GUI 節省資源、macOS 終端機連線驗證、SSH 金鑰對生成與免密登入、SSH Agent 轉發、常見連線問題排解,打造安全高效的遠端運維環境。

一、服務端 (CentOS) 安裝與基礎配置

# 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

二、sshd_config 安全強化 (必做項)

vi /etc/ssh/sshd_config
參數建議值說明
Port2222修改預設埠減少掃描噪音 (需同步防火牆)
PermitRootLoginno禁止 root 直接登入
PubkeyAuthenticationyes啟用金鑰認證
PasswordAuthenticationno禁用密碼認證 (需先部署金鑰)
PermitEmptyPasswordsno禁止空密碼
MaxAuthTries3限制嘗試次數
ClientAliveInterval3005 分鐘無操作發送保活
ClientAliveCountMax2保活失敗 2 次斷線
AllowUsersadmin deploy僅允許指定用戶登入 (空格分隔)
DenyUsersroot daemon明確拒絕用戶
LoginGraceTime30登入逾時秒數
Banner/etc/ssh/banner登入前顯示法律警告
Protocol2僅支援 SSH-2

修改後重啟:systemctl restart sshd

三、關閉 GUI 進入命令列模式 (節省資源)

vi /etc/inittab
# 將 id:5:initdefault: 改為 id:3:initdefault:
# 或 systemd 方式:
systemctl set-default multi-user.target
# 重啟生效
reboot

四、macOS 客戶端連線與金鑰免密登入

1. 生成金鑰對 (macOS 終端機)


ssh-keygen -t ed25519 -C "admin@macbook"
# 一路 Enter,產生 ~/.ssh/id_ed25519 (私鑰) 與 ~/.ssh/id_ed25519.pub (公鑰)

2. 部署公鑰至 CentOS


# 方法 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"

3. 驗證免密登入


ssh -p 2222 admin@centos-host
# 應直接進入 Shell,無需輸入密碼

4. SSH Config 簡化連線指令 (~/.ssh/config)


Host myserver
    HostName 192.168.1.100
    Port 2222
    User admin
    IdentityFile ~/.ssh/id_ed25519
    ServerAliveInterval 60
    ServerAliveCountMax 3

之後只需 ssh myserver 即可連線。

五、進階技巧

SSH Agent 轉發 (跳板機場景)


# macOS 啟動 agent 並加入金鑰
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519

# 連線時帶上 -A 參數
ssh -A admin@jump-host
# 在 jump-host 上再 ssh 目標主機,將使用本地金鑰認證

禁用密碼認證前的檢查清單

  • 至少一組金鑰已部署並驗證可登入
  • root 已被禁止,但有 sudo 權限的普通用戶可用
  • 防火牆已放行新埠 (如 2222)
  • SELinux 若為 Enforcing,確認 semanage port -a -t ssh_port_t -p tcp 2222

六、常見連線問題排解

現象可能原因解決
Permission denied (publickey)公鑰未正確部署、authorized_keys 權限非 600、.ssh 目錄權限非 700chmod 700 ~/.ssh; chmod 600 ~/.ssh/authorized_keys; 檢查擁有者
Connection refusedsshd 未啟動、埠號錯誤、防火牆攔截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
Copyright © Windows教程網 All Rights Reserved