debian

Debian下如何配置防火墙

小樊
38
2025-03-22 10:54:01
栏目: 智能运维

在Debian系统下,你可以使用iptablesufw(Uncomplicated Firewall)来配置防火墙。以下是两种方法的简要说明和步骤:

方法一:使用iptables

  1. 安装iptables(如果尚未安装)

    sudo apt update
    sudo apt install iptables
    
  2. 查看当前的iptables规则

    sudo iptables -L -n -v
    
  3. 添加规则

    • 允许特定IP访问SSH端口(默认22)
      sudo iptables -A INPUT -p tcp --dport 22 -s 你的IP地址 -j ACCEPT
      
    • 允许特定IP访问HTTP端口(默认80)
      sudo iptables -A INPUT -p tcp --dport 80 -s 你的IP地址 -j ACCEPT
      
    • 允许特定IP访问HTTPS端口(默认443)
      sudo iptables -A INPUT -p tcp --dport 443 -s 你的IP地址 -j ACCEPT
      
    • 允许特定IP访问MySQL端口(默认3306)
      sudo iptables -A INPUT -p tcp --dport 3306 -s 你的IP地址 -j ACCEPT
      
    • 拒绝所有其他入站连接
      sudo iptables -P INPUT DROP
      
  4. 保存iptables规则 Debian默认不保存iptables规则,你需要手动保存:

    sudo sh -c "iptables-save > /etc/iptables/rules.v4"
    
  5. 设置iptables在启动时自动加载规则 编辑/etc/network/if-pre-up.d/iptables文件:

    sudo nano /etc/network/if-pre-up.d/iptables
    

    添加以下内容:

    #!/bin/sh
    /sbin/iptables-restore < /etc/iptables/rules.v4
    

    赋予执行权限:

    sudo chmod +x /etc/network/if-pre-up.d/iptables
    

方法二:使用ufw

  1. 安装ufw(如果尚未安装)

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

    sudo ufw enable
    
  3. 查看ufw状态

    sudo ufw status
    
  4. 添加规则

    • 允许特定IP访问SSH端口(默认22)
      sudo ufw allow from 你的IP地址 to any port 22
      
    • 允许特定IP访问HTTP端口(默认80)
      sudo ufw allow from 你的IP地址 to any port 80
      
    • 允许特定IP访问HTTPS端口(默认443)
      sudo ufw allow from 你的IP地址 to any port 443
      
    • 允许特定IP访问MySQL端口(默认3306)
      sudo ufw allow from 你的IP地址 to any port 3306
      
  5. 禁用ufw(如果需要)

    sudo ufw disable
    

注意事项

通过以上步骤,你可以在Debian系统下配置防火墙,保护你的服务器免受不必要的网络攻击。

0
看了该问题的人还看了