Shell script implementation prevents foreign IP from accessing the server

Time:2022-8-3

According to the customer’s requirements, I don’t want foreign IP to access the server. I originally wanted to let the computer room route at the upper end, but those people don’t bird you~~~~
In this case, you can only solve it with iptables~~~~~~~~~
You can go to the IP library http://www.ipdeny.com/ipblocks/ Download, here are the ~ ~ ~

Copy codeThe code is as follows:
#Download IP library
#wget http://rfyiamcool.googlecode.com/files/allip.txt
wget http://www.ipdeny.com/ipblocks/data/countries/cn.zone
#Remove the semicolon
sed -i ‘s/;$//’ allip.txt
#Call out the IP terminal
for i in `cat cn.zone`
do
echo “iptables -A INPUT -s $i -j ACCEPT” >>iptables.sh
done
cat iptables.sh

Optimize this script and add the following command in front of iptables.sh!

Copy codeThe code is as follows:
#!/bin/bash
ziji=”222.173.13.5″
iptables -F
iptables -X
iptables -Z
iptables -t nat -F
iptables -t mangle -F
modprobe iptable_nat
modprobe ip_nat_ftp
modprobe ip_nat_irc
modprobe ip_conntrack
modprobe ip_conntrack_ftp
modprobe ip_conntrack_irc
modprobe ipt_limit
modprobe ipt_recent ip_list_tot=16384
modprobe ip_conntrack hashsize=16384
echo “1024  63000” > /proc/sys/net/ipv4/ip_local_port_range
echo “1” > /proc/sys/net/ipv4/tcp_tw_recycle
echo “1” > /proc/sys/net/ipv4/tcp_tw_reuse
echo “1” > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts
echo “1” >/proc/sys/net/ipv4/conf/all/log_martians
echo “1” >/proc/sys/net/ipv4/tcp_syncookies
echo “2” >/proc/sys/net/ipv4/tcp_synack_retries
echo “5000” >/proc/sys/net/ipv4/tcp_max_syn_backlog
echo “3” >/proc/sys/net/ipv4/tcp_syn_retries
echo “1” > /proc/sys/net/ipv4/tcp_tw_reuse
echo “1” > /proc/sys/net/ipv4/tcp_tw_recycle
echo “30” > /proc/sys/net/ipv4/tcp_fin_timeout
echo “1800” > /proc/sys/net/ipv4/tcp_keepalive_time
echo “1” > /proc/sys/net/ipv4/ip_forward
iptables -P INPUT DROP
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
/sbin/iptables -t nat -P PREROUTING ACCEPT
/sbin/iptables -t nat -P POSTROUTING ACCEPT
iptables -A INPUT -s $ziji -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m state –state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp ! –syn -m state –state NEW -j DROP

The following is the effect picture ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ (just shut down the host, and you can’t Ping it in China o (∩ _8745;) o~)