CentOS

1. 备份 SSH 的配置文件

sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

2. 修改配置文件

vim /etc/ssh/sshd_config

为了出现不正确的改了 SSH 端口,导致设备无法正常登陆的情况,我们先保留 22 端口并添加新的端口,确认无问题后再禁掉 22 端口

# If you want to change the port on a SELinux system, you have to tell
# SELinux about this change.
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
#
Port 22
Port 10022
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

然后保存配置。

3. SELINUX添加新的端口以供SSH登陆

安装 SEManage

yum -y install policycoreutils-python

通过 SEManage 添加新的SSH端口

semanage port -a -t ssh_port_t -p tcp 10022

4. 防火墙放行新的 SSH 端口

放行新的 SSH 端口

firewall-cmd --permanent --zone=public --add-port=10022/tcp

查看防火墙状态

firewall-cmd --state

5. 重新加载防火墙状态

firewall-cmd --reload

6. 重启 SSH 服务,查看SSH服务状态,并检查是否已经正常监听新端口

systemctl restart sshd
systemctl status sshd
ss -tnlp | grep ssh

7. 使用新端口登陆测试,如果成功则禁用原 SSH 端口

# If you want to change the port on a SELinux system, you have to tell
# SELinux about this change.America/Phoenix
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
#
# Port 22
Port 10022
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

8. 重启 SSH 服务

systemctl restart sshd

Ubuntu

由于 Ubuntu 默认端口全开,因此我们不必配置 iptables 或 ufw 放行新的端口。不过为了保险起见,我们依旧应该先测试新端口是否能正常连接再关闭旧端口。

1. 备份 SSH 的配置文件

sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

2. 修改配置文件

vim /etc/ssh/sshd_config

为了出现不正确的改了SSH端口,导致设备无法正常登陆的情况,我们先保留22端口并添加新的端口,确认无问题后再禁掉22端口

# If you want to change the port on a SELinux system, you have to tell
# SELinux about this change.
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
#
Port 22
Port 10022
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

然后保存配置。

3. 重启 SSH 服务,查看SSH服务状态,并检查是否已经正常监听新端口

systemctl restart sshd
systemctl status sshd
ss -tnlp | grep ssh

4. 使用新端口登陆测试,如果成功则禁用原 SSH 端口

# If you want to change the port on a SELinux system, you have to tell
# SELinux about this change.America/Phoenix
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
#
# Port 22
Port 10022
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

5. 重启 SSH 服务

systemctl restart sshd