用脚本快速切换网络防火墙

wen 实用脚本 3

自动化管理网络安全的终极指南

目录导读

  1. 为什么需要脚本化防火墙切换?
  2. 主流防火墙脚本工具对比
  3. 实战:Windows防火墙脚本一键切换
  4. 实战:Linux iptables/nftables脚本管理
  5. 高级技巧:条件触发与计划任务
  6. 常见问题与解答

为什么需要脚本化防火墙切换?

Q:为什么不能手动修改防火墙规则,而非要用脚本?

用脚本快速切换网络防火墙

A:在日常运维或开发测试中,我们经常需要在“严格模式”(仅允许特定端口)和“宽松模式”(允许临时调试)之间切换,手动操作不仅耗时,而且容易因误操作导致安全漏洞或服务中断,根据Stack Overflow 2024年开发者调查,超过62%的运维人员曾因手动修改防火墙规则导致过至少一次生产事故。

脚本化切换的三大核心价值:

  • 速度:从输入命令到切换完成,只需0.5-1秒,比手动操作快20倍以上
  • 一致性:脚本执行结果可预测,避免“我上次好像是这样改的”的模糊记忆
  • 可审计:每次切换都能记录日志,满足合规要求

搜索引擎优化提示:将“防火墙脚本切换”与“自动化运维工具如Ansible”结合,本指南重点聚焦单机脚本方案,适合个人开发者或中小团队。


主流防火墙脚本工具对比

Q:Windows和Linux分别用什么工具写防火墙切换脚本?

操作系统 原生工具 脚本语言 优势 劣势
Windows netsh advfirewall PowerShell/Batch 系统自带,兼容性好 语法略显笨重
Windows New-NetFirewallRule PowerShell 面向对象,易于管理 需要较高PowerShell版本
Linux iptables Bash 经典稳定,资料丰富 规则重启后易丢失
Linux nftables Bash 新一代方案,性能更优 学习曲线稍陡
跨平台 ufw (Ubuntu) Bash 语法简单,适合新手 仅限Linux,功能有限

关键告示:无论选择哪种工具,建议将脚本保存在版本控制(如Git)中,并附带md5校验,防止脚本被篡改。


实战:Windows防火墙脚本一键切换

Q:如何写一个脚本,在“允许所有”和“仅允许80/443”之间切换?

以下是一个经过优化的PowerShell脚本,支持三种模式:

# Firewall-Switcher.ps1
param(
    [ValidateSet('strict','open','maintenance')]
    [string]$Mode = 'strict'
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
switch ($Mode) {
    'strict' {
        # 仅允许HTTP/HTTPS和RDP
        netsh advfirewall set allprofiles firewallpolicy blockinbound,allowoutbound
        Enable-NetFirewallRule -DisplayGroup "Remote Desktop"
        New-NetFirewallRule -DisplayName "Allow HTTP" -Direction Inbound -LocalPort 80 -Protocol TCP -Action Allow
        New-NetFirewallRule -DisplayName "Allow HTTPS" -Direction Inbound -LocalPort 443 -Protocol TCP -Action Allow
        Write-Host "[$timestamp] 切换到严格模式:仅80/443/RDP允许入站"
    }
    'open' {
        # 允许所有入站连接(危险!仅用于隔离测试环境)
        netsh advfirewall set allprofiles firewallpolicy allowinbound,allowoutbound
        Write-Host "[$timestamp] 切换到开放模式:允许所有入站 - **风险警告**"
    }
    'maintenance' {
        # 允许特定IP段(如运维IP)
        $adminIP = "192.168.1.100"
        netsh advfirewall set allprofiles firewallpolicy blockinbound,allowoutbound
        New-NetFirewallRule -DisplayName "Allow from admin" -Direction Inbound -RemoteAddress $adminIP -Action Allow
        Write-Host "[$timestamp] 切换到维护模式:仅允许来自$adminIP的连接"
    }
}
# 记录切换日志
$logEntry = "$timestamp | 切换到模式: $Mode"
Add-Content -Path "C:\Logs\fw_switch.log" -Value $logEntry

使用方法

.\Firewall-Switcher.ps1 -Mode strict   # 切换到严格模式
.\Firewall-Switcher.ps1 -Mode open     # 打开所有防火墙

SEO优化提示:本脚本可配合Windows任务计划程序,实现定期自动切换(工作日上午9点开,下午6点关)。


实战:Linux iptables/nftables脚本管理

Q:Linux下如何用脚本实现防火墙规则集的备份与切换?

情景:你需要一个“一键开启Web服务”和“一键锁定”的脚本。

iptables + iptables-save/restore

#!/bin/bash
# /usr/local/bin/fw-switch.sh
function strict_mode() {
    # 清空所有规则
    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 INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
    # 只允许22和443端口
    iptables -A INPUT -p tcp --dport 22 -j ACCEPT
    iptables -A INPUT -p tcp --dport 443 -j ACCEPT
    # 保存规则
    iptables-save > /etc/iptables/rules.v4
    echo "已切换至严格模式:仅22/443端口开放"
}
function open_mode() {
    iptables -P INPUT ACCEPT
    iptables -P FORWARD ACCEPT
    iptables -P OUTPUT ACCEPT
    iptables -F
    iptables -X
    iptables-save > /etc/iptables/rules.v4
    echo "已切换至开放模式 **警告:所有端口开放**"
}
case "$1" in
    strict) strict_mode ;;
    open) open_mode ;;
    status) iptables -L -n -v ;;
    *) echo "用法: $0 {strict|open|status}" ;;
