debian

Debian Context里如何设置防火墙

小樊
41
2025-09-04 17:34:18
栏目: 智能运维

在Debian系统中,常用ufwiptables配置防火墙,以下是具体方法:

使用ufw(推荐,简单易用)

  1. 安装ufw

    sudo apt update && sudo apt install ufw  
    
  2. 启用ufw

    sudo ufw enable  
    
  3. 配置规则

    • 允许端口(如HTTP/HTTPS):
      sudo ufw allow 80/tcp  # HTTP  
      sudo ufw allow 443/tcp # HTTPS  
      
    • 拒绝端口(如FTP):
      sudo ufw deny 21/tcp  
      
    • 允许特定IP访问
      sudo ufw allow from 192.168.1.100 to any port 22  
      
  4. 查看状态

    sudo ufw status  
    
  5. 保存规则(自动生效,无需手动保存)

使用iptables(底层工具,需手动配置)

  1. 安装iptables

    sudo apt update && sudo apt install iptables  
    
  2. 配置规则

    • 允许SSH
      sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT  
      
    • 拒绝其他入站流量
      sudo iptables -P INPUT DROP  
      sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT  
      
  3. 保存规则

    sudo iptables-save > /etc/iptables/rules.v4  
    
  4. 设置开机自启
    创建服务文件/etc/systemd/system/iptables-restore.service,内容如下:

    [Unit]  
    Description=Restore IPTables rules  
    Before=network.target  
    
    [Service]  
    Type=oneshot  
    ExecStart=/sbin/iptables-restore < /etc/iptables/rules.v4  
    
    [Install]  
    WantedBy=multi-user.target  
    

    然后执行:

    sudo systemctl enable iptables-restore.service  
    sudo systemctl start iptables-restore.service  
    

注意事项

0
看了该问题的人还看了