温馨提示×

Debian防火墙自动化脚本编写

小樊
41
2025-11-21 12:26:56
栏目: 智能运维

在Debian系统上,你可以使用iptablesnftables来配置防火墙规则。以下是一个简单的示例,展示如何使用Bash脚本来自动化设置基本的防火墙规则。

使用 iptables 的示例脚本

  1. 创建一个名为 setup_firewall.sh 的文件:
#!/bin/bash

# 清除现有规则
iptables -F
iptables -X

# 设置默认策略
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# 允许本地回环接口的流量
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

# 允许已建立的连接
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# 允许SSH连接(假设SSH端口为22)
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# 允许HTTP和HTTPS连接
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# 允许DNS查询
iptables -A INPUT -p udp --dport 53 -j ACCEPT
iptables -A INPUT -p tcp --dport 53 -j ACCEPT

# 允许ICMP请求(ping)
iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT

# 保存规则
iptables-save > /etc/iptables/rules.v4

echo "Firewall setup complete."
  1. 赋予脚本执行权限:
chmod +x setup_firewall.sh
  1. 运行脚本:
sudo ./setup_firewall.sh

使用 nftables 的示例脚本

  1. 创建一个名为 setup_firewall.sh 的文件:
#!/bin/bash

# 清除现有规则
nft flush ruleset

# 设置默认策略
nft add rule ip filter input drop
nft add rule ip filter forward drop
nft add rule ip filter output accept

# 允许本地回环接口的流量
nft add rule ip filter input iif lo accept
nft add rule ip filter output oif lo accept

# 允许已建立的连接
nft add rule ip filter input ct state established,related accept
nft add rule ip filter output ct state established,related accept

# 允许SSH连接(假设SSH端口为22)
nft add rule ip filter input tcp dport 22 accept

# 允许HTTP和HTTPS连接
nft add rule ip filter input tcp dport 80 accept
nft add rule ip filter input tcp dport 443 accept

# 允许DNS查询
nft add rule ip filter input udp dport 53 accept
nft add rule ip filter input tcp dport 53 accept

# 允许ICMP请求(ping)
nft add rule ip filter input icmp type echo-request accept

# 保存规则
nft list ruleset > /etc/nftables.conf

echo "Firewall setup complete."
  1. 赋予脚本执行权限:
chmod +x setup_firewall.sh
  1. 运行脚本:
sudo ./setup_firewall.sh

注意事项

  • 运行这些脚本需要超级用户权限,因此请使用 sudo
  • 这些脚本只是基本的防火墙配置示例,实际使用中可能需要根据具体需求进行调整。
  • 如果你使用的是较新的Debian版本,可能会默认使用 nftables 而不是 iptables。请根据你的系统情况选择合适的脚本。

通过这些脚本,你可以自动化地设置基本的防火墙规则,确保系统的安全性。

0