# Firewalld使用ipset快速屏蔽指定国家的IP访问

ipset是iptables的扩展，它允许你创建匹配整个IP地址集合的规则。可以快速的让我们屏蔽某个IP段。这里分享个屏蔽指定国家访问的方法，有时候还可以有效的帮网站阻挡下攻击。

更多参考: <https://datacadamia.com/os/linux/firewalld>

### 方法

首先需要得到国家IP段，下载地址：[http://www.ipdeny.com/ipblocks/](https://www.ipdeny.com/ipblocks/) 这里以我们国家为例。

### 1.安装ipset

```bash
yum -y install ipset
```

### 2.创建规则

```bash
#创建一个名为cnblocks的规则
ipset -N cnblocks hash:net
#下载国家IP段到当前目录
wget -P . http://www.ipdeny.com/ipblocks/data/countries/cn.zone
#将IP段添加到cnblocks规则中(firewalld)
for i in $(cat /root/cn.zone ); firewall-cmd --permanent --ipset=cnblocks --add-entry=$i; done

```

> CentOS7中自带的是firewalld,添加到规则中时用上面这条命令 如果你换成了iptables,那就用下面这条命令

```bash
#将IP段添加到cnblocks规则中(iptables)
for i in $(cat /root/cn.zone ); do ipset -A cnblocks $i; done
```

### 3.开始屏蔽

```bash
#firewalld
firewall-cmd --permanent --add-rich-rule='rule family=ipv4 source ipset=cnblocks drop'
firewall-cmd --reload
 
#iptables
iptables -I INPUT -p tcp -m set --match-set cnblocks src -j DROP
service iptables save
```

### 4.解除屏蔽

```bash
#firewalld
firewall-cmd --permanent --remove-rich-rule='rule family=ipv4 source ipset=cnblocks drop'
firewall-cmd --permanent --delete-ipset=cnblocks
firewall-cmd --reload
 
#iptables
iptables -D INPUT -p tcp -m set --match-set cnblocks src -j DROP
ipset destroy cnblocks
service iptables save

```

## 或者

1. 新建ipset

   ```bash
   firewall-cmd --permanent --new-ipset=blacklist --type=hash:net --option=family=inet --option=hashsize=4096 --option=maxelem=200000
   ```
2. 下载 ip段文件

   ```bash
   wget http://www.ipdeny.com/ipblocks/data/countries/all-zones.tar.gz
   tar -vxzf all-zones.tar.gz
   ```
3. 将你想屏蔽的国家加入ipset集合中

   ```bash
   firewall-cmd --permanent --ipset=blacklist --add-entries-from-file=./gr.zone
   ```
4. 将blacklist集合 定向到 drop区域

   ```bash
   firewall-cmd --permanent --zone=drop --add-source=ipset:blacklist
   ```
5. 生效

   ```
   firewall-cmd --reload
   ```
6. 手动添加ip进入blacklist

   ```bash
   firewall-cmd --permanent --ipset=blacklist --add-entry=IP地址
   firewall-cmd --reload
   ```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://close.gitbook.io/yun-wei-bi-ji/centos/iptable/firewalld-shi-yong-ipset-kuai-su-ping-bi-zhi-ding-guo-jia-de-ip-fang-wen.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
