# 1. 拒絕所有 SSH 連線
echo "sshd:ALL" >> /etc/hosts.deny
# 2. 允許特定 IP/網段
echo "sshd:192.168.1.16" >> /etc/hosts.allow
# 或允許網段
echo "sshd:192.168.1.0/255.255.255.0" >> /etc/hosts.allow
# 或允許主機名
echo "sshd:trusted.host.domain" >> /etc/hosts.allow
生效順序:hosts.allow 優先 → hosts.deny → 未匹配則允許
vim /etc/ssh/sshd_config
# 找到 #Port 22,修改為雙埠過渡期:
Port 22
Port 9999
# 過渡期驗證無誤後,僅保留新埠:
# Port 9999
/etc/init.d/sshd restart
# 或
systemctl restart sshd
# iptables
iptables -A INPUT -p tcp --dport 9999 -j ACCEPT
service iptables save
# firewalld
firewall-cmd --permanent --add-port=9999/tcp
firewall-cmd --reload
# ufw
ufw allow 9999/tcp
ssh -p 9999 user@server
# 或配置 ~/.ssh/config
Host myserver
HostName server.ip
Port 9999
User myuser
# 移除 sshd_config 中的 Port 22
# 移除防火牆 22 埠規則
iptables -D INPUT -p tcp --dport 22 -j ACCEPT
service iptables save
/etc/init.d/sshd restart
防止修改配置過程中斷線、配置錯誤導致完全無法連線,必須跑機房掛顯示器鍵盤修復。雙埠並行驗證成功後再關閉舊埠,風險為零。
PermitRootLogin no
# 或僅允許金鑰
PermitRootLogin prohibit-password
AllowUsers admin deploy@192.168.1.*
AllowGroups sshusers
PasswordAuthentication no
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
Protocol 2
ClientAliveInterval 300
ClientAliveCountMax 2
# 5分鐘無回應斷線
# 建立 /etc/ssh/banner.txt
echo "*** Authorized Access Only ***" > /etc/ssh/banner.txt
# sshd_config
Banner /etc/ssh/banner.txt
MaxAuthTries 3
MaxSessions 2
# 語法檢查
sshd -t
# 顯示生效配置
sshd -T | grep -E 'port|permitroot|passwordauth|pubkey|protocol|banner|clientalive|maxauth'
# 連線測試
ssh -vvv -p 9999 user@server