操作系统:CentOS 7.9
防火墙:firewalld
防火墙设置
防火墙先放行要设置的SSH端口,防止端口修改后无法远程服务器。
# 23622是将要设置的SSH端口号
sudo firewall-cmd --permanent --zone=public --add-port=23622/tcp
# 重新加载
sudo firewall-cmd --reload
SELinux设置
如果 SELinux 未配置,启动sshd服务时,会提示“Bind to port xxx on 0.0.0.0 failed: Permission denied.” 的错误,详见最后章节的说明。
配置SELinux的端口策略
安装 policycoreutils-python
软件包,用于管理和操作 SELinux 策略。
sudo yum install policycoreutils-python
使用semanage
工具将指定端口号设置为ssh可用端口。
sudo semanage port -a -t ssh_port_t -p tcp 22322
或者 直接关闭SELinux(不推荐)
先临时禁用SELinux
sudo setenforce 0
然后修改配置文件,永久禁用SELinux
sudo vi /etc/selinux/config
修改SELINUX
为disabled
后,保存即可。
SELINUX=disabled
修改SSH端口
编辑 sshd_config 文件。
# 编辑sshd_config
sudo vi /etc/ssh/sshd_config
在里面添加端口配置,其中23622为修改后的端口号。
Port 23622
保存后重启 SSH服务。
sudo systemctl restart sshd.service
测试SSH连接
使用telnet 或 ssh连接工具测试新端口是否能访问。
注意:在测试成功之前,不要关闭当前的SSH连接。
Bind to port xx on 0.0.0.0 failed: Permission denied.
SELinux未作处理的情况下,启动sshd 服务,会提示如下错误:
[root@localhost ~]# sudo systemctl start sshd
Job for sshd.service failed because the control process exited with error code. See "systemctl status sshd.service" and "journalctl -xe" for details.
sudo journalctl -xe
查看详细错误信息如下:
11月 05 10:10:23 localhost.localdomain sshd[8297]: error: Bind to port 22322 on 0.0.0.0 failed: Permission denied.
11月 05 10:10:23 localhost.localdomain sshd[8297]: error: Bind to port 22322 on :: failed: Permission denied.
11月 05 10:10:23 localhost.localdomain sshd[8297]: fatal: Cannot bind any address.
11月 05 10:10:23 localhost.localdomain systemd[1]: sshd.service: main process exited, code=exited, status=255/n/a
11月 05 10:10:23 localhost.localdomain systemd[1]: Failed to start OpenSSH server daemon.
原因是绑定端口的操作被SELinux 阻止了,如何处理可参考“SELinux设置”章节的说明。