加油
努力

TencentOS Server 3.1 如何配置iptables防火墙规则?

在 TencentOS Server 3.1(基于 CentOS 8/RHEL 8 体系)中,虽然默认推荐使用 firewalld 作为防火墙管理工具,但系统仍支持并兼容传统的 iptables。以下是配置 iptables 防火墙规则的完整指南:


一、确认当前防火墙状态

# 检查 firewalld 是否运行(TencentOS 默认启用)
systemctl status firewalld

# 若需使用 iptables,建议先停止 firewalld(避免冲突)
sudo systemctl stop firewalld
sudo systemctl disable firewalld

⚠️ 注意:同时运行 firewalldiptables 可能导致规则冲突。若必须使用 iptables,请确保 firewalld 已禁用。


二、安装/验证 iptables 工具

TencentOS 3.1 通常预装 iptables-services,如未安装可执行:

sudo dnf install -y iptables-services

启动服务并设置开机自启:

sudo systemctl enable --now iptables

三、基础配置示例

1. 查看当前规则

sudo iptables -L -n -v

2. 设置默认策略(拒绝所有入站,允许出站)

sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT

3. 允许已建立的连接(关键!否则无法远程登录)

sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

4. 开放常用端口(以 SSH + HTTP + HTTPS 为例)

# SSH (22)
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# HTTP (80)
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT

# HTTPS (443)
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT

5. 允许本地回环接口

sudo iptables -A INPUT -i lo -j ACCEPT

6. 禁止违规源地址(可选安全加固)

# 丢弃来自无效源地址的数据包
sudo iptables -A INPUT -s 127.0.0.0/8 ! -i lo -j DROP

四、保存规则(持久化)

TencentOS 3.1 使用 iptables-services 时,需手动保存规则:

# 保存当前规则到 /etc/sysconfig/iptables
sudo iptables-save > /etc/sysconfig/iptables

# 或自动保存(推荐配合 service 脚本)
sudo service iptables save

✅ 重启后规则将自动加载(因 iptables 服务已启用)。


五、验证与测试

  • 重新连接 SSH 会话前务必确认规则正确,避免被锁外。
  • 使用新终端测试端口连通性:
    telnet <服务器IP> 22
    curl http://<服务器IP>

六、替代方案建议(推荐)

若无需深度定制 iptables,更推荐使用 firewalld(TencentOS 默认且更易维护):

# 启用 firewalld
sudo systemctl enable --now firewalld

# 开放端口(动态生效,无需重启)
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

如需进一步自定义链(如自定义过滤规则、NAT 转换等),可提供具体场景,我可给出针对性配置。

云服务器