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 SSH 端口修改與安全加固雙重保障實戰

編輯:關於 Linux

SSH 服務默認監聽 22 端口,長期暴露於公網將面臨暴力破解、掃描攻擊風險。修改默認端口雖非絕對安全,但能有效避開 90% 以上自動化掃描腳本。本文提供「雙端口平滑遷移」「防火牆聯動」「TCP Wrapper 訪問控制」三層防護體系,確保修改過程零斷連、生產環境零風險。

SSH 端口修改流程圖

方案一:單端口直接修改 (僅限可承受短暫中斷的環境)


# 1. 備份配置
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

# 2. 修改端口 (建議 10000-65535 間未佔用端口,如 2222/50000)
vim /etc/ssh/sshd_config
Port 50000
# 註釋掉原 Port 22

# 3. 重啟 SSH 服務
systemctl restart sshd

# 4. 防火牆放行新端口
firewall-cmd --add-port=50000/tcp --permanent
firewall-cmd --reload
# 或 iptables
iptables -A INPUT -p tcp --dport 50000 -j ACCEPT
service iptables save

# 5. 客戶端連接驗證
ssh -p 50000 user@server

風險:重啟瞬間現有連接斷開,若新端口防火牆未放行將導致永久失聯。

方案二:雙端口平滑遷移 (生產環境強推,零斷連)


# 1. 配置雙端口監聽
vim /etc/ssh/sshd_config
Port 22
Port 50000
# 保留 22,新增 50000

# 2. 重啟 SSH 服務 (此時雙端口均可連接)
systemctl restart sshd

# 3. 防火牆放行新端口
firewall-cmd --add-port=50000/tcp --permanent
firewall-cmd --reload

# 4. 客戶端驗證新端口連通性
ssh -p 50000 user@server
# 確認新端口登錄、操作完全正常

# 5. 移除舊端口
vim /etc/ssh/sshd_config
# 刪除 Port 22 行,保留 Port 50000
systemctl restart sshd

# 6. 防火牆關閉舊端口
firewall-cmd --remove-port=22/tcp --permanent
firewall-cmd --reload

核心邏輯:新舊並存驗證 → 切換客戶端 → 關閉舊端口。任何階段失敗均可回滾至 22 端口搶救。

進階加固:TCP Wrapper 限制訪問來源


# 1. 拒絕所有 SSH 連接
echo "sshd: ALL" >> /etc/hosts.deny

# 2. 僅允許受信任 IP/網段
echo "sshd: 192.168.1.0/255.255.255.0" >> /etc/hosts.allow
echo "sshd: 203.0.113.50" >> /etc/hosts.allow
# 支援 CIDR、主機名、IP 範圍

# 3. 驗證生效 (無需重啟服務)
ssh user@server  # 受信任 IP 正常,其他 IP 直接拒絕連接

優先級:hosts.allow > hosts.deny。配合防火牆雙層過濾。

方案三:fail2ban 智能封禁暴力破解 (必裝)


# 安裝
apt install fail2ban  # 或 yum install fail2ban

# 配置 /etc/fail2ban/jail.local
[sshd]
enabled = true
port = 50000          # 對應修改後的 SSH 端口
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600        # 封禁 1 小時
findtime = 600

# 啟動
systemctl enable --now fail2ban

驗證清單

檢查項命令預期結果
SSH 監聽端口ss -tlnp | grep sshdLISTEN 0 128 *:50000
防火牆規則firewall-cmd --list-ports50000/tcp
TCP Wrappercat /etc/hosts.allow包含允許規則
fail2ban 狀態fail2ban-client status sshdStatus: active, Jail list: sshd
客戶端連接ssh -p 50000 user@server登錄成功、操作正常

總結

SSH 端口修改遵循 「雙端口驗證 → 切換 → 關閉舊端口」 黃金法則,配合 防火牆端口控制 + TCP Wrapper 來源限制 + fail2ban 智能封禁 三層防護,將暴露面壓縮至最小。生產環境變更務必在維護窗口期執行,並準備好控制台/串口/雲廠商 VNC 等帶外管理通道作為最後防線。

Copyright © Windows教程網 All Rights Reserved