封禁指定国家IP访问

发布于 12 天前  31 次阅读


AI 摘要

### 摘要: 本文介绍了如何封禁指定国家的IP访问,包括通过一键脚本实现端口范围封禁和全部端口封禁的方法。此外,文章详细讲解了通过创建开机自动运行脚本,实现指定国家IP的持久化封禁步骤。文中提供了具体代码,以及脚本参数配置方法,例如国家代码(`geoip`)和端口范围设置。同时,还展示了如何配置系统服务确保规则在系统启动时生效。

一键脚本

封端口范围

   curl -L https://static.7li7li.com/block-ips/block-ips.sh -o block-ips.sh && chmod +x block-ips.sh && ./block-ips.sh

封全部端口

   curl -L https://static.7li7li.com/block-ips/block-ips.sh -o block-ips.sh && chmod +x block-ips.sh && ./block-ips-all.sh

封禁ip时会要求你输入国家代码,代码查看:点击进入。参数均为小写字母,以上脚本重启后失效。

开机自动屏蔽

1.新建sh脚本

  sudo vim /usr/local/bin/block_ip.sh

输入以下内容,注意修改脚本内的国家和端口号

#!/bin/bash

# 定义颜色
Green="\033[32m"
Font="\033[0m"

# 内置配置
GEOIP="cn"                 # 要封禁的国家代码
START_PORT="1024"          # 起始端口
END_PORT="65535"          # 结束端口

# 检查ipset是否安装
check_ipset() {
    if ! command -v ipset &> /dev/null; then
        echo -e "${Green}正在安装ipset...${Font}"
        apt-get update
        apt-get install -y ipset
    fi
}

# 封禁ip函数
block_ipset(){
    check_ipset
    
    echo -e "${Green}正在下载IPs data...${Font}"
    wget -P /tmp http://www.ipdeny.com/ipblocks/data/countries/$GEOIP.zone 2> /dev/null
    
    if [ ! -f "/tmp/$GEOIP.zone" ]; then
        echo -e "${Green}下载失败,请检查网络连接!${Font}"
        echo -e "${Green}代码查看地址:http://www.ipdeny.com/ipblocks/data/countries/${Font}"
        exit 1
    fi
    
    echo -e "${Green}IPs data下载成功!${Font}"
    
    # 删除已存在的同名规则(如果存在)
    ipset destroy $GEOIP 2>/dev/null
    
    # 创建规则
    ipset -N $GEOIP hash:net
    for i in $(cat /tmp/$GEOIP.zone ); do ipset -A $GEOIP $i; done
    rm -f /tmp/$GEOIP.zone
    
    echo -e "${Green}规则添加成功,即将开始封禁ip!${Font}"
    
    # 删除已存在的相同iptables规则(如果存在)
    iptables -D INPUT -p tcp -m set --match-set "$GEOIP" src -m multiport --dports $START_PORT:$END_PORT -j DROP 2>/dev/null
    iptables -D INPUT -p udp -m set --match-set "$GEOIP" src -m multiport --dports $START_PORT:$END_PORT -j DROP 2>/dev/null
    
    # 添加新规则
    iptables -I INPUT -p tcp -m set --match-set "$GEOIP" src -m multiport --dports $START_PORT:$END_PORT -j DROP
    iptables -I INPUT -p udp -m set --match-set "$GEOIP" src -m multiport --dports $START_PORT:$END_PORT -j DROP
    
    echo -e "${Green}所指定国家($GEOIP)的ip在端口范围${START_PORT}-${END_PORT}内已封禁!${Font}"
}

# 执行封禁
block_ipset

2.给脚本添加执行权限

   sudo chmod +x /usr/local/bin/block_ip.sh

3.创建一个系统服务文件

   sudo vim /etc/systemd/system/block-ip.service 

输入以下内容

[Unit]
Description=Block IPs Service
After=network.target

[Service]
Type=oneshot
ExecStart=/usr/local/bin/block_ip.sh
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target

4.启用服务

sudo systemctl daemon-reload
sudo systemctl enable block-ip.service
sudo systemctl start block-ip.service
  • alipay_img
  • wechat_img
公众号:享生活爱羊毛
最后更新于 2025-04-27