温馨提示×

centos哪里替换ssh端口设置

小樊
47
2026-09-06 09:44:44
栏目: 智能运维

在 CentOS 中修改(替换)SSH 端口,通常是在 SSH 服务端配置文件 里改,然后重启服务,并注意防火墙和 SELinux。


一、修改 SSH 端口配置文件

编辑 SSH 配置文件:

vi /etc/ssh/sshd_config

找到这一行(默认可能是注释的):

#Port 22

改成你想要的端口,例如:

Port 2222

如果想保留 22 再加一个端口,也可以写多行:

Port 22
Port 2222

保存退出(:wq)。


二、关闭 SELinux 限制(或放行端口)

方式 1:临时关闭 SELinux(不推荐生产)

setenforce 0

方式 2:放行 SSH 新端口(推荐)

semanage port -a -t ssh_port_t -p tcp 2222

如果提示 semanage 不存在:

yum install policycoreutils-python -y

三、防火墙放行新端口

firewalld(CentOS 7/8)

firewall-cmd --permanent --add-port=2222/tcp
firewall-cmd --reload

iptables(老版本)

iptables -A INPUT -p tcp --dport 2222 -j ACCEPT
service iptables save

四、重启 SSH 服务

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),我可以给你更精确的命令。

0