esac

nftables(RHEL 8+/Ubuntu 22+推荐)

#!/bin/bash
# 使用nftables规则集切换
FW_FILE="/etc/nftables.conf"
function strict_nft() {
    cat > $FW_FILE << 'EOF'
#!/usr/sbin/nft -f
flush ruleset
table inet filter {
    chain input {
        type filter hook input priority 0; policy drop;
        ct state established,related accept
        iif "lo" accept
        tcp dport {22, 443} accept
    }
    chain forward {
        type filter hook forward priority 0; policy drop;
    }
    chain output {
        type filter hook output priority 0; policy accept;
    }
}
EOF
    systemctl reload nftables
    echo "nftables严格模式已启用"
}
function open_nft() {
    cat > $FW_FILE << 'EOF'
#!/usr/sbin/nft -f
flush ruleset
table inet filter {
    chain input {
        type filter hook input priority 0; policy accept;
    }
    chain forward {
        type filter hook forward priority 0; policy accept;
    }
    chain output {
        type filter hook output priority 0; policy accept;
    }
}
EOF
    systemctl reload nftables
    echo "nftables已切换为开放模式"
}
case "$1" in
    strict) strict_nft ;;
    open) open_nft ;;
    status) nft list ruleset ;;
    *) echo "用法: $0 {strict|open|status}"
esac

搜索引擎优化技巧:在脚本中加入trap命令捕获退出信号,确保切换失败时自动回滚到上一个安全状态。


高级技巧:条件触发与计划任务

Q:如何让脚本在检测到特定条件时自动切换防火墙?

场景:当检测到SSH爆破攻击时,自动切换为“只允许特定IP连接”。

实现方案:结合fail2ban或自定义监控脚本

#!/bin/bash
# auto-fw-defense.sh
# 设置可信IP列表
TRUSTED_IPS=("10.0.0.1" "192.168.1.100")
# 检测攻击(示例:检查/var/log/auth.log中的失败登录)
ATTACK_DETECTED=$(grep "Failed password" /var/log/auth.log | wc -l)
if [ $ATTACK_DETECTED -gt 10 ]; then
    echo "检测到SSH爆破攻击,自动切换防火墙模式..."
    # 调用切换脚本
    /usr/local/bin/fw-switch.sh strict
    # 仅允许可信IP
    for ip in "${TRUSTED_IPS[@]}"; do
        iptables -A INPUT -s $ip -p tcp --dport 22 -j ACCEPT
    done
    echo "已将SSH访问限制为仅可信IP"
    # 发送告警(邮件或企业微信机器人)
    curl -X POST "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY" \
        -H "Content-Type: application/json" \
        -d '{"msgtype":"text","text":{"content":"防火墙已自动锁定,检测到SSH攻击"}}'
fi

结合cron定期执行

# 每5分钟检查一次攻击日志
*/5 * * * * /usr/local/bin/auto-fw-defense.sh

Windows对应方案:使用PowerShell + 任务计划程序,监控安全事件日志ID 4625(登录失败)。


常见问题与解答

Q:脚本切换防火墙后,正在运行的连接会不会中断? A:不会,iptables/nftables的state模块会保留已建立的连接(ESTABLISHED,RELATED),Windows防火墙同样有连接跟踪机制,但UDP连接的跟踪可能不完整,建议在切换前测试。

Q:切换脚本被误执行了怎么办? A:建议在脚本开头添加确认提示(交互模式),并记录所有切换历史,也可设置“切换间隔限制”,如10分钟内不允许重复切换。

Q:公司有安全策略,脚本必须经过审批才能使用? A:将脚本作为“变更管理”流程的一部分,在脚本中添加版本号、作者签名,并集成到CI/CD的审批网关中,每次切换前需输入审批工单号,否则脚本拒绝执行。

Q:脚本中的明文IP和端口会不会泄露? A:一定不要硬编码敏感信息,建议使用环境变量或外部配置文件,

# 从加密配置文件读取
source /etc/fw-config.enc
# 该文件通过gpg加密,启动时需输入密码

Q:跨平台(Windows+Linux)如何统一管理? A:使用Ansible或SaltStack,编写统一的playbook,在剧本中针对不同OS使用相应的模块(如win_firewall_ruleiptables模块)。

抱歉,评论功能暂时关闭!