基于宝塔的firewall 一键封禁非中国大陆ip

600.one 默认分类 2025-01-26

每小时更新一次的中国ip库

https://github.com/mayaxcn/china-ip-list?tab=readme-ov-file

下载中国ip段
https://raw.githubusercontent.com/mayaxcn/china-ip-list/master/chnroute.txt

mv chnroute.txt china_ip_list.txt # 文本重命名

或者

wget -O china_ip_list.txt https://raw.githubusercontent.com/mayaxcn/china-ip-list/master/chnroute.txt

基于宝塔firewalld的防火墙一键封禁国外ip的脚本

#!/bin/bash

add_china_ips() {
    sudo firewall-cmd --permanent --new-ipset=china_ip_list --type=hash:net
    sudo firewall-cmd --permanent --ipset=china_ip_list --add-entries-from-file=china_ip_list.txt
}

remove_china_ips() {
    sudo firewall-cmd --permanent --delete-ipset=china_ip_list
}

block_foreign_ips() {
    echo "正在封禁非中国IP..."
    add_china_ips
    sudo firewall-cmd --permanent --zone=public --add-rich-rule='rule family="ipv4" source ipset="china_ip_list" accept'
    sudo firewall-cmd --permanent --zone=public --add-rich-rule='rule family="ipv4" source not ipset="china_ip_list" reject'
    sudo firewall-cmd --reload
    echo "非中国IP已被封禁。"
}

unblock_all_ips() {
    echo "正在解封所有IP..."
    remove_china_ips
    sudo firewall-cmd --permanent --zone=public --remove-rich-rule='rule family="ipv4" source ipset="china_ip_list" accept'
    sudo firewall-cmd --permanent --zone=public --remove-rich-rule='rule family="ipv4" source not ipset="china_ip_list" reject'
    sudo firewall-cmd --reload
    echo "所有IP已被解封。"
}

if [ "$1" == "block" ]; then
    block_foreign_ips
elif [ "$1" == "unblock" ]; then
    unblock_all_ips
else
    echo "使用方法: $0 [block|unblock]"
    exit 1
fi

保存为

block_ip.sh
chmod +x block_ip.sh

使用方法

./block_ip.sh block
./block_ip.sh unblock

查看当前的防火墙状态和配置
查看防火墙的状态:
bash
sudo firewall-cmd --state
列出所有配置:
bash
sudo firewall-cmd --list-all
列出当前生效的防火墙规则:
bash
sudo firewall-cmd --list-all-zones
列出所有永久配置(未生效的规则):
bash
sudo firewall-cmd --permanent --list-all

查看具体规则
查看特定区域(zone)的规则:
bash
sudo firewall-cmd --zone=public --list-all
查看所有服务规则:
bash
sudo firewall-cmd --list-services
查看所有端口规则:
bash
sudo firewall-cmd --list-ports
查看所有富规则(rich rules):
bash
sudo firewall-cmd --list-rich-rules
查看所有源地址规则:
bash
sudo firewall-cmd --list-sources
查看所有接口规则:
bash
sudo firewall-cmd --list-interfaces

管理规则
添加一个服务(比如,允许HTTP):
bash
sudo firewall-cmd --permanent --add-service=http
添加一个端口:
bash
sudo firewall-cmd --permanent --add-port=8080/tcp
添加一个富规则:
bash
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.0.0/24" port protocol="tcp" port="80" accept'
删除一个规则:
例如,删除一个端口:
bash
sudo firewall-cmd --permanent --remove-port=8080/tcp
使永久更改生效:
bash
sudo firewall-cmd --reload

其他有用的命令
查看所有已定义的区域:
bash
sudo firewall-cmd --get-zones
查看某个区域的默认配置:
bash
sudo firewall-cmd --zone=public --list-all
查询特定服务是否允许:
bash
sudo firewall-cmd --query-service=http
查询特定端口是否开放:
bash
sudo firewall-cmd --query-port=80/tcp

注意:

--permanent 选项使得更改永久生效,但需要重新加载防火墙配置(--reload)才能应用于运行中的防火墙。
如果不使用--permanent,更改只会在本次系统运行中生效,重启后会丢失。

评论(0)

发布评论