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

CentOS 7 修改 SSH 端口完整步驟:sshd_config、SELinux、firewalld 三步走

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

修改 SSH 默認端口 22 能有效減少自動化掃描腳本的暴力嘗試噪音。CentOS 7 引入 SELinux 與 firewalld,修改端口需同步更新三處配置,否則服務啟動失敗或無法連接。本文給出標準化操作流程。

操作步驟

1. 修改 sshd 配置文件

vim /etc/ssh/sshd_config
# 找到 #Port 22,取消註釋並添加新端口(建議保留 22 直到驗證新端口通)
Port 22
Port 20000
# 或直接修改為 Port 20000(風險較高,建議雙端口過渡)

重啟前先驗證語法: sshd -t(無輸出即通過)。

2. SELinux 開放新端口

# 查看當前允許的 SSH 端口
semanage port -l | grep ssh
# 輸出:ssh_port_t  tcp  22

# 添加 20000 到 ssh_port_t 類型
semanage port -a -t ssh_port_t -p tcp 20000

# 驗證
semanage port -l | grep ssh
# 應顯示:ssh_port_t  tcp  20000, 22

若提示 semanage: command not found: yum install -y policycoreutils-python (CentOS 7) 或 dnf install -y policycoreutils-python-utils (CentOS 8+)。

3. firewalld 放行新端口

# 永久開放
firewall-cmd --permanent --add-port=20000/tcp
# 立即生效
firewall-cmd --reload

# 驗證
firewall-cmd --list-ports
# 應包含 20000/tcp

4. 重啟 SSH 服務並驗證

systemctl restart sshd.service
systemctl status sshd.service

# 新終端測試新端口連接(勿斷開當前會話!)
ssh -p 20000 user@server_ip

# 驗證成功後,可選關閉端口 22
# vim /etc/ssh/sshd_config  刪除 Port 22
# semanage port -d -t ssh_port_t -p tcp 22
# firewall-cmd --permanent --remove-port=22/tcp
# systemctl restart sshd

常見坑點

  • 只改 sshd_config 不改 SELinux:服務啟動失敗,日志 SELinux is preventing /usr/sbin/sshd from name_bind access on the port 20000。
  • 只改 SELinux 不改 firewalld:服務啟動正常,但外部無法連接(連接超時)。
  • 端口衝突:ss -tulnp | grep 20000 確認未被佔用。
  • 配置語法錯誤:修改後必須 sshd -t 驗證,否則重啟導致服務掛起,只能通過 VNC/控制台修復。
  • 雙棧 IPv6:同樣需放行 20000/tcp 的 IPv6,firewalld 默認雙棧生效。

一鍵腳本(生產環境請審閱後使用)

#!/bin/bash
NEW_PORT=20000
set -euo pipefail

# 1. sshd_config
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
sed -i "/^#\?Port 22$/a Port $NEW_PORT" /etc/ssh/sshd_config
sshd -t || { echo "sshd config test failed"; exit 1; }

# 2. SELinux
if command -v semanage &>/dev/null; then
    semanage port -a -t ssh_port_t -p tcp $NEW_PORT 2>/dev/null || true
else
    echo "WARNING: semanage not found, install policycoreutils-python"
fi

# 3. firewalld
firewall-cmd --permanent --add-port=${NEW_PORT}/tcp
firewall-cmd --reload

# 4. Restart
systemctl restart sshd
echo "SSH port $NEW_PORT added. Test with: ssh -p $NEW_PORT user@host"
echo "After verification, remove Port 22 from sshd_config and semanage/firewalld."

安全建議: 修改端口僅是「安繩上的隱身術」,核心防禦仍是:禁用密碼登錄(PasswordAuthentication no)、強制密鑰認證、配置 Fail2Ban、限制來源 IP、啟用 2FA、審計日志告警。

Copyright © Windows教程網 All Rights Reserved