Hot Article
- Centos7 closes and restarts the system firewall and opens firewall ports
- How IID server uses Xshell to connect to Linux (centos) server
- BT panel forgets the background login URL, and the solution to the security entrance verification failure
- The php domain name points to ip, how to use the specified ip address to access a server in the url request domain name in curl mode
- How to purchase a dedicated server
- Error connecting to MySQL: Cant connect to MySQL server (10060)
How to block foreign IP access on Linux server?
- Author:Benson
- Category:Server Maintain
- Release Time:2022-11-03
Log in to the Linux cloud server remotely through SSH, and run the following command statement to obtain the domestic IP network segment, which will be saved 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 script below 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.
chmod +x allcn.sh
Execute the following command to start blocking foreign IP access.
/root/allcn.sh
Execute the following command to stop blocking foreign IP access.
/root/allcn.sh stop
related topic
- What to do if a cp: omitting directory error occurs in Linux (detailed solution)
- IDGlobal teaches you how to set up root remote login in Ubuntu SSH
- How to change the password of Windows server 2008 server?
- Expand the root directory space of the CentOS system, and expand the home directory space to the root directory
- centos7 open and close 80 port tutorial
- linux how to change the user password (linux command to change the password)