linux

Linux防火墙如何配置IP白名单

小樊
72
2025-08-23 16:37:18
栏目: 智能运维

在Linux系统中,配置IP白名单通常涉及使用iptables或firewalld等工具。以下是使用这两种工具配置IP白名单的基本步骤:

使用iptables配置IP白名单

  1. 清空现有规则(可选,但推荐):

    sudo iptables -F
    
  2. 设置默认策略(可选):

    sudo iptables -P INPUT DROP
    sudo iptables -P FORWARD DROP
    sudo iptables -P OUTPUT ACCEPT
    
  3. 允许本地回环接口的流量

    sudo iptables -A INPUT -i lo -j ACCEPT
    
  4. 允许已建立的连接

    sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
    
  5. 添加IP白名单规则: 假设你想允许IP地址为192.168.1.100的设备访问:

    sudo iptables -A INPUT -s 192.168.1.100 -j ACCEPT
    
  6. 保存规则(根据发行版不同,命令可能有所不同):

    • Debian/Ubuntu:
      sudo sh -c "iptables-save > /etc/iptables/rules.v4"
      
    • CentOS/RHEL:
      sudo service iptables save
      
  7. 重启iptables服务(如果需要):

    sudo systemctl restart iptables
    

使用firewalld配置IP白名单

  1. 启用firewalld服务(如果尚未启用):

    sudo systemctl start firewalld
    sudo systemctl enable firewalld
    
  2. 添加IP白名单规则: 假设你想允许IP地址为192.168.1.100的设备访问:

    sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.100" accept'
    
  3. 重新加载firewalld配置

    sudo firewall-cmd --reload
    

验证配置

无论使用哪种工具,都可以通过以下命令查看当前的防火墙规则:

通过这些步骤,你可以成功配置Linux系统的IP白名单,确保只有指定的IP地址可以访问你的系统。

0
看了该问题的人还看了