温馨提示×

Linux Trigger:怎样配置防火墙规则

小樊
52
2025-09-30 10:45:47
栏目: 智能运维

在Linux系统中,配置防火墙规则通常使用iptablesfirewalld工具。以下是使用这两个工具配置防火墙规则的基本步骤:

使用 iptables

  1. 查看当前规则

    sudo iptables -L -n -v
    
  2. 允许特定IP访问

    sudo iptables -A INPUT -s 192.168.1.100 -j ACCEPT
    
  3. 拒绝特定IP访问

    sudo iptables -A INPUT -s 192.168.1.101 -j DROP
    
  4. 允许特定端口访问

    sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
    
  5. 拒绝特定端口访问

    sudo iptables -A INPUT -p tcp --dport 22 -j DROP
    
  6. 保存规则

    sudo iptables-save > /etc/iptables/rules.v4
    
  7. 恢复规则

    sudo iptables-restore < /etc/iptables/rules.v4
    

使用 firewalld

  1. 查看当前区域和规则

    sudo firewall-cmd --list-all
    
  2. 允许特定IP访问

    sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.100" accept'
    
  3. 拒绝特定IP访问

    sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.101" reject'
    
  4. 允许特定端口访问

    sudo firewall-cmd --permanent --add-port=80/tcp
    
  5. 拒绝特定端口访问

    sudo firewall-cmd --permanent --remove-port=22/tcp
    
  6. 重新加载防火墙配置

    sudo firewall-cmd --reload
    

注意事项

  • 备份规则:在修改防火墙规则之前,建议备份当前的规则集,以便在出现问题时可以恢复。
  • 权限:配置防火墙规则通常需要超级用户权限,因此需要使用sudo
  • 持久化iptables的规则在系统重启后会丢失,除非使用iptables-saveiptables-restore命令保存和恢复规则。firewalld的规则可以通过--permanent选项设置为持久化。

通过以上步骤,你可以根据需要配置Linux系统的防火墙规则,以保护你的系统免受不必要的网络访问。

0