利用 iptable + ipset 封鎖大量 IP

利用 iptable + ipset 封鎖大量 IP

安裝 ipset

yum install ipset

新增規則配宜置檔 : block_ip => 以 ip 型式的黑名單

ipset create block_ip hash:ip hashsize 4096

說明 : hash:ip 即是設定為 ip 型式

新增規則配宜置檔 : block_net => 以 net 型式的黑名單

ipset create block_net hash:net hashsize 4096

說明 : hash:net 即是設定為 net 型式

新增 ip 到清單

ipset add block_ip 172.245.110.180

新增一網段到清單

ipset add block_net 191.96.249.0/24

新增在 iptable 規則

iptables -I INPUT -m set --match-set block_ip src -j DROP
iptables -I INPUT -m set --match-set block_net src -j DROP

如果是要當白名單 , 在 set 後加一個 ! 即可.

iptables -I INPUT -m set ! --match-set white_net src -j DROP

ipset 說明 :

1.建立一個配置檔

ipset create 名單 hash:型態,Port maxelem 1000000

型態 :  ip 和 net
Port : 指定的 Port (可省略) 前面需加逗號 【,】
maxelem : 預設可以儲存65536個元素,使用maxelem指定數量(可省略)

2.檢視已建立的 ipset

ipset list
ipset list 名單

3.加入名單內

ipset add 名單 ip(net)

3.從名單移除

ipset del 名單 ip(net)

4.將ipset 名單儲存到文件

ipset save 名單 -f  檔名.txt

5.刪除 ipset 規則名單

ipset destroy          #刪除所有名單
ipset destroy 名單     #刪除單一名單

6.匯入 ipset 規則

ipset restore -f 檔名.txt

7.自動過期

ipset add 名單 ip timeout 100

8.重新指定到期時間 , 需加 -exist

ipset -exist add 名單 ip timeout 100

9.清空規則

ipset flush           #清空所有名單
ipset flush 名單      #清空單一名單

參考資料 :
https://fixatom.com/block-ip-with-ipset/
https://tw.saowen.com/a/e1dbc5e061b224c07fffc36ba1ea16861f3a6116dfd2d8ef82e0a07aacde8509