Ubuntu只允许中国IPv4进行访问

本文简单写几行命令,作为自己的备忘。实现效果为:22端口全网可通,其他端口仅允许中国IP访问。

1、安装 IPSet

apt update && apt install ipset -y

2、新建 /opt/chnroute/chnroute.sh

mkdir /opt/chnroute/ && vim /opt/chnroute/chnroute.sh

3、写入chnroute.sh,主要功能为获取中国IPv4并写入ipset

#!/bin/bash
ipset create chnroute hash:net maxelem 65536
wget --no-check-certificate -O- 'http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest'| awk -F\| '/CN\|ipv4/ { printf("%s/%d\n", $4, 32-log($5)/log(2)) }'>/opt/chnroute/chnroute.txt
ipset flush chnroute
while read ip;do
 ipset add chnroute $ip
done</opt/chnroute/chnroute.txt
ipset save chnroute >/opt/chnroute/chnroute.conf

4、对 /opt/chnroute/chnroute.sh 授权并执行

chmod +x /opt/chnroute/chnroute.sh && /opt/chnroute/chnroute.sh

5、写入iptables规则

iptables -F
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -m set --match-set chnroute src -p tcp -j ACCEPT
iptables -A INPUT -m set --match-set chnroute src -p udp -j ACCEPT
iptables -A INPUT -p tcp -j DROP
iptables -A INPUT -p udp -j DROP
iptables -P INPUT DROP