Linux服务器 屏蔽国外IP访问亲测可用

程序猿 2023-02-09 15:24:50 932浏览 加载中

通过ssh远程登录服务器内,运行如下命令语句获取国内IP网段,会保存为/root/china_ssr.txt

wget -q --timeout=60 -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)) }' > /root/china_ssr.txt

将下面脚本保存为/root/allcn.sh ,并设置可执行权限( 命令: chmod +x  allcn.sh)

mmode=$1

CNIP="/root/china_ssr.txt"

gen_iplist() {
        cat <<-EOF
                $(cat ${CNIP:=/dev/null} 2>/dev/null)
EOF
}

flush_r() {
iptables  -F ALLCNRULE 2>/dev/null
iptables -D INPUT -p tcp -j ALLCNRULE 2>/dev/null
iptables  -X ALLCNRULE 2>/dev/null
ipset -X allcn 2>/dev/null
}

mstart() {
ipset create allcn hash:net 2>/dev/null
ipset -! -R <<-EOF 
$(gen_iplist | sed -e "s/^/add allcn /")
EOF

iptables -N ALLCNRULE 
iptables -I INPUT -p tcp -j ALLCNRULE 
iptables -A ALLCNRULE -s 127.0.0.0/8 -j RETURN
iptables -A ALLCNRULE -s 169.254.0.0/16 -j RETURN
iptables -A ALLCNRULE -s 224.0.0.0/4 -j RETURN
iptables -A ALLCNRULE -s 255.255.255.255 -j RETURN
iptables -A ALLCNRULE -m set --match-set allcn  src -j RETURN 
iptables -A ALLCNRULE -p tcp -j DROP 
}
if [ "$mmode" == "stop" ] ;then
flush_r
exit 0
fi
flush_r
sleep 1
mstart

执行如下命令将开始拦截

/root/allcn.sh

执行如下命令即可停止拦截

/root/allcn.sh stop

标签:
最后修改:2024-05-02 06:17:56

非特殊说明,本博所有文章均为博主原创。