banner
Bai

Bai

写代码菜的一批 🤣
twitter
telegram
tg_channel
pixiv
github
bilibili
whatsapp

Server blocks foreign IP addresses

To remotely log in to a cloud server via SSH, run the following command to obtain the domestic IP range, and save it as /root/china_ip.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_ip.txt

Save the following script as /root/allcn.sh

mmode=$1
CNIP="/root/china_ip.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

Make the script executable by running the following command:

chmod +x  allcn.sh

To start blocking foreign IP access, run the following command:

/root/allcn.sh

To stop blocking foreign IP access, run the following command:

/root/allcn.sh stop
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.