c handbook-master/docs/CentOS
修改ssh端口号的方法| modified | Tuesday 7 July 2026 |
|---|
使用场景,公司一个公网IP,两台服务器,所以尝试使用修改ssh端口号的方法,来链接不同的服务器。
1netstat -tnlp # 查看端口
2netstat -tnlp |grep ssh # 查看ssh端口
3
4tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 986/sshd
5tcp6 0 0 :::22 :::* LISTEN 986/sshd
1vi /etc/ssh/sshd_config
2#Port 22 # 这行去掉#号
3Port 2211 # 下面添加这一行
修改SELinux
1# 修改SELinux
2# 使用以下命令查看当前SElinux 允许的ssh端口:
3semanage port -l | grep ssh
4
5# 添加2211端口到 SELinux
6semanage port -a -t ssh_port_t -p tcp 2211
7
8# 然后确认一下是否添加进去
9semanage port -l | grep ssh
10
11# 如果成功会输出
12ssh_port_t tcp 2211, 22
重启ssh
1systemctl restart sshd.service
不过上述方法仅仅是在ssh中设置端口,还要在防火墙firewalld中放行才是
1# 还有一种办法直接关掉, 执行下面三条命令
2sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
3grep SELINUX=disabled /etc/selinux/config
4setenforce 0
1# 编辑文件/etc/sysconfig/iptables 添加下面这行
2-A INPUT -p tcp -m state --state NEW -m tcp --dport 2211 -j ACCEPT
也可下面方法
1# 防火墙中开启端口2211
2firewall-cmd --zone=public --add-port=2211/tcp --permanent
3
4# 查看2211端口打开情况
5firewall-cmd --zone=public --query-port=2211/tcp
重启iptables
1systemctl stop iptables
2systemctl start iptables
3systemctl status iptables
重启 ssh 查看状态
1systemctl restart sshd.service
2systemctl status sshd