温馨提示×

CentOS iptables中如何添加规则

小樊
38
2025-11-17 17:28:29
栏目: 智能运维

在 CentOS 系统中,使用 iptables 命令可以管理防火墙规则。以下是添加规则的步骤:

  1. 打开终端:首先,确保你有权限访问服务器的终端。通常需要 root 权限。

  2. 查看现有规则(可选):在添加新规则之前,你可以查看当前的 iptables 规则,以便了解现有的配置。

    sudo iptables -L -n -v
    
  3. 添加规则:使用 iptables 命令添加规则。以下是一些常见的规则示例:

    • 允许特定 IP 访问

      sudo iptables -A INPUT -s 192.168.1.100 -j ACCEPT
      

      这条规则允许来自 IP 地址 192.168.1.100 的所有流量。

    • 拒绝特定 IP 访问

      sudo iptables -A INPUT -s 192.168.1.101 -j DROP
      

      这条规则拒绝来自 IP 地址 192.168.1.101 的所有流量。

    • 允许特定端口

      sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
      

      这条规则允许 TCP 流量通过端口 80(HTTP)。

    • 拒绝特定端口

      sudo iptables -A INPUT -p tcp --dport 22 -j DROP
      

      这条规则拒绝 TCP 流量通过端口 22(SSH)。

    • 允许已建立的连接

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

      这条规则允许所有已建立的连接和相关的流量。

  4. 保存规则:在 CentOS 7 及更高版本中,iptables 规则在重启后不会自动保存。你可以使用 firewalld 服务来管理防火墙规则,或者手动保存规则。

    • 使用 firewalld 服务(推荐):

      sudo systemctl start firewalld
      sudo systemctl enable firewalld
      
    • 手动保存规则

      sudo service iptables save
      

      或者

      sudo iptables-save > /etc/sysconfig/iptables
      
  5. 重启防火墙(可选):如果你手动保存了规则,可能需要重启防火墙以使更改生效。

    sudo systemctl restart iptables
    

通过以上步骤,你可以在 CentOS 系统中使用 iptables 添加和管理防火墙规则。请根据你的具体需求调整规则。

0