服务器设置ip黑白名单限制访问

各个国家地区IP地址范围查询: IPdeny (opens new window),IPtoasn (opens new window),Country IP Blocks (opens new window),ip2location (opens new window),

国内各个地区IP地址范围查询:╃苍狼山庄╃ (opens new window),ip.cn (opens new window)纯真 (opens new window)

# Firewalld防火墙设置

利用firewall-cmd对ipset进行操作

ipset的存储路径:/etc/firewalld/ipsets

<只允许中国的IP访问> 脚本

#!/bin/bash
directory=$(
    cd $(dirname $0)
    pwd
)/cn_$(date +"%Y%m%d%H%M%S")
mkdir ${directory} && cp diy.zone ${directory} && cd ${directory}
wget -c http://www.ipdeny.com/ipblocks/data/countries/cn.zone

echo '<?xml version="1.0" encoding="utf-8"?>' >>whitelist.xml
echo '<ipset type="hash:net">' >>whitelist.xml
echo '  <option name="maxelem" value="300000"/>' >>whitelist.xml

for i in $(ls *.zone); do
    cat ${i} | while read line; do
        echo "  <entry>${line}</entry>" >>whitelist.xml
    done
done
echo '</ipset>' >>whitelist.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

然后复制whitelist.xml/etc/firewalld/ipsets

firewall-cmd --permanent --new-ipset-from-file=whitelist.xml --name=whitelist
firewall-cmd --permanent --add-rich-rule 'rule family="ipv4" source ipset="whitelist" port port=22 protocol=tcp accept'
firewall-cmd --permanent --add-rich-rule 'rule family="ipv4" source ipset="whitelist" port port=9000-9100 protocol=udp accept'
firewall-cmd --reload
1
2
3
4

更多规则策略命令参考:linux(centos8):firewalld使用ipset管理ip地址的集合 (opens new window)

# iptables防火墙设置

也是利用ipset进行操作 可参考链接 (opens new window),更多详细链接 (opens new window)

# 参考链接

YangQing1989/firewalld (opens new window)

linux(centos8):firewalld使用ipset管理ip地址的集合 (opens new window)