配置 SELinux 以允许非默认 SSH 端口

默认 SELinux 配置不允许任何服务在非默认端口上运行。
因此,我们必须配置 SElinux 以允许 SSH 使用端口 2222/tcp 。

我们需要 semanage 命令来配置 SELinux 设置。
如果我们使用的是最小安装的 CentOS 8 系统,那么它在系统上不可用。

安装 policycoreutils-python-utils 包以获取 semanage 命令。

然后使用 semanage 命令添加端口 2222/tcp 以键入 ssh_port_t 。

# semanage port -a -t ssh_port_t -p tcp 2222

重启 SSH 服务

重新启动 SSH 服务以应用我们在 sshd_config 文件中所做的更改。

# systemctl restart sshd.service

验证 SSH 服务的状态。

# systemctl status sshd.service
 
Aug 08 18:13:37 centos-8.onitroad.com sshd[10376]: Server listening on 0.0.0.0 port 2222.
Aug 08 18:13:37 centos-8.onitroad.com sshd[10376]: Server listening on :: port 2222.
Aug 08 18:13:37 centos-8.onitroad.com systemd[1]: Started OpenSSH server daemon.

我们可以看到该服务现在在非默认端口 2222 上运行 。

在 CentOS/RHEL 8 中更改默认 SSH 端口

SSH 守护进程/服务配置位于 /etc/ssh/sshd_config 文件中。
我们可以根据我们的要求调整它们以自定义 SSH 服务。

最初在这个文件中没有 Port 指令,相反,SSH 服务使用默认的 ssh 端口号 22.

让我们使用 echo 命令在 sshd_config 文件中添加一个 Port 指令。

# echo "Port 2222" >> /etc/ssh/sshd_config

使用非默认 SSH 端口访问服务

尝试从默认 ssh 端口使用 ssh 和 sftp 命令访问 SSH 服务。

# ssh root@centos-8.onitroad.com
ssh: connect to host centos-8.onitroad.com port 22: Connection refused
# sftp root@centos-8.onitroad.com
ssh: connect to host centos-8.onitroad.com port 22: Connection refused
Connection closed.
Connection closed

它确认 Linux 防火墙不允许流量通过端口 22.

现在,从非默认 ssh 端口使用 ssh 命令访问 SSH 服务。

# ssh root@centos-8.onitroad.com -p 2222
The authenticity of host '[centos-8.onitroad.com]:2222 ([192.168.1.206]:2222)' can't be established.
ECDSA key fingerprint is SHA256:skGj4xg0w+jIQtrfF8AOdfItgcXUQQu+bWUFfvws1Hk.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '[centos-8.onitroad.com]:2222,[192.168.1.206]:2222' (ECDSA) to the list of known hosts.
root@centos-8.onitroad.com's password:
Last login: Sat Aug  8 17:59:01 2020
#

同样,对于 sftp 。

# sftp -P 2222 root@centos-8.onitroad.com
root@centos-8.onitroad.com's password:
Connected to root@centos-8.onitroad.com.
sftp>

检查 SSH 服务的状态:

使用 systemctl 命令验证 SSH 服务的当前状态。

# systemctl status sshd.service
 
Aug 08 17:59:18 centos-8.onitroad.com sshd[1564]: Server listening on 0.0.0.0 port 22.
Aug 08 17:59:18 centos-8.onitroad.com sshd[1564]: Server listening on :: port 22.
Aug 08 17:59:18 centos-8.onitroad.com systemd[1]: Started OpenSSH server daemon.

我们可以看到该服务在默认的 SSH 端口号 22 上运行。

https://onitroad.com 更多教程

配置防火墙以允许非默认 SSH 端口

列出 Linux 防火墙中允许的端口或者服务。

# firewall-cmd --list-all
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: ens33
  sources:
  services: cockpit dhcpv6-client ssh
  ports:
  protocols:
  masquerade: no
  icmp-blocks:
  rich rules:

大多数 Linux 发行版(包括 CentOS/RHEL 8)默认允许 SSH 服务。

现在,我们需要阻止这个 ssh 服务并在 Linux 防火墙中允许我们的新 ssh 端口。

# firewall-cmd --permanent --remove-service=ssh
success
# firewall-cmd --permanent --add-port=2222/tcp
success
# firewall-cmd --reload
success
如何更改 CentOS/RHEL 8 中的默认 SSH 端口

SSH 的标准 TCP 端口是 22。
为了安全我们可以修改为其他端口。

日期:2020-09-17 00:12:47 来源:oir作者:oir