在 CentOS 中修改(替换)SSH 端口,通常是在 SSH 服务端配置文件 里改,然后重启服务,并注意防火墙和 SELinux。
编辑 SSH 配置文件:
vi /etc/ssh/sshd_config
找到这一行(默认可能是注释的):
#Port 22
改成你想要的端口,例如:
Port 2222
如果想保留 22 再加一个端口,也可以写多行:
Port 22 Port 2222
保存退出(:wq)。
setenforce 0
semanage port -a -t ssh_port_t -p tcp 2222
如果提示 semanage 不存在:
yum install policycoreutils-python -y
firewall-cmd --permanent --add-port=2222/tcp
firewall-cmd --reload
iptables -A INPUT -p tcp --dport 2222 -j ACCEPT
service iptables save
systemctl restart sshd
⚠️ 重要:
在断开当前连接前,用新端口测试能否登录:
ssh -p 2222 user@服务器IP
确认没问题后,再考虑注释掉 Port 22。
| 项目 | 位置 |
|---|---|
| SSH 端口配置 | /etc/ssh/sshd_config |
| 防火墙 | firewalld / iptables |
| SELinux 端口 | ssh_port_t |
| 服务管理 | systemctl restart sshd |
如果你告诉我 CentOS 版本(6 / 7 / 8 / Stream),我可以给你更精确的命令